28
29
from bzrlib import (
35
config as _mod_config,
40
39
merge as _mod_merge,
45
43
revision as _mod_revision,
54
50
from bzrlib.branch import Branch
55
51
from bzrlib.conflicts import ConflictList
56
from bzrlib.transport import memory
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
52
from bzrlib.revisionspec import RevisionSpec
58
53
from bzrlib.smtp_connection import SMTPConnection
59
54
from bzrlib.workingtree import WorkingTree
62
from bzrlib.commands import (
64
builtin_command_registry,
67
from bzrlib.option import (
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
77
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
80
return internal_tree_files(file_list, default_branch, canonicalize,
84
def tree_files_for_add(file_list):
86
Return a tree and list of absolute paths from a file list.
88
Similar to tree_files, but add handles files a bit differently, so it a
89
custom implementation. In particular, MutableTreeTree.smart_add expects
90
absolute paths, which it immediately converts to relative paths.
92
# FIXME Would be nice to just return the relative paths like
93
# internal_tree_files does, but there are a large number of unit tests
94
# that assume the current interface to mutabletree.smart_add
96
tree, relpath = WorkingTree.open_containing(file_list[0])
97
if tree.supports_views():
98
view_files = tree.views.lookup_view()
100
for filename in file_list:
101
if not osutils.is_inside_any(view_files, filename):
102
raise errors.FileOutsideView(filename, view_files)
103
file_list = file_list[:]
104
file_list[0] = tree.abspath(relpath)
106
tree = WorkingTree.open_containing(u'.')[0]
107
if tree.supports_views():
108
view_files = tree.views.lookup_view()
110
file_list = view_files
111
view_str = views.view_display_str(view_files)
112
note("Ignoring files outside view. View is %s" % view_str)
113
return tree, file_list
116
def _get_one_revision(command_name, revisions):
117
if revisions is None:
119
if len(revisions) != 1:
120
raise errors.BzrCommandError(
121
'bzr %s --revision takes exactly one revision identifier' % (
126
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
127
"""Get a revision tree. Not suitable for commands that change the tree.
129
Specifically, the basis tree in dirstate trees is coupled to the dirstate
130
and doing a commit/uncommit/pull will at best fail due to changing the
133
If tree is passed in, it should be already locked, for lifetime management
134
of the trees internal cached state.
138
if revisions is None:
140
rev_tree = tree.basis_tree()
142
rev_tree = branch.basis_tree()
144
revision = _get_one_revision(command_name, revisions)
145
rev_tree = revision.as_tree(branch)
57
from bzrlib.commands import Command, display_command
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
59
from bzrlib.trace import mutter, note, warning, is_quiet, info
62
def tree_files(file_list, default_branch=u'.'):
64
return internal_tree_files(file_list, default_branch)
65
except errors.FileInWrongBranch, e:
66
raise errors.BzrCommandError("%s is not in the same branch as %s" %
67
(e.path, file_list[0]))
149
70
# XXX: Bad function name; should possibly also be a class method of
150
71
# WorkingTree rather than a function.
151
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
152
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
72
def internal_tree_files(file_list, default_branch=u'.'):
154
73
"""Convert command-line paths to a WorkingTree and relative paths.
156
Deprecated: use WorkingTree.open_containing_paths instead.
158
75
This is typically used for command-line processors that take one or
159
76
more filenames, and infer the workingtree that contains them.
161
78
The filenames given are not required to exist.
163
:param file_list: Filenames to convert.
80
:param file_list: Filenames to convert.
165
82
:param default_branch: Fallback tree path to use if file_list is empty or
168
:param apply_view: if True and a view is set, apply it or check that
169
specified files are within it
171
85
:return: workingtree, [relative_paths]
173
return WorkingTree.open_containing_paths(
174
file_list, default_directory='.',
179
def _get_view_info_for_change_reporter(tree):
180
"""Get the view information from a tree for change reporting."""
87
if file_list is None or len(file_list) == 0:
88
return WorkingTree.open_containing(default_branch)[0], file_list
89
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
91
for filename in file_list:
93
new_list.append(tree.relpath(osutils.dereference_path(filename)))
94
except errors.PathNotChild:
95
raise errors.FileInWrongBranch(tree.branch, filename)
99
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
100
def get_format_type(typestring):
101
"""Parse and return a format specifier."""
102
# Have to use BzrDirMetaFormat1 directly, so that
103
# RepositoryFormat.set_default_format works
104
if typestring == "default":
105
return bzrdir.BzrDirMetaFormat1()
183
current_view = tree.views.get_view_info()[0]
184
if current_view is not None:
185
view_info = (current_view, tree.views.lookup_view())
186
except errors.ViewsNotSupported:
191
def _open_directory_or_containing_tree_or_branch(filename, directory):
192
"""Open the tree or branch containing the specified file, unless
193
the --directory option is used to specify a different branch."""
194
if directory is not None:
195
return (None, Branch.open(directory), filename)
196
return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
107
return bzrdir.format_registry.make_bzrdir(typestring)
109
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
110
raise errors.BzrCommandError(msg)
199
113
# TODO: Make sure no commands unconditionally use the working directory as a
230
144
Not versioned and not matching an ignore pattern.
232
Additionally for directories, symlinks and files with an executable
233
bit, Bazaar indicates their type using a trailing character: '/', '@'
236
146
To see ignored files use 'bzr ignored'. For details on the
237
147
changes to file texts, use 'bzr diff'.
239
149
Note that --short or -S gives status flags for each item, similar
240
150
to Subversion's status command. To get output similar to svn -q,
243
153
If no arguments are specified, the status of the entire working
244
154
directory is shown. Otherwise, only the status of the specified
245
155
files or directories is reported. If a directory is given, status
246
156
is reported for everything inside that directory.
248
Before merges are committed, the pending merge tip revisions are
249
shown. To see all pending merge revisions, use the -v option.
250
To skip the display of pending merge information altogether, use
251
the no-pending option or specify a file/directory.
253
To compare the working directory to a specific revision, pass a
254
single revision to the revision argument.
256
To see which files have changed in a specific revision, or between
257
two revisions, pass a revision range to the revision argument.
258
This will produce the same results as calling 'bzr diff --summarize'.
158
If a revision argument is given, the status is calculated against
159
that revision, or between two revisions if two are provided.
261
162
# TODO: --no-recurse, --recurse options
263
164
takes_args = ['file*']
264
takes_options = ['show-ids', 'revision', 'change', 'verbose',
165
takes_options = ['show-ids', 'revision', 'change',
265
166
Option('short', help='Use short status indicators.',
267
168
Option('versioned', help='Only show versioned files.',
269
Option('no-pending', help='Don\'t show pending merges.',
272
171
aliases = ['st', 'stat']
274
173
encoding_type = 'replace'
275
174
_see_also = ['diff', 'revert', 'status-flags']
278
177
def run(self, show_ids=False, file_list=None, revision=None, short=False,
279
versioned=False, no_pending=False, verbose=False):
280
179
from bzrlib.status import show_tree_status
282
181
if revision and len(revision) > 2:
283
182
raise errors.BzrCommandError('bzr status --revision takes exactly'
284
183
' one or two revision specifiers')
286
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
287
# Avoid asking for specific files when that is not needed.
288
if relfile_list == ['']:
290
# Don't disable pending merges for full trees other than '.'.
291
if file_list == ['.']:
293
# A specific path within a tree was given.
294
elif relfile_list is not None:
185
tree, file_list = tree_files(file_list)
296
187
show_tree_status(tree, show_ids=show_ids,
297
specific_files=relfile_list, revision=revision,
298
to_file=self.outf, short=short, versioned=versioned,
299
show_pending=(not no_pending), verbose=verbose)
188
specific_files=file_list, revision=revision,
189
to_file=self.outf, short=short, versioned=versioned)
302
192
class cmd_cat_revision(Command):
303
__doc__ = """Write out metadata for a revision.
193
"""Write out metadata for a revision.
305
195
The revision to print can either be specified by a specific
306
196
revision identifier, or you can use --revision.
310
200
takes_args = ['revision_id?']
311
takes_options = ['directory', 'revision']
201
takes_options = ['revision']
312
202
# cat-revision is more for frontends so should be exact
313
203
encoding = 'strict'
315
def print_revision(self, revisions, revid):
316
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
317
record = stream.next()
318
if record.storage_kind == 'absent':
319
raise errors.NoSuchRevision(revisions, revid)
320
revtext = record.get_bytes_as('fulltext')
321
self.outf.write(revtext.decode('utf-8'))
324
def run(self, revision_id=None, revision=None, directory=u'.'):
206
def run(self, revision_id=None, revision=None):
325
207
if revision_id is not None and revision is not None:
326
208
raise errors.BzrCommandError('You can only supply one of'
327
209
' revision_id or --revision')
328
210
if revision_id is None and revision is None:
329
211
raise errors.BzrCommandError('You must supply either'
330
212
' --revision or a revision_id')
332
b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
334
revisions = b.repository.revisions
335
if revisions is None:
336
raise errors.BzrCommandError('Repository %r does not support '
337
'access to raw revision texts')
339
b.repository.lock_read()
341
# TODO: jam 20060112 should cat-revision always output utf-8?
342
if revision_id is not None:
343
revision_id = osutils.safe_revision_id(revision_id, warn=False)
345
self.print_revision(revisions, revision_id)
346
except errors.NoSuchRevision:
347
msg = "The repository %s contains no revision %s." % (
348
b.repository.base, revision_id)
349
raise errors.BzrCommandError(msg)
350
elif revision is not None:
353
raise errors.BzrCommandError(
354
'You cannot specify a NULL revision.')
355
rev_id = rev.as_revision_id(b)
356
self.print_revision(revisions, rev_id)
358
b.repository.unlock()
361
class cmd_dump_btree(Command):
362
__doc__ = """Dump the contents of a btree index file to stdout.
364
PATH is a btree index file, it can be any URL. This includes things like
365
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
367
By default, the tuples stored in the index file will be displayed. With
368
--raw, we will uncompress the pages, but otherwise display the raw bytes
372
# TODO: Do we want to dump the internal nodes as well?
373
# TODO: It would be nice to be able to dump the un-parsed information,
374
# rather than only going through iter_all_entries. However, this is
375
# good enough for a start
377
encoding_type = 'exact'
378
takes_args = ['path']
379
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
380
' rather than the parsed tuples.'),
383
def run(self, path, raw=False):
384
dirname, basename = osutils.split(path)
385
t = transport.get_transport(dirname)
387
self._dump_raw_bytes(t, basename)
389
self._dump_entries(t, basename)
391
def _get_index_and_bytes(self, trans, basename):
392
"""Create a BTreeGraphIndex and raw bytes."""
393
bt = btree_index.BTreeGraphIndex(trans, basename, None)
394
bytes = trans.get_bytes(basename)
395
bt._file = cStringIO.StringIO(bytes)
396
bt._size = len(bytes)
399
def _dump_raw_bytes(self, trans, basename):
402
# We need to parse at least the root node.
403
# This is because the first page of every row starts with an
404
# uncompressed header.
405
bt, bytes = self._get_index_and_bytes(trans, basename)
406
for page_idx, page_start in enumerate(xrange(0, len(bytes),
407
btree_index._PAGE_SIZE)):
408
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
409
page_bytes = bytes[page_start:page_end]
411
self.outf.write('Root node:\n')
412
header_end, data = bt._parse_header_from_bytes(page_bytes)
413
self.outf.write(page_bytes[:header_end])
415
self.outf.write('\nPage %d\n' % (page_idx,))
416
if len(page_bytes) == 0:
417
self.outf.write('(empty)\n');
419
decomp_bytes = zlib.decompress(page_bytes)
420
self.outf.write(decomp_bytes)
421
self.outf.write('\n')
423
def _dump_entries(self, trans, basename):
425
st = trans.stat(basename)
426
except errors.TransportNotPossible:
427
# We can't stat, so we'll fake it because we have to do the 'get()'
429
bt, _ = self._get_index_and_bytes(trans, basename)
431
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
432
for node in bt.iter_all_entries():
433
# Node is made up of:
434
# (index, key, value, [references])
438
refs_as_tuples = None
440
refs_as_tuples = static_tuple.as_tuples(refs)
441
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
442
self.outf.write('%s\n' % (as_tuple,))
213
b = WorkingTree.open_containing(u'.')[0].branch
215
# TODO: jam 20060112 should cat-revision always output utf-8?
216
if revision_id is not None:
217
revision_id = osutils.safe_revision_id(revision_id, warn=False)
218
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
219
elif revision is not None:
222
raise errors.BzrCommandError('You cannot specify a NULL'
224
revno, rev_id = rev.in_history(b)
225
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
445
228
class cmd_remove_tree(Command):
446
__doc__ = """Remove the working tree from a given branch/checkout.
229
"""Remove the working tree from a given branch/checkout.
448
231
Since a lightweight checkout is little more than a working tree
449
232
this will refuse to run against one.
451
234
To re-create the working tree, use "bzr checkout".
453
236
_see_also = ['checkout', 'working-trees']
454
takes_args = ['location*']
457
help='Remove the working tree even if it has '
458
'uncommitted or shelved changes.'),
461
def run(self, location_list, force=False):
462
if not location_list:
465
for location in location_list:
466
d = bzrdir.BzrDir.open(location)
469
working = d.open_workingtree()
470
except errors.NoWorkingTree:
471
raise errors.BzrCommandError("No working tree to remove")
472
except errors.NotLocalUrl:
473
raise errors.BzrCommandError("You cannot remove the working tree"
476
if (working.has_changes()):
477
raise errors.UncommittedChanges(working)
478
if working.get_shelf_manager().last_shelf() is not None:
479
raise errors.ShelvedChanges(working)
481
if working.user_url != working.branch.user_url:
482
raise errors.BzrCommandError("You cannot remove the working tree"
483
" from a lightweight checkout")
485
d.destroy_workingtree()
488
class cmd_repair_workingtree(Command):
489
__doc__ = """Reset the working tree state file.
491
This is not meant to be used normally, but more as a way to recover from
492
filesystem corruption, etc. This rebuilds the working inventory back to a
493
'known good' state. Any new modifications (adding a file, renaming, etc)
494
will be lost, though modified files will still be detected as such.
496
Most users will want something more like "bzr revert" or "bzr update"
497
unless the state file has become corrupted.
499
By default this attempts to recover the current state by looking at the
500
headers of the state file. If the state file is too corrupted to even do
501
that, you can supply --revision to force the state of the tree.
504
takes_options = ['revision', 'directory',
506
help='Reset the tree even if it doesn\'t appear to be'
511
def run(self, revision=None, directory='.', force=False):
512
tree, _ = WorkingTree.open_containing(directory)
513
self.add_cleanup(tree.lock_tree_write().unlock)
517
except errors.BzrError:
518
pass # There seems to be a real error here, so we'll reset
521
raise errors.BzrCommandError(
522
'The tree does not appear to be corrupt. You probably'
523
' want "bzr revert" instead. Use "--force" if you are'
524
' sure you want to reset the working tree.')
528
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
238
takes_args = ['location?']
240
def run(self, location='.'):
241
d = bzrdir.BzrDir.open(location)
530
tree.reset_state(revision_ids)
531
except errors.BzrError, e:
532
if revision_ids is None:
533
extra = (', the header appears corrupt, try passing -r -1'
534
' to set the state to the last commit')
537
raise errors.BzrCommandError('failed to reset the tree state'
244
working = d.open_workingtree()
245
except errors.NoWorkingTree:
246
raise errors.BzrCommandError("No working tree to remove")
247
except errors.NotLocalUrl:
248
raise errors.BzrCommandError("You cannot remove the working tree of a "
251
working_path = working.bzrdir.root_transport.base
252
branch_path = working.branch.bzrdir.root_transport.base
253
if working_path != branch_path:
254
raise errors.BzrCommandError("You cannot remove the working tree from "
255
"a lightweight checkout")
257
d.destroy_workingtree()
541
260
class cmd_revno(Command):
542
__doc__ = """Show current revision number.
261
"""Show current revision number.
544
263
This is equal to the number of revisions on this branch.
547
266
_see_also = ['info']
548
267
takes_args = ['location?']
550
Option('tree', help='Show revno of working tree'),
554
def run(self, tree=False, location=u'.'):
557
wt = WorkingTree.open_containing(location)[0]
558
self.add_cleanup(wt.lock_read().unlock)
559
except (errors.NoWorkingTree, errors.NotLocalUrl):
560
raise errors.NoWorkingTree(location)
561
revid = wt.last_revision()
563
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
564
except errors.NoSuchRevision:
566
revno = ".".join(str(n) for n in revno_t)
568
b = Branch.open_containing(location)[0]
569
self.add_cleanup(b.lock_read().unlock)
572
self.outf.write(str(revno) + '\n')
270
def run(self, location=u'.'):
271
self.outf.write(str(Branch.open_containing(location)[0].revno()))
272
self.outf.write('\n')
575
275
class cmd_revision_info(Command):
576
__doc__ = """Show revision number and revision id for a given revision identifier.
276
"""Show revision number and revision id for a given revision identifier.
579
279
takes_args = ['revision_info*']
582
custom_help('directory',
583
help='Branch to examine, '
584
'rather than the one containing the working directory.'),
585
Option('tree', help='Show revno of working tree'),
280
takes_options = ['revision']
589
def run(self, revision=None, directory=u'.', tree=False,
590
revision_info_list=[]):
283
def run(self, revision=None, revision_info_list=[]):
593
wt = WorkingTree.open_containing(directory)[0]
595
self.add_cleanup(wt.lock_read().unlock)
596
except (errors.NoWorkingTree, errors.NotLocalUrl):
598
b = Branch.open_containing(directory)[0]
599
self.add_cleanup(b.lock_read().unlock)
601
286
if revision is not None:
602
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
287
revs.extend(revision)
603
288
if revision_info_list is not None:
604
for rev_str in revision_info_list:
605
rev_spec = RevisionSpec.from_string(rev_str)
606
revision_ids.append(rev_spec.as_revision_id(b))
607
# No arguments supplied, default to the last revision
608
if len(revision_ids) == 0:
611
raise errors.NoWorkingTree(directory)
612
revision_ids.append(wt.last_revision())
289
for rev in revision_info_list:
290
revs.append(RevisionSpec.from_string(rev))
292
b = Branch.open_containing(u'.')[0]
295
revs.append(RevisionSpec.from_string('-1'))
298
revinfo = rev.in_history(b)
299
if revinfo.revno is None:
300
dotted_map = b.get_revision_id_to_revno_map()
301
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
302
print '%s %s' % (revno, revinfo.rev_id)
614
revision_ids.append(b.last_revision())
618
for revision_id in revision_ids:
620
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
621
revno = '.'.join(str(i) for i in dotted_revno)
622
except errors.NoSuchRevision:
624
maxlen = max(maxlen, len(revno))
625
revinfos.append([revno, revision_id])
629
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
304
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
632
307
class cmd_add(Command):
633
__doc__ = """Add specified files or directories.
308
"""Add specified files or directories.
635
310
In non-recursive mode, all the named items are added, regardless
636
311
of whether they were previously ignored. A warning is given if
834
523
takes_args = ['names*']
835
524
takes_options = [Option("after", help="Move only the bzr identifier"
836
525
" of the file, because the file has already been moved."),
837
Option('auto', help='Automatically guess renames.'),
838
Option('dry-run', help='Avoid making changes when guessing renames.'),
840
527
aliases = ['move', 'rename']
841
528
encoding_type = 'replace'
843
def run(self, names_list, after=False, auto=False, dry_run=False):
845
return self.run_auto(names_list, after, dry_run)
847
raise errors.BzrCommandError('--dry-run requires --auto.')
530
def run(self, names_list, after=False):
848
531
if names_list is None:
850
534
if len(names_list) < 2:
851
535
raise errors.BzrCommandError("missing file argument")
852
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
853
self.add_cleanup(tree.lock_tree_write().unlock)
854
self._run(tree, names_list, rel_names, after)
856
def run_auto(self, names_list, after, dry_run):
857
if names_list is not None and len(names_list) > 1:
858
raise errors.BzrCommandError('Only one path may be specified to'
861
raise errors.BzrCommandError('--after cannot be specified with'
863
work_tree, file_list = WorkingTree.open_containing_paths(
864
names_list, default_directory='.')
865
self.add_cleanup(work_tree.lock_tree_write().unlock)
866
rename_map.RenameMap.guess_renames(work_tree, dry_run)
868
def _run(self, tree, names_list, rel_names, after):
869
into_existing = osutils.isdir(names_list[-1])
870
if into_existing and len(names_list) == 2:
872
# a. case-insensitive filesystem and change case of dir
873
# b. move directory after the fact (if the source used to be
874
# a directory, but now doesn't exist in the working tree
875
# and the target is an existing directory, just rename it)
876
if (not tree.case_sensitive
877
and rel_names[0].lower() == rel_names[1].lower()):
878
into_existing = False
881
# 'fix' the case of a potential 'from'
882
from_id = tree.path2id(
883
tree.get_canonical_inventory_path(rel_names[0]))
884
if (not osutils.lexists(names_list[0]) and
885
from_id and inv.get_file_kind(from_id) == "directory"):
886
into_existing = False
536
tree, rel_names = tree_files(names_list)
538
if os.path.isdir(names_list[-1]):
889
539
# move into existing directory
890
# All entries reference existing inventory items, so fix them up
891
# for cicp file-systems.
892
rel_names = tree.get_canonical_inventory_paths(rel_names)
893
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
895
self.outf.write("%s => %s\n" % (src, dest))
540
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
541
self.outf.write("%s => %s\n" % pair)
897
543
if len(names_list) != 2:
898
544
raise errors.BzrCommandError('to mv multiple files the'
899
545
' destination must be a versioned'
902
# for cicp file-systems: the src references an existing inventory
904
src = tree.get_canonical_inventory_path(rel_names[0])
905
# Find the canonical version of the destination: In all cases, the
906
# parent of the target must be in the inventory, so we fetch the
907
# canonical version from there (we do not always *use* the
908
# canonicalized tail portion - we may be attempting to rename the
910
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
911
dest_parent = osutils.dirname(canon_dest)
912
spec_tail = osutils.basename(rel_names[1])
913
# For a CICP file-system, we need to avoid creating 2 inventory
914
# entries that differ only by case. So regardless of the case
915
# we *want* to use (ie, specified by the user or the file-system),
916
# we must always choose to use the case of any existing inventory
917
# items. The only exception to this is when we are attempting a
918
# case-only rename (ie, canonical versions of src and dest are
920
dest_id = tree.path2id(canon_dest)
921
if dest_id is None or tree.path2id(src) == dest_id:
922
# No existing item we care about, so work out what case we
923
# are actually going to use.
925
# If 'after' is specified, the tail must refer to a file on disk.
927
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
929
# pathjoin with an empty tail adds a slash, which breaks
931
dest_parent_fq = tree.basedir
933
dest_tail = osutils.canonical_relpath(
935
osutils.pathjoin(dest_parent_fq, spec_tail))
937
# not 'after', so case as specified is used
938
dest_tail = spec_tail
940
# Use the existing item so 'mv' fails with AlreadyVersioned.
941
dest_tail = os.path.basename(canon_dest)
942
dest = osutils.pathjoin(dest_parent, dest_tail)
943
mutter("attempting to move %s => %s", src, dest)
944
tree.rename_one(src, dest, after=after)
946
self.outf.write("%s => %s\n" % (src, dest))
547
tree.rename_one(rel_names[0], rel_names[1], after=after)
548
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
949
551
class cmd_pull(Command):
950
__doc__ = """Turn this branch into a mirror of another branch.
552
"""Turn this branch into a mirror of another branch.
952
By default, this command only works on branches that have not diverged.
953
Branches are considered diverged if the destination branch's most recent
954
commit is one that has not been merged (directly or indirectly) into the
554
This command only works on branches that have not diverged. Branches are
555
considered diverged if the destination branch's most recent commit is one
556
that has not been merged (directly or indirectly) into the parent.
957
558
If branches have diverged, you can use 'bzr merge' to integrate the changes
958
559
from one into the other. Once one branch has merged, the other should
959
560
be able to pull it again.
961
If you want to replace your local changes and just want your branch to
962
match the remote one, use pull --overwrite. This will work even if the two
963
branches have diverged.
562
If you want to forget your local changes and just update your branch to
563
match the remote one, use pull --overwrite.
965
565
If there is no default location set, the first pull will set it. After
966
566
that, you can omit the location to use the default. To change the
967
567
default, use --remember. The value will only be saved if the remote
968
568
location can be accessed.
970
Note: The location can be specified either in the form of a branch,
971
or in the form of a path to a file containing a merge directive generated
975
_see_also = ['push', 'update', 'status-flags', 'send']
571
_see_also = ['push', 'update', 'status-flags']
976
572
takes_options = ['remember', 'overwrite', 'revision',
977
573
custom_help('verbose',
978
574
help='Show logs of pulled revisions.'),
979
custom_help('directory',
980
576
help='Branch to pull into, '
981
'rather than the one containing the working directory.'),
983
help="Perform a local pull in a bound "
984
"branch. Local pulls are not applied to "
577
'rather than the one containing the working directory.',
988
help="Show base revision text in conflicts.")
990
582
takes_args = ['location?']
991
583
encoding_type = 'replace'
993
585
def run(self, location=None, remember=False, overwrite=False,
994
586
revision=None, verbose=False,
995
directory=None, local=False,
997
588
# FIXME: too much stuff is in the command class
998
589
revision_id = None
1107
683
_see_also = ['pull', 'update', 'working-trees']
1108
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
684
takes_options = ['remember', 'overwrite', 'verbose',
1109
685
Option('create-prefix',
1110
686
help='Create the path leading up to the branch '
1111
687
'if it does not already exist.'),
1112
custom_help('directory',
1113
689
help='Branch to push from, '
1114
'rather than the one containing the working directory.'),
690
'rather than the one containing the working directory.',
1115
694
Option('use-existing-dir',
1116
695
help='By default push will fail if the target'
1117
696
' directory exists, but does not already'
1118
697
' have a control directory. This flag will'
1119
698
' allow push to proceed.'),
1121
help='Create a stacked branch that references the public location '
1122
'of the parent branch.'),
1123
Option('stacked-on',
1124
help='Create a stacked branch that refers to another branch '
1125
'for the commit history. Only the work not present in the '
1126
'referenced branch is included in the branch created.',
1129
help='Refuse to push if there are uncommitted changes in'
1130
' the working tree, --no-strict disables the check.'),
1132
help="Don't populate the working tree, even for protocols"
1133
" that support it."),
1135
700
takes_args = ['location?']
1136
701
encoding_type = 'replace'
1138
703
def run(self, location=None, remember=False, overwrite=False,
1139
create_prefix=False, verbose=False, revision=None,
1140
use_existing_dir=False, directory=None, stacked_on=None,
1141
stacked=False, strict=None, no_tree=False):
1142
from bzrlib.push import _show_push_branch
704
create_prefix=False, verbose=False,
705
use_existing_dir=False,
707
# FIXME: Way too big! Put this into a function called from the
1144
709
if directory is None:
1146
# Get the source branch
1148
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1149
# Get the tip's revision_id
1150
revision = _get_one_revision('push', revision)
1151
if revision is not None:
1152
revision_id = revision.in_history(br_from).rev_id
1155
if tree is not None and revision_id is None:
1156
tree.check_changed_or_out_of_date(
1157
strict, 'push_strict',
1158
more_error='Use --no-strict to force the push.',
1159
more_warning='Uncommitted changes will not be pushed.')
1160
# Get the stacked_on branch, if any
1161
if stacked_on is not None:
1162
stacked_on = urlutils.normalize_url(stacked_on)
1164
parent_url = br_from.get_parent()
1166
parent = Branch.open(parent_url)
1167
stacked_on = parent.get_public_branch()
1169
# I considered excluding non-http url's here, thus forcing
1170
# 'public' branches only, but that only works for some
1171
# users, so it's best to just depend on the user spotting an
1172
# error by the feedback given to them. RBC 20080227.
1173
stacked_on = parent_url
1175
raise errors.BzrCommandError(
1176
"Could not determine branch to refer to.")
1178
# Get the destination location
711
br_from = Branch.open_containing(directory)[0]
712
stored_loc = br_from.get_push_location()
1179
713
if location is None:
1180
stored_loc = br_from.get_push_location()
1181
714
if stored_loc is None:
1182
raise errors.BzrCommandError(
1183
"No push location known or specified.")
715
raise errors.BzrCommandError("No push location known or specified.")
1185
717
display_url = urlutils.unescape_for_display(stored_loc,
1186
718
self.outf.encoding)
1187
self.outf.write("Using saved push location: %s\n" % display_url)
719
self.outf.write("Using saved location: %s\n" % display_url)
1188
720
location = stored_loc
1190
_show_push_branch(br_from, revision_id, location, self.outf,
1191
verbose=verbose, overwrite=overwrite, remember=remember,
1192
stacked_on=stacked_on, create_prefix=create_prefix,
1193
use_existing_dir=use_existing_dir, no_tree=no_tree)
722
to_transport = transport.get_transport(location)
724
br_to = repository_to = dir_to = None
726
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
727
except errors.NotBranchError:
728
pass # Didn't find anything
730
# If we can open a branch, use its direct repository, otherwise see
731
# if there is a repository without a branch.
733
br_to = dir_to.open_branch()
734
except errors.NotBranchError:
735
# Didn't find a branch, can we find a repository?
737
repository_to = dir_to.find_repository()
738
except errors.NoRepositoryPresent:
741
# Found a branch, so we must have found a repository
742
repository_to = br_to.repository
747
# The destination doesn't exist; create it.
748
# XXX: Refactor the create_prefix/no_create_prefix code into a
749
# common helper function
751
to_transport.mkdir('.')
752
except errors.FileExists:
753
if not use_existing_dir:
754
raise errors.BzrCommandError("Target directory %s"
755
" already exists, but does not have a valid .bzr"
756
" directory. Supply --use-existing-dir to push"
757
" there anyway." % location)
758
except errors.NoSuchFile:
759
if not create_prefix:
760
raise errors.BzrCommandError("Parent directory of %s"
762
"\nYou may supply --create-prefix to create all"
763
" leading parent directories."
765
_create_prefix(to_transport)
767
# Now the target directory exists, but doesn't have a .bzr
768
# directory. So we need to create it, along with any work to create
769
# all of the dependent branches, etc.
770
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
771
revision_id=br_from.last_revision())
772
br_to = dir_to.open_branch()
773
# TODO: Some more useful message about what was copied
774
note('Created new branch.')
775
# We successfully created the target, remember it
776
if br_from.get_push_location() is None or remember:
777
br_from.set_push_location(br_to.base)
778
elif repository_to is None:
779
# we have a bzrdir but no branch or repository
780
# XXX: Figure out what to do other than complain.
781
raise errors.BzrCommandError("At %s you have a valid .bzr control"
782
" directory, but not a branch or repository. This is an"
783
" unsupported configuration. Please move the target directory"
784
" out of the way and try again."
787
# We have a repository but no branch, copy the revisions, and then
789
last_revision_id = br_from.last_revision()
790
repository_to.fetch(br_from.repository,
791
revision_id=last_revision_id)
792
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
793
note('Created new branch.')
794
if br_from.get_push_location() is None or remember:
795
br_from.set_push_location(br_to.base)
796
else: # We have a valid to branch
797
# We were able to connect to the remote location, so remember it
798
# we don't need to successfully push because of possible divergence.
799
if br_from.get_push_location() is None or remember:
800
br_from.set_push_location(br_to.base)
802
old_rh = br_to.revision_history()
805
tree_to = dir_to.open_workingtree()
806
except errors.NotLocalUrl:
807
warning("This transport does not update the working "
808
"tree of: %s. See 'bzr help working-trees' for "
809
"more information." % br_to.base)
810
push_result = br_from.push(br_to, overwrite)
811
except errors.NoWorkingTree:
812
push_result = br_from.push(br_to, overwrite)
816
push_result = br_from.push(tree_to.branch, overwrite)
820
except errors.DivergedBranches:
821
raise errors.BzrCommandError('These branches have diverged.'
822
' Try using "merge" and then "push".')
823
if push_result is not None:
824
push_result.report(self.outf)
826
new_rh = br_to.revision_history()
829
from bzrlib.log import show_changed_revisions
830
show_changed_revisions(br_to, old_rh, new_rh,
833
# we probably did a clone rather than a push, so a message was
1196
838
class cmd_branch(Command):
1197
__doc__ = """Create a new branch that is a copy of an existing branch.
839
"""Create a new copy of a branch.
1199
841
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1200
842
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1206
848
To retrieve the branch as of a particular revision, supply the --revision
1207
849
parameter, as in "branch foo/bar -r 5".
1209
The synonyms 'clone' and 'get' for this command are deprecated.
1212
852
_see_also = ['checkout']
1213
853
takes_args = ['from_location', 'to_location?']
1214
takes_options = ['revision',
1215
Option('hardlink', help='Hard-link working tree files where possible.'),
1216
Option('files-from', type=str,
1217
help="Get file contents from this tree."),
1219
help="Create a branch without a working-tree."),
1221
help="Switch the checkout in the current directory "
1222
"to the new branch."),
1224
help='Create a stacked branch referring to the source branch. '
1225
'The new branch will depend on the availability of the source '
1226
'branch for all operations.'),
1227
Option('standalone',
1228
help='Do not use a shared repository, even if available.'),
1229
Option('use-existing-dir',
1230
help='By default branch will fail if the target'
1231
' directory exists, but does not already'
1232
' have a control directory. This flag will'
1233
' allow branch to proceed.'),
1235
help="Bind new branch to from location."),
854
takes_options = ['revision']
1237
855
aliases = ['get', 'clone']
1239
def run(self, from_location, to_location=None, revision=None,
1240
hardlink=False, stacked=False, standalone=False, no_tree=False,
1241
use_existing_dir=False, switch=False, bind=False,
1243
from bzrlib import switch as _mod_switch
857
def run(self, from_location, to_location=None, revision=None):
1244
858
from bzrlib.tag import _merge_tags_if_possible
1245
if self.invoked_as in ['get', 'clone']:
1246
ui.ui_factory.show_user_warning(
1247
'deprecated_command',
1248
deprecated_name=self.invoked_as,
1249
recommended_name='branch',
1250
deprecated_in_version='2.4')
1251
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1253
if not (hardlink or files_from):
1254
# accelerator_tree is usually slower because you have to read N
1255
# files (no readahead, lots of seeks, etc), but allow the user to
1256
# explicitly request it
1257
accelerator_tree = None
1258
if files_from is not None and files_from != from_location:
1259
accelerator_tree = WorkingTree.open(files_from)
1260
revision = _get_one_revision('branch', revision)
1261
self.add_cleanup(br_from.lock_read().unlock)
1262
if revision is not None:
1263
revision_id = revision.as_revision_id(br_from)
1265
# FIXME - wt.last_revision, fallback to branch, fall back to
1266
# None or perhaps NULL_REVISION to mean copy nothing
1268
revision_id = br_from.last_revision()
1269
if to_location is None:
1270
to_location = urlutils.derive_to_location(from_location)
1271
to_transport = transport.get_transport(to_location)
1273
to_transport.mkdir('.')
1274
except errors.FileExists:
1275
if not use_existing_dir:
1276
raise errors.BzrCommandError('Target directory "%s" '
1277
'already exists.' % to_location)
1280
bzrdir.BzrDir.open_from_transport(to_transport)
1281
except errors.NotBranchError:
1284
raise errors.AlreadyBranchError(to_location)
1285
except errors.NoSuchFile:
1286
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1289
# preserve whatever source format we have.
1290
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1291
possible_transports=[to_transport],
1292
accelerator_tree=accelerator_tree,
1293
hardlink=hardlink, stacked=stacked,
1294
force_new_repo=standalone,
1295
create_tree_if_local=not no_tree,
1296
source_branch=br_from)
1297
branch = dir.open_branch()
1298
except errors.NoSuchRevision:
1299
to_transport.delete_tree('.')
1300
msg = "The branch %s has no revision %s." % (from_location,
1302
raise errors.BzrCommandError(msg)
1303
_merge_tags_if_possible(br_from, branch)
1304
# If the source branch is stacked, the new branch may
1305
# be stacked whether we asked for that explicitly or not.
1306
# We therefore need a try/except here and not just 'if stacked:'
1308
note('Created new stacked branch referring to %s.' %
1309
branch.get_stacked_on_url())
1310
except (errors.NotStacked, errors.UnstackableBranchFormat,
1311
errors.UnstackableRepositoryFormat), e:
861
elif len(revision) > 1:
862
raise errors.BzrCommandError(
863
'bzr branch --revision takes exactly 1 revision value')
865
br_from = Branch.open(from_location)
868
if len(revision) == 1 and revision[0] is not None:
869
revision_id = revision[0].in_history(br_from)[1]
871
# FIXME - wt.last_revision, fallback to branch, fall back to
872
# None or perhaps NULL_REVISION to mean copy nothing
874
revision_id = br_from.last_revision()
875
if to_location is None:
876
to_location = urlutils.derive_to_location(from_location)
879
name = os.path.basename(to_location) + '\n'
881
to_transport = transport.get_transport(to_location)
883
to_transport.mkdir('.')
884
except errors.FileExists:
885
raise errors.BzrCommandError('Target directory "%s" already'
886
' exists.' % to_location)
887
except errors.NoSuchFile:
888
raise errors.BzrCommandError('Parent of "%s" does not exist.'
891
# preserve whatever source format we have.
892
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
893
possible_transports=[to_transport])
894
branch = dir.open_branch()
895
except errors.NoSuchRevision:
896
to_transport.delete_tree('.')
897
msg = "The branch %s has no revision %s." % (from_location, revision[0])
898
raise errors.BzrCommandError(msg)
900
branch.control_files.put_utf8('branch-name', name)
901
_merge_tags_if_possible(br_from, branch)
1312
902
note('Branched %d revision(s).' % branch.revno())
1314
# Bind to the parent
1315
parent_branch = Branch.open(from_location)
1316
branch.bind(parent_branch)
1317
note('New branch bound to %s' % from_location)
1319
# Switch to the new branch
1320
wt, _ = WorkingTree.open_containing('.')
1321
_mod_switch.switch(wt.bzrdir, branch)
1322
note('Switched to branch: %s',
1323
urlutils.unescape_for_display(branch.base, 'utf-8'))
1326
907
class cmd_checkout(Command):
1327
__doc__ = """Create a new checkout of an existing branch.
908
"""Create a new checkout of an existing branch.
1329
910
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1330
911
the branch found in '.'. This is useful if you have removed the working tree
1331
912
or if it was never created - i.e. if you pushed the branch to its current
1332
913
location using SFTP.
1334
915
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1335
916
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1336
917
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1409
981
@display_command
1410
982
def run(self, dir=u'.'):
1411
983
tree = WorkingTree.open_containing(dir)[0]
1412
self.add_cleanup(tree.lock_read().unlock)
1413
new_inv = tree.inventory
1414
old_tree = tree.basis_tree()
1415
self.add_cleanup(old_tree.lock_read().unlock)
1416
old_inv = old_tree.inventory
1418
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1419
for f, paths, c, v, p, n, k, e in iterator:
1420
if paths[0] == paths[1]:
1424
renames.append(paths)
1426
for old_name, new_name in renames:
1427
self.outf.write("%s => %s\n" % (old_name, new_name))
986
new_inv = tree.inventory
987
old_tree = tree.basis_tree()
990
old_inv = old_tree.inventory
991
renames = list(_mod_tree.find_renames(old_inv, new_inv))
993
for old_name, new_name in renames:
994
self.outf.write("%s => %s\n" % (old_name, new_name))
1430
1001
class cmd_update(Command):
1431
__doc__ = """Update a tree to have the latest code committed to its branch.
1002
"""Update a tree to have the latest code committed to its branch.
1433
1004
This will perform a merge into the working tree, and may generate
1434
conflicts. If you have any local changes, you will still
1005
conflicts. If you have any local changes, you will still
1435
1006
need to commit them after the update for the update to be complete.
1437
If you want to discard your local changes, you can just do a
1008
If you want to discard your local changes, you can just do a
1438
1009
'bzr revert' instead of 'bzr commit' after the update.
1440
If you want to restore a file that has been removed locally, use
1441
'bzr revert' instead of 'bzr update'.
1443
If the tree's branch is bound to a master branch, it will also update
1444
the branch from the master.
1447
1012
_see_also = ['pull', 'working-trees', 'status-flags']
1448
1013
takes_args = ['dir?']
1449
takes_options = ['revision',
1451
help="Show base revision text in conflicts."),
1453
1014
aliases = ['up']
1455
def run(self, dir='.', revision=None, show_base=None):
1456
if revision is not None and len(revision) != 1:
1457
raise errors.BzrCommandError(
1458
"bzr update --revision takes exactly one revision")
1016
def run(self, dir='.'):
1459
1017
tree = WorkingTree.open_containing(dir)[0]
1460
branch = tree.branch
1461
1018
possible_transports = []
1462
master = branch.get_master_branch(
1019
master = tree.branch.get_master_branch(
1463
1020
possible_transports=possible_transports)
1464
1021
if master is not None:
1465
branch_location = master.base
1466
1022
tree.lock_write()
1468
branch_location = tree.branch.base
1469
1024
tree.lock_tree_write()
1470
self.add_cleanup(tree.unlock)
1471
# get rid of the final '/' and be ready for display
1472
branch_location = urlutils.unescape_for_display(
1473
branch_location.rstrip('/'),
1475
existing_pending_merges = tree.get_parent_ids()[1:]
1479
# may need to fetch data into a heavyweight checkout
1480
# XXX: this may take some time, maybe we should display a
1482
old_tip = branch.update(possible_transports)
1483
if revision is not None:
1484
revision_id = revision[0].as_revision_id(branch)
1486
revision_id = branch.last_revision()
1487
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1488
revno = branch.revision_id_to_dotted_revno(revision_id)
1489
note("Tree is up to date at revision %s of branch %s" %
1490
('.'.join(map(str, revno)), branch_location))
1492
view_info = _get_view_info_for_change_reporter(tree)
1493
change_reporter = delta._ChangeReporter(
1494
unversioned_filter=tree.is_ignored,
1495
view_info=view_info)
1026
existing_pending_merges = tree.get_parent_ids()[1:]
1027
last_rev = _mod_revision.ensure_null(tree.last_revision())
1028
if last_rev == _mod_revision.ensure_null(
1029
tree.branch.last_revision()):
1030
# may be up to date, check master too.
1031
if master is None or last_rev == _mod_revision.ensure_null(
1032
master.last_revision()):
1033
revno = tree.branch.revision_id_to_revno(last_rev)
1034
note("Tree is up to date at revision %d." % (revno,))
1497
1036
conflicts = tree.update(
1499
possible_transports=possible_transports,
1500
revision=revision_id,
1502
show_base=show_base)
1503
except errors.NoSuchRevision, e:
1504
raise errors.BzrCommandError(
1505
"branch has no revision %s\n"
1506
"bzr update --revision only works"
1507
" for a revision in the branch history"
1509
revno = tree.branch.revision_id_to_dotted_revno(
1510
_mod_revision.ensure_null(tree.last_revision()))
1511
note('Updated to revision %s of branch %s' %
1512
('.'.join(map(str, revno)), branch_location))
1513
parent_ids = tree.get_parent_ids()
1514
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1515
note('Your local commits will now show as pending merges with '
1516
"'bzr status', and can be committed with 'bzr commit'.")
1037
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1038
possible_transports=possible_transports)
1039
revno = tree.branch.revision_id_to_revno(
1040
_mod_revision.ensure_null(tree.last_revision()))
1041
note('Updated to revision %d.' % (revno,))
1042
if tree.get_parent_ids()[1:] != existing_pending_merges:
1043
note('Your local commits will now show as pending merges with '
1044
"'bzr status', and can be committed with 'bzr commit'.")
1523
1053
class cmd_info(Command):
1524
__doc__ = """Show information about a working tree, branch or repository.
1054
"""Show information about a working tree, branch or repository.
1526
1056
This command will show all known locations and formats associated to the
1527
tree, branch or repository.
1529
In verbose mode, statistical information is included with each report.
1530
To see extended statistic information, use a verbosity level of 2 or
1531
higher by specifying the verbose option multiple times, e.g. -vv.
1057
tree, branch or repository. Statistical information is included with
1533
1060
Branches and working trees will also report any missing revisions.
1537
Display information on the format and related locations:
1541
Display the above together with extended format information and
1542
basic statistics (like the number of files in the working tree and
1543
number of revisions in the branch and repository):
1547
Display the above together with number of committers to the branch:
1551
1062
_see_also = ['revno', 'working-trees', 'repositories']
1552
1063
takes_args = ['location?']
1553
1064
takes_options = ['verbose']
1554
encoding_type = 'replace'
1556
1066
@display_command
1557
1067
def run(self, location=None, verbose=False):
1559
noise_level = get_verbosity_level()
1561
1071
noise_level = 0
1562
1072
from bzrlib.info import show_bzrdir_info
1563
1073
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1564
verbose=noise_level, outfile=self.outf)
1074
verbose=noise_level)
1567
1077
class cmd_remove(Command):
1568
__doc__ = """Remove files or directories.
1570
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1571
delete them if they can easily be recovered using revert otherwise they
1572
will be backed up (adding an extention of the form .~#~). If no options or
1573
parameters are given Bazaar will scan for files that are being tracked by
1574
Bazaar but missing in your tree and stop tracking them for you.
1078
"""Remove files or directories.
1080
This makes bzr stop tracking changes to the specified files and
1081
delete them if they can easily be recovered using revert.
1083
You can specify one or more files, and/or --new. If you specify --new,
1084
only 'added' files will be removed. If you specify both, then new files
1085
in the specified directories will be removed. If the directories are
1086
also new, they will also be removed.
1576
1088
takes_args = ['file*']
1577
1089
takes_options = ['verbose',
1578
Option('new', help='Only remove files that have never been committed.'),
1090
Option('new', help='Remove newly-added files.'),
1579
1091
RegistryOption.from_kwargs('file-deletion-strategy',
1580
1092
'The file deletion mode to be used.',
1581
1093
title='Deletion Strategy', value_switches=True, enum_switch=False,
1582
safe='Backup changed files (default).',
1583
keep='Delete from bzr but leave the working copy.',
1584
no_backup='Don\'t backup changed files.',
1094
safe='Only delete files if they can be'
1095
' safely recovered (default).',
1096
keep="Don't delete any files.",
1585
1097
force='Delete all the specified files, even if they can not be '
1586
'recovered and even if they are non-empty directories. '
1587
'(deprecated, use no-backup)')]
1588
aliases = ['rm', 'del']
1098
'recovered and even if they are non-empty directories.')]
1589
1100
encoding_type = 'replace'
1591
1102
def run(self, file_list, verbose=False, new=False,
1592
1103
file_deletion_strategy='safe'):
1593
if file_deletion_strategy == 'force':
1594
note("(The --force option is deprecated, rather use --no-backup "
1596
file_deletion_strategy = 'no-backup'
1598
tree, file_list = WorkingTree.open_containing_paths(file_list)
1104
tree, file_list = tree_files(file_list)
1600
1106
if file_list is not None:
1601
1107
file_list = [f for f in file_list]
1109
raise errors.BzrCommandError('Specify one or more files to'
1110
' remove, or use --new.')
1603
self.add_cleanup(tree.lock_write().unlock)
1604
# Heuristics should probably all move into tree.remove_smart or
1607
1113
added = tree.changes_from(tree.basis_tree(),
1608
1114
specific_files=file_list).added
1609
1115
file_list = sorted([f[0] for f in added], reverse=True)
1610
1116
if len(file_list) == 0:
1611
1117
raise errors.BzrCommandError('No matching files.')
1612
elif file_list is None:
1613
# missing files show up in iter_changes(basis) as
1614
# versioned-with-no-kind.
1616
for change in tree.iter_changes(tree.basis_tree()):
1617
# Find paths in the working tree that have no kind:
1618
if change[1][1] is not None and change[6][1] is None:
1619
missing.append(change[1][1])
1620
file_list = sorted(missing, reverse=True)
1621
file_deletion_strategy = 'keep'
1622
1118
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1623
1119
keep_files=file_deletion_strategy=='keep',
1624
force=(file_deletion_strategy=='no-backup'))
1120
force=file_deletion_strategy=='force')
1627
1123
class cmd_file_id(Command):
1628
__doc__ = """Print file_id of a particular file or directory.
1124
"""Print file_id of a particular file or directory.
1630
1126
The file_id is assigned when the file is first added and remains the
1631
1127
same through all revisions where the file exists, even when it is
2182
1604
raise errors.BzrCommandError(msg)
2185
def _parse_levels(s):
2189
msg = "The levels argument must be an integer."
2190
raise errors.BzrCommandError(msg)
2193
1607
class cmd_log(Command):
2194
__doc__ = """Show historical log for a branch or subset of a branch.
2196
log is bzr's default tool for exploring the history of a branch.
2197
The branch to use is taken from the first parameter. If no parameters
2198
are given, the branch containing the working directory is logged.
2199
Here are some simple examples::
2201
bzr log log the current branch
2202
bzr log foo.py log a file in its branch
2203
bzr log http://server/branch log a branch on a server
2205
The filtering, ordering and information shown for each revision can
2206
be controlled as explained below. By default, all revisions are
2207
shown sorted (topologically) so that newer revisions appear before
2208
older ones and descendants always appear before ancestors. If displayed,
2209
merged revisions are shown indented under the revision in which they
2214
The log format controls how information about each revision is
2215
displayed. The standard log formats are called ``long``, ``short``
2216
and ``line``. The default is long. See ``bzr help log-formats``
2217
for more details on log formats.
2219
The following options can be used to control what information is
2222
-l N display a maximum of N revisions
2223
-n N display N levels of revisions (0 for all, 1 for collapsed)
2224
-v display a status summary (delta) for each revision
2225
-p display a diff (patch) for each revision
2226
--show-ids display revision-ids (and file-ids), not just revnos
2228
Note that the default number of levels to display is a function of the
2229
log format. If the -n option is not used, the standard log formats show
2230
just the top level (mainline).
2232
Status summaries are shown using status flags like A, M, etc. To see
2233
the changes explained using words like ``added`` and ``modified``
2234
instead, use the -vv option.
2238
To display revisions from oldest to newest, use the --forward option.
2239
In most cases, using this option will have little impact on the total
2240
time taken to produce a log, though --forward does not incrementally
2241
display revisions like --reverse does when it can.
2243
:Revision filtering:
2245
The -r option can be used to specify what revision or range of revisions
2246
to filter against. The various forms are shown below::
2248
-rX display revision X
2249
-rX.. display revision X and later
2250
-r..Y display up to and including revision Y
2251
-rX..Y display from X to Y inclusive
2253
See ``bzr help revisionspec`` for details on how to specify X and Y.
2254
Some common examples are given below::
2256
-r-1 show just the tip
2257
-r-10.. show the last 10 mainline revisions
2258
-rsubmit:.. show what's new on this branch
2259
-rancestor:path.. show changes since the common ancestor of this
2260
branch and the one at location path
2261
-rdate:yesterday.. show changes since yesterday
2263
When logging a range of revisions using -rX..Y, log starts at
2264
revision Y and searches back in history through the primary
2265
("left-hand") parents until it finds X. When logging just the
2266
top level (using -n1), an error is reported if X is not found
2267
along the way. If multi-level logging is used (-n0), X may be
2268
a nested merge revision and the log will be truncated accordingly.
2272
If parameters are given and the first one is not a branch, the log
2273
will be filtered to show only those revisions that changed the
2274
nominated files or directories.
2276
Filenames are interpreted within their historical context. To log a
2277
deleted file, specify a revision range so that the file existed at
2278
the end or start of the range.
2280
Historical context is also important when interpreting pathnames of
2281
renamed files/directories. Consider the following example:
2283
* revision 1: add tutorial.txt
2284
* revision 2: modify tutorial.txt
2285
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2289
* ``bzr log guide.txt`` will log the file added in revision 1
2291
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2293
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2294
the original file in revision 2.
2296
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2297
was no file called guide.txt in revision 2.
2299
Renames are always followed by log. By design, there is no need to
2300
explicitly ask for this (and no way to stop logging a file back
2301
until it was last renamed).
2305
The --message option can be used for finding revisions that match a
2306
regular expression in a commit message.
2310
GUI tools and IDEs are often better at exploring history than command
2311
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2312
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2313
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2314
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2316
You may find it useful to add the aliases below to ``bazaar.conf``::
2320
top = log -l10 --line
2323
``bzr tip`` will then show the latest revision while ``bzr top``
2324
will show the last 10 mainline revisions. To see the details of a
2325
particular revision X, ``bzr show -rX``.
2327
If you are interested in looking deeper into a particular merge X,
2328
use ``bzr log -n0 -rX``.
2330
``bzr log -v`` on a branch with lots of history is currently
2331
very slow. A fix for this issue is currently under development.
2332
With or without that fix, it is recommended that a revision range
2333
be given when using the -v option.
2335
bzr has a generic full-text matching plugin, bzr-search, that can be
2336
used to find revisions matching user names, commit messages, etc.
2337
Among other features, this plugin can find all revisions containing
2338
a list of words but not others.
2340
When exploring non-mainline history on large projects with deep
2341
history, the performance of log can be greatly improved by installing
2342
the historycache plugin. This plugin buffers historical information
2343
trading disk space for faster speed.
1608
"""Show log of a branch, file, or directory.
1610
By default show the log of the branch containing the working directory.
1612
To request a range of logs, you can use the command -r begin..end
1613
-r revision requests a specific revision, -r ..end or -r begin.. are
1617
Log the current branch::
1625
Log the last 10 revisions of a branch::
1627
bzr log -r -10.. http://server/branch
2345
takes_args = ['file*']
2346
_see_also = ['log-formats', 'revisionspec']
1630
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1632
takes_args = ['location?']
2347
1633
takes_options = [
2348
1634
Option('forward',
2349
1635
help='Show from oldest to newest.'),
1638
help='Display timezone as local, original, or utc.'),
2351
1639
custom_help('verbose',
2352
1640
help='Show files changed in each revision.'),
2356
type=bzrlib.option._parse_revision_str,
2358
help='Show just the specified revision.'
2359
' See also "help revisionspec".'),
2361
RegistryOption('authors',
2362
'What names to list as authors - first, all or committer.',
2364
lazy_registry=('bzrlib.log', 'author_list_registry'),
2368
help='Number of levels to display - 0 for all, 1 for flat.',
2370
type=_parse_levels),
2371
1644
Option('message',
2372
1645
short_name='m',
2373
1646
help='Show revisions whose message matches this '
2374
1647
'regular expression.',
2376
1649
Option('limit',
2378
1650
help='Limit the output to the first N revisions.',
2380
1652
type=_parse_limit),
2383
help='Show changes made in each revision as a patch.'),
2384
Option('include-merges',
2385
help='Show merged revisions like --levels 0 does.'),
2386
Option('exclude-common-ancestry',
2387
help='Display only the revisions that are not part'
2388
' of both ancestries (require -rX..Y)'
2391
1654
encoding_type = 'replace'
2393
1656
@display_command
2394
def run(self, file_list=None, timezone='original',
1657
def run(self, location=None, timezone='original',
2396
1659
show_ids=False,
2400
1662
log_format=None,
2405
include_merges=False,
2407
exclude_common_ancestry=False,
2409
from bzrlib.log import (
2411
make_log_request_dict,
2412
_get_info_for_log_files,
1665
from bzrlib.log import show_log
1666
assert message is None or isinstance(message, basestring), \
1667
"invalid message argument %r" % message
2414
1668
direction = (forward and 'forward') or 'reverse'
2415
if (exclude_common_ancestry
2416
and (revision is None or len(revision) != 2)):
2417
raise errors.BzrCommandError(
2418
'--exclude-common-ancestry requires -r with two revisions')
2423
raise errors.BzrCommandError(
2424
'--levels and --include-merges are mutually exclusive')
2426
if change is not None:
2428
raise errors.RangeInChangeOption()
2429
if revision is not None:
2430
raise errors.BzrCommandError(
2431
'--revision and --change are mutually exclusive')
2436
filter_by_dir = False
2438
# find the file ids to log and check for directory filtering
2439
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2440
revision, file_list, self.add_cleanup)
2441
for relpath, file_id, kind in file_info_list:
1673
# find the file id to log:
1675
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1679
tree = b.basis_tree()
1680
file_id = tree.path2id(fp)
2442
1681
if file_id is None:
2443
1682
raise errors.BzrCommandError(
2444
"Path unknown at end or start of revision range: %s" %
2446
# If the relpath is the top of the tree, we log everything
2451
file_ids.append(file_id)
2452
filter_by_dir = filter_by_dir or (
2453
kind in ['directory', 'tree-reference'])
1683
"Path does not have any revision history: %s" %
2456
# FIXME ? log the current subdir only RBC 20060203
1687
# FIXME ? log the current subdir only RBC 20060203
2457
1688
if revision is not None \
2458
1689
and len(revision) > 0 and revision[0].get_branch():
2459
1690
location = revision[0].get_branch()
2462
1693
dir, relpath = bzrdir.BzrDir.open_containing(location)
2463
1694
b = dir.open_branch()
2464
self.add_cleanup(b.lock_read().unlock)
2465
rev1, rev2 = _get_revision_range(revision, b, self.name())
2467
# Decide on the type of delta & diff filtering to use
2468
# TODO: add an --all-files option to make this configurable & consistent
2476
diff_type = 'partial'
2480
# Build the log formatter
2481
if log_format is None:
2482
log_format = log.log_formatter_registry.get_default(b)
2483
# Make a non-encoding output to include the diffs - bug 328007
2484
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2485
lf = log_format(show_ids=show_ids, to_file=self.outf,
2486
to_exact_file=unencoded_output,
2487
show_timezone=timezone,
2488
delta_format=get_verbosity_level(),
2490
show_advice=levels is None,
2491
author_list_handler=authors)
2493
# Choose the algorithm for doing the logging. It's annoying
2494
# having multiple code paths like this but necessary until
2495
# the underlying repository format is faster at generating
2496
# deltas or can provide everything we need from the indices.
2497
# The default algorithm - match-using-deltas - works for
2498
# multiple files and directories and is faster for small
2499
# amounts of history (200 revisions say). However, it's too
2500
# slow for logging a single file in a repository with deep
2501
# history, i.e. > 10K revisions. In the spirit of "do no
2502
# evil when adding features", we continue to use the
2503
# original algorithm - per-file-graph - for the "single
2504
# file that isn't a directory without showing a delta" case.
2505
partial_history = revision and b.repository._format.supports_chks
2506
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2507
or delta_type or partial_history)
2509
# Build the LogRequest and execute it
2510
if len(file_ids) == 0:
2512
rqst = make_log_request_dict(
2513
direction=direction, specific_fileids=file_ids,
2514
start_revision=rev1, end_revision=rev2, limit=limit,
2515
message_search=message, delta_type=delta_type,
2516
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2517
exclude_common_ancestry=exclude_common_ancestry,
2519
Logger(b, rqst).show(lf)
2522
def _get_revision_range(revisionspec_list, branch, command_name):
2523
"""Take the input of a revision option and turn it into a revision range.
2525
It returns RevisionInfo objects which can be used to obtain the rev_id's
2526
of the desired revisions. It does some user input validations.
2528
if revisionspec_list is None:
2531
elif len(revisionspec_list) == 1:
2532
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2533
elif len(revisionspec_list) == 2:
2534
start_spec = revisionspec_list[0]
2535
end_spec = revisionspec_list[1]
2536
if end_spec.get_branch() != start_spec.get_branch():
2537
# b is taken from revision[0].get_branch(), and
2538
# show_log will use its revision_history. Having
2539
# different branches will lead to weird behaviors.
2540
raise errors.BzrCommandError(
2541
"bzr %s doesn't accept two revisions in different"
2542
" branches." % command_name)
2543
if start_spec.spec is None:
2544
# Avoid loading all the history.
2545
rev1 = RevisionInfo(branch, None, None)
2547
rev1 = start_spec.in_history(branch)
2548
# Avoid loading all of history when we know a missing
2549
# end of range means the last revision ...
2550
if end_spec.spec is None:
2551
last_revno, last_revision_id = branch.last_revision_info()
2552
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2554
rev2 = end_spec.in_history(branch)
2556
raise errors.BzrCommandError(
2557
'bzr %s --revision takes one or two values.' % command_name)
2561
def _revision_range_to_revid_range(revision_range):
2564
if revision_range[0] is not None:
2565
rev_id1 = revision_range[0].rev_id
2566
if revision_range[1] is not None:
2567
rev_id2 = revision_range[1].rev_id
2568
return rev_id1, rev_id2
1698
if revision is None:
1701
elif len(revision) == 1:
1702
rev1 = rev2 = revision[0].in_history(b)
1703
elif len(revision) == 2:
1704
if revision[1].get_branch() != revision[0].get_branch():
1705
# b is taken from revision[0].get_branch(), and
1706
# show_log will use its revision_history. Having
1707
# different branches will lead to weird behaviors.
1708
raise errors.BzrCommandError(
1709
"Log doesn't accept two revisions in different"
1711
rev1 = revision[0].in_history(b)
1712
rev2 = revision[1].in_history(b)
1714
raise errors.BzrCommandError(
1715
'bzr log --revision takes one or two values.')
1717
if log_format is None:
1718
log_format = log.log_formatter_registry.get_default(b)
1720
lf = log_format(show_ids=show_ids, to_file=self.outf,
1721
show_timezone=timezone)
1727
direction=direction,
1728
start_revision=rev1,
2570
1736
def get_log_format(long=False, short=False, line=False, default='long'):
2571
1737
log_format = default
2642
1805
if path is None:
2646
1810
raise errors.BzrCommandError('cannot specify both --from-root'
2649
tree, branch, relpath = \
2650
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2652
# Calculate the prefix to use
1814
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2656
prefix = relpath + '/'
2657
elif fs_path != '.' and not fs_path.endswith('/'):
2658
prefix = fs_path + '/'
2660
if revision is not None or tree is None:
2661
tree = _get_one_revision_tree('ls', revision, branch=branch)
2664
if isinstance(tree, WorkingTree) and tree.supports_views():
2665
view_files = tree.views.lookup_view()
2668
view_str = views.view_display_str(view_files)
2669
note("Ignoring files outside view. View is %s" % view_str)
2671
self.add_cleanup(tree.lock_read().unlock)
2672
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2673
from_dir=relpath, recursive=recursive):
2674
# Apply additional masking
2675
if not all and not selection[fc]:
2677
if kind is not None and fkind != kind:
2682
fullpath = osutils.pathjoin(relpath, fp)
2685
views.check_path_in_view(tree, fullpath)
2686
except errors.FileOutsideView:
2691
fp = osutils.pathjoin(prefix, fp)
2692
kindch = entry.kind_character()
2693
outstring = fp + kindch
2694
ui.ui_factory.clear_term()
2696
outstring = '%-8s %s' % (fc, outstring)
2697
if show_ids and fid is not None:
2698
outstring = "%-50s %s" % (outstring, fid)
2699
self.outf.write(outstring + '\n')
2701
self.outf.write(fp + '\0')
2704
self.outf.write(fid)
2705
self.outf.write('\0')
2713
self.outf.write('%-50s %s\n' % (outstring, my_id))
2715
self.outf.write(outstring + '\n')
1820
if revision is not None:
1821
tree = branch.repository.revision_tree(
1822
revision[0].in_history(branch).rev_id)
1824
tree = branch.basis_tree()
1828
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1829
if fp.startswith(relpath):
1830
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1831
if non_recursive and '/' in fp:
1833
if not all and not selection[fc]:
1835
if kind is not None and fkind != kind:
1838
kindch = entry.kind_character()
1839
outstring = '%-8s %s%s' % (fc, fp, kindch)
1840
if show_ids and fid is not None:
1841
outstring = "%-50s %s" % (outstring, fid)
1842
self.outf.write(outstring + '\n')
1844
self.outf.write(fp + '\0')
1847
self.outf.write(fid)
1848
self.outf.write('\0')
1856
self.outf.write('%-50s %s\n' % (fp, my_id))
1858
self.outf.write(fp + '\n')
2718
1863
class cmd_unknowns(Command):
2719
__doc__ = """List unknown files.
1864
"""List unknown files.
2723
1868
_see_also = ['ls']
2724
takes_options = ['directory']
2726
1870
@display_command
2727
def run(self, directory=u'.'):
2728
for f in WorkingTree.open_containing(directory)[0].unknowns():
1872
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2729
1873
self.outf.write(osutils.quotefn(f) + '\n')
2732
1876
class cmd_ignore(Command):
2733
__doc__ = """Ignore specified files or patterns.
2735
See ``bzr help patterns`` for details on the syntax of patterns.
2737
If a .bzrignore file does not exist, the ignore command
2738
will create one and add the specified files or patterns to the newly
2739
created file. The ignore command will also automatically add the
2740
.bzrignore file to be versioned. Creating a .bzrignore file without
2741
the use of the ignore command will require an explicit add command.
1877
"""Ignore specified files or patterns.
2743
1879
To remove patterns from the ignore list, edit the .bzrignore file.
2744
After adding, editing or deleting that file either indirectly by
2745
using this command or directly by using an editor, be sure to commit
2748
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2749
the global ignore file can be found in the application data directory as
2750
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2751
Global ignores are not touched by this command. The global ignore file
2752
can be edited directly using an editor.
2754
Patterns prefixed with '!' are exceptions to ignore patterns and take
2755
precedence over regular ignores. Such exceptions are used to specify
2756
files that should be versioned which would otherwise be ignored.
2758
Patterns prefixed with '!!' act as regular ignore patterns, but have
2759
precedence over the '!' exception patterns.
2763
* Ignore patterns containing shell wildcards must be quoted from
2766
* Ignore patterns starting with "#" act as comments in the ignore file.
2767
To ignore patterns that begin with that character, use the "RE:" prefix.
1881
Trailing slashes on patterns are ignored.
1882
If the pattern contains a slash or is a regular expression, it is compared
1883
to the whole path from the branch root. Otherwise, it is compared to only
1884
the last component of the path. To match a file only in the root
1885
directory, prepend './'.
1887
Ignore patterns specifying absolute paths are not allowed.
1889
Ignore patterns may include globbing wildcards such as::
1891
? - Matches any single character except '/'
1892
* - Matches 0 or more characters except '/'
1893
/**/ - Matches 0 or more directories in a path
1894
[a-z] - Matches a single character from within a group of characters
1896
Ignore patterns may also be Python regular expressions.
1897
Regular expression ignore patterns are identified by a 'RE:' prefix
1898
followed by the regular expression. Regular expression ignore patterns
1899
may not include named or numbered groups.
1901
Note: ignore patterns containing shell wildcards must be quoted from
2770
1905
Ignore the top level Makefile::
2772
1907
bzr ignore ./Makefile
2774
Ignore .class files in all directories...::
2776
bzr ignore "*.class"
2778
...but do not ignore "special.class"::
2780
bzr ignore "!special.class"
2782
Ignore files whose name begins with the "#" character::
2786
Ignore .o files under the lib directory::
2788
bzr ignore "lib/**/*.o"
2790
Ignore .o files under the lib directory::
2792
bzr ignore "RE:lib/.*\.o"
2794
Ignore everything but the "debian" toplevel directory::
2796
bzr ignore "RE:(?!debian/).*"
2798
Ignore everything except the "local" toplevel directory,
2799
but always ignore autosave files ending in ~, even under local/::
2802
bzr ignore "!./local"
1909
Ignore class files in all directories::
1911
bzr ignore '*.class'
1913
Ignore .o files under the lib directory::
1915
bzr ignore 'lib/**/*.o'
1917
Ignore .o files under the lib directory::
1919
bzr ignore 'RE:lib/.*\.o'
2806
_see_also = ['status', 'ignored', 'patterns']
1922
_see_also = ['status', 'ignored']
2807
1923
takes_args = ['name_pattern*']
2808
takes_options = ['directory',
2809
Option('default-rules',
2810
help='Display the default ignore rules that bzr uses.')
1925
Option('old-default-rules',
1926
help='Write out the ignore rules bzr < 0.9 always used.')
2813
def run(self, name_pattern_list=None, default_rules=None,
2815
from bzrlib import ignores
2816
if default_rules is not None:
2817
# dump the default rules and exit
2818
for pattern in ignores.USER_DEFAULTS:
2819
self.outf.write("%s\n" % pattern)
1929
def run(self, name_pattern_list=None, old_default_rules=None):
1930
from bzrlib.atomicfile import AtomicFile
1931
if old_default_rules is not None:
1932
# dump the rules and exit
1933
for pattern in ignores.OLD_DEFAULTS:
2821
1936
if not name_pattern_list:
2822
1937
raise errors.BzrCommandError("ignore requires at least one "
2823
"NAME_PATTERN or --default-rules.")
2824
name_pattern_list = [globbing.normalize_pattern(p)
1938
"NAME_PATTERN or --old-default-rules")
1939
name_pattern_list = [globbing.normalize_pattern(p)
2825
1940
for p in name_pattern_list]
2827
for p in name_pattern_list:
2828
if not globbing.Globster.is_pattern_valid(p):
2829
bad_patterns += ('\n %s' % p)
2831
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2832
ui.ui_factory.show_error(msg)
2833
raise errors.InvalidPattern('')
2834
1941
for name_pattern in name_pattern_list:
2835
if (name_pattern[0] == '/' or
1942
if (name_pattern[0] == '/' or
2836
1943
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2837
1944
raise errors.BzrCommandError(
2838
1945
"NAME_PATTERN should not be an absolute path")
2839
tree, relpath = WorkingTree.open_containing(directory)
2840
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
1946
tree, relpath = WorkingTree.open_containing(u'.')
1947
ifn = tree.abspath('.bzrignore')
1948
if os.path.exists(ifn):
1951
igns = f.read().decode('utf-8')
1957
# TODO: If the file already uses crlf-style termination, maybe
1958
# we should use that for the newly added lines?
1960
if igns and igns[-1] != '\n':
1962
for name_pattern in name_pattern_list:
1963
igns += name_pattern + '\n'
1965
f = AtomicFile(ifn, 'wb')
1967
f.write(igns.encode('utf-8'))
1972
if not tree.path2id('.bzrignore'):
1973
tree.add(['.bzrignore'])
2841
1975
ignored = globbing.Globster(name_pattern_list)
2843
self.add_cleanup(tree.lock_read().unlock)
2844
1978
for entry in tree.list_files():
2846
1980
if id is not None:
2847
1981
filename = entry[0]
2848
1982
if ignored.match(filename):
2849
matches.append(filename)
1983
matches.append(filename.encode('utf-8'))
2850
1985
if len(matches) > 0:
2851
self.outf.write("Warning: the following files are version controlled and"
2852
" match your ignore pattern:\n%s"
2853
"\nThese files will continue to be version controlled"
2854
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1986
print "Warning: the following files are version controlled and" \
1987
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2857
1989
class cmd_ignored(Command):
2858
__doc__ = """List ignored files and the patterns that matched them.
2860
List all the ignored files and the ignore pattern that caused the file to
2863
Alternatively, to list just the files::
1990
"""List ignored files and the patterns that matched them.
2868
encoding_type = 'replace'
2869
_see_also = ['ignore', 'ls']
2870
takes_options = ['directory']
1993
_see_also = ['ignore']
2872
1994
@display_command
2873
def run(self, directory=u'.'):
2874
tree = WorkingTree.open_containing(directory)[0]
2875
self.add_cleanup(tree.lock_read().unlock)
2876
for path, file_class, kind, file_id, entry in tree.list_files():
2877
if file_class != 'I':
2879
## XXX: Slightly inefficient since this was already calculated
2880
pat = tree.is_ignored(path)
2881
self.outf.write('%-50s %s\n' % (path, pat))
1996
tree = WorkingTree.open_containing(u'.')[0]
1999
for path, file_class, kind, file_id, entry in tree.list_files():
2000
if file_class != 'I':
2002
## XXX: Slightly inefficient since this was already calculated
2003
pat = tree.is_ignored(path)
2004
print '%-50s %s' % (path, pat)
2884
2009
class cmd_lookup_revision(Command):
2885
__doc__ = """Lookup the revision-id from a revision-number
2010
"""Lookup the revision-id from a revision-number
2888
2013
bzr lookup-revision 33
2891
2016
takes_args = ['revno']
2892
takes_options = ['directory']
2894
2018
@display_command
2895
def run(self, revno, directory=u'.'):
2019
def run(self, revno):
2897
2021
revno = int(revno)
2898
2022
except ValueError:
2899
raise errors.BzrCommandError("not a valid revision-number: %r"
2901
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2902
self.outf.write("%s\n" % revid)
2023
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2025
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2905
2028
class cmd_export(Command):
2906
__doc__ = """Export current or past revision to a destination directory or archive.
2029
"""Export current or past revision to a destination directory or archive.
2908
2031
If no revision is specified this exports the last committed revision.
2931
2054
================= =========================
2934
takes_args = ['dest', 'branch_or_subdir?']
2935
takes_options = ['directory',
2056
takes_args = ['dest', 'branch?']
2936
2058
Option('format',
2937
2059
help="Type of file to export to.",
2940
Option('filters', help='Apply content filters to export the '
2941
'convenient form.'),
2944
2064
help="Name of the root directory inside the exported file."),
2945
Option('per-file-timestamps',
2946
help='Set modification time of files to that of the last '
2947
'revision in which it was changed.'),
2949
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2950
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2066
def run(self, dest, branch=None, revision=None, format=None, root=None):
2951
2067
from bzrlib.export import export
2953
if branch_or_subdir is None:
2954
tree = WorkingTree.open_containing(directory)[0]
2070
tree = WorkingTree.open_containing(u'.')[0]
2955
2071
b = tree.branch
2958
b, subdir = Branch.open_containing(branch_or_subdir)
2961
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2073
b = Branch.open(branch)
2075
if revision is None:
2076
# should be tree.last_revision FIXME
2077
rev_id = b.last_revision()
2079
if len(revision) != 1:
2080
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2081
rev_id = revision[0].in_history(b).rev_id
2082
t = b.repository.revision_tree(rev_id)
2963
export(rev_tree, dest, format, root, subdir, filtered=filters,
2964
per_file_timestamps=per_file_timestamps)
2084
export(t, dest, format, root)
2965
2085
except errors.NoSuchExportFormat, e:
2966
2086
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2969
2089
class cmd_cat(Command):
2970
__doc__ = """Write the contents of a file as of a given revision to standard output.
2090
"""Write the contents of a file as of a given revision to standard output.
2972
2092
If no revision is nominated, the last revision is used.
2974
2094
Note: Take care to redirect standard output when using this command on a
2978
2098
_see_also = ['ls']
2979
takes_options = ['directory',
2980
2100
Option('name-from-revision', help='The path name in the old tree.'),
2981
Option('filters', help='Apply content filters to display the '
2982
'convenience form.'),
2985
2103
takes_args = ['filename']
2986
2104
encoding_type = 'exact'
2988
2106
@display_command
2989
def run(self, filename, revision=None, name_from_revision=False,
2990
filters=False, directory=None):
2107
def run(self, filename, revision=None, name_from_revision=False):
2991
2108
if revision is not None and len(revision) != 1:
2992
2109
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2993
" one revision specifier")
2994
tree, branch, relpath = \
2995
_open_directory_or_containing_tree_or_branch(filename, directory)
2996
self.add_cleanup(branch.lock_read().unlock)
2997
return self._run(tree, branch, relpath, filename, revision,
2998
name_from_revision, filters)
3000
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2114
tree, b, relpath = \
2115
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2116
except errors.NotBranchError:
2119
if revision is not None and revision[0].get_branch() is not None:
2120
b = Branch.open(revision[0].get_branch())
3002
2121
if tree is None:
3003
2122
tree = b.basis_tree()
3004
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3005
self.add_cleanup(rev_tree.lock_read().unlock)
2123
if revision is None:
2124
revision_id = b.last_revision()
2126
revision_id = revision[0].in_history(b).rev_id
2128
cur_file_id = tree.path2id(relpath)
2129
rev_tree = b.repository.revision_tree(revision_id)
3007
2130
old_file_id = rev_tree.path2id(relpath)
3009
2132
if name_from_revision:
3010
# Try in revision if requested
3011
2133
if old_file_id is None:
3012
raise errors.BzrCommandError(
3013
"%r is not present in revision %s" % (
3014
filename, rev_tree.get_revision_id()))
2134
raise errors.BzrCommandError("%r is not present in revision %s"
2135
% (filename, revision_id))
3016
content = rev_tree.get_file_text(old_file_id)
3018
cur_file_id = tree.path2id(relpath)
3020
if cur_file_id is not None:
3021
# Then try with the actual file id
3023
content = rev_tree.get_file_text(cur_file_id)
3025
except errors.NoSuchId:
3026
# The actual file id didn't exist at that time
3028
if not found and old_file_id is not None:
3029
# Finally try with the old file id
3030
content = rev_tree.get_file_text(old_file_id)
3033
# Can't be found anywhere
3034
raise errors.BzrCommandError(
3035
"%r is not present in revision %s" % (
3036
filename, rev_tree.get_revision_id()))
3038
from bzrlib.filters import (
3039
ContentFilterContext,
3040
filtered_output_bytes,
3042
filters = rev_tree._content_filter_stack(relpath)
3043
chunks = content.splitlines(True)
3044
content = filtered_output_bytes(chunks, filters,
3045
ContentFilterContext(relpath, rev_tree))
3047
self.outf.writelines(content)
3050
self.outf.write(content)
2137
rev_tree.print_file(old_file_id)
2138
elif cur_file_id is not None:
2139
rev_tree.print_file(cur_file_id)
2140
elif old_file_id is not None:
2141
rev_tree.print_file(old_file_id)
2143
raise errors.BzrCommandError("%r is not present in revision %s" %
2144
(filename, revision_id))
3053
2147
class cmd_local_time_offset(Command):
3054
__doc__ = """Show the offset in seconds from GMT to local time."""
2148
"""Show the offset in seconds from GMT to local time."""
3056
2150
@display_command
3058
self.outf.write("%s\n" % osutils.local_time_offset())
2152
print osutils.local_time_offset()
3062
2156
class cmd_commit(Command):
3063
__doc__ = """Commit changes into a new revision.
3065
An explanatory message needs to be given for each commit. This is
3066
often done by using the --message option (getting the message from the
3067
command line) or by using the --file option (getting the message from
3068
a file). If neither of these options is given, an editor is opened for
3069
the user to enter the message. To see the changed files in the
3070
boilerplate text loaded into the editor, use the --show-diff option.
3072
By default, the entire tree is committed and the person doing the
3073
commit is assumed to be the author. These defaults can be overridden
3078
If selected files are specified, only changes to those files are
3079
committed. If a directory is specified then the directory and
3080
everything within it is committed.
3082
When excludes are given, they take precedence over selected files.
3083
For example, to commit only changes within foo, but not changes
3086
bzr commit foo -x foo/bar
3088
A selective commit after a merge is not yet supported.
3092
If the author of the change is not the same person as the committer,
3093
you can specify the author's name using the --author option. The
3094
name should be in the same format as a committer-id, e.g.
3095
"John Doe <jdoe@example.com>". If there is more than one author of
3096
the change you can specify the option multiple times, once for each
3101
A common mistake is to forget to add a new file or directory before
3102
running the commit command. The --strict option checks for unknown
3103
files and aborts the commit if any are found. More advanced pre-commit
3104
checks can be implemented by defining hooks. See ``bzr help hooks``
3109
If you accidentially commit the wrong changes or make a spelling
3110
mistake in the commit message say, you can use the uncommit command
3111
to undo it. See ``bzr help uncommit`` for details.
3113
Hooks can also be configured to run after a commit. This allows you
3114
to trigger updates to external systems like bug trackers. The --fixes
3115
option can be used to record the association between a revision and
3116
one or more bugs. See ``bzr help bugs`` for details.
2157
"""Commit changes into a new revision.
2159
If no arguments are given, the entire tree is committed.
2161
If selected files are specified, only changes to those files are
2162
committed. If a directory is specified then the directory and everything
2163
within it is committed.
2165
If author of the change is not the same person as the committer, you can
2166
specify the author's name using the --author option. The name should be
2167
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2169
A selected-file commit may fail in some cases where the committed
2170
tree would be invalid. Consider::
2175
bzr commit foo -m "committing foo"
2176
bzr mv foo/bar foo/baz
2179
bzr commit foo/bar -m "committing bar but not baz"
2181
In the example above, the last commit will fail by design. This gives
2182
the user the opportunity to decide whether they want to commit the
2183
rename at the same time, separately first, or not at all. (As a general
2184
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2186
Note: A selected-file commit after a merge is not yet supported.
3119
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
2188
# TODO: Run hooks on tree to-be-committed, and after commit.
2190
# TODO: Strict commit that fails if there are deleted files.
2191
# (what does "deleted files" mean ??)
2193
# TODO: Give better message for -s, --summary, used by tla people
2195
# XXX: verbose currently does nothing
2197
_see_also = ['bugs', 'uncommit']
3120
2198
takes_args = ['selected*']
3121
2199
takes_options = [
3122
ListOption('exclude', type=str, short_name='x',
3123
help="Do not consider changes made to a given path."),
3124
2200
Option('message', type=unicode,
3125
2201
short_name='m',
3126
2202
help="Description of the new revision."),
3297
2326
raise errors.BzrCommandError("Commit refused because there are"
3298
2327
" unknown files in the working tree.")
3299
2328
except errors.BoundBranchOutOfDate, e:
3300
e.extra_help = ("\n"
3301
'To commit to master branch, run update and then commit.\n'
3302
'You can also pass --local to commit to continue working '
2329
raise errors.BzrCommandError(str(e) + "\n"
2330
'To commit to master branch, run update and then commit.\n'
2331
'You can also pass --local to commit to continue working '
3307
2335
class cmd_check(Command):
3308
__doc__ = """Validate working tree structure, branch consistency and repository history.
3310
This command checks various invariants about branch and repository storage
3311
to detect data corruption or bzr bugs.
3313
The working tree and branch checks will only give output if a problem is
3314
detected. The output fields of the repository check are:
3317
This is just the number of revisions checked. It doesn't
3321
This is just the number of versionedfiles checked. It
3322
doesn't indicate a problem.
3324
unreferenced ancestors
3325
Texts that are ancestors of other texts, but
3326
are not properly referenced by the revision ancestry. This is a
3327
subtle problem that Bazaar can work around.
3330
This is the total number of unique file contents
3331
seen in the checked revisions. It does not indicate a problem.
3334
This is the total number of repeated texts seen
3335
in the checked revisions. Texts can be repeated when their file
3336
entries are modified, but the file contents are not. It does not
3339
If no restrictions are specified, all Bazaar data that is found at the given
3340
location will be checked.
3344
Check the tree and branch at 'foo'::
3346
bzr check --tree --branch foo
3348
Check only the repository at 'bar'::
3350
bzr check --repo bar
3352
Check everything at 'baz'::
2336
"""Validate consistency of branch history.
2338
This command checks various invariants about the branch storage to
2339
detect data corruption or bzr bugs.
2343
revisions: This is just the number of revisions checked. It doesn't
2345
versionedfiles: This is just the number of versionedfiles checked. It
2346
doesn't indicate a problem.
2347
unreferenced ancestors: Texts that are ancestors of other texts, but
2348
are not properly referenced by the revision ancestry. This is a
2349
subtle problem that Bazaar can work around.
2350
unique file texts: This is the total number of unique file contents
2351
seen in the checked revisions. It does not indicate a problem.
2352
repeated file texts: This is the total number of repeated texts seen
2353
in the checked revisions. Texts can be repeated when their file
2354
entries are modified, but the file contents are not. It does not
3357
2358
_see_also = ['reconcile']
3358
takes_args = ['path?']
3359
takes_options = ['verbose',
3360
Option('branch', help="Check the branch related to the"
3361
" current directory."),
3362
Option('repo', help="Check the repository related to the"
3363
" current directory."),
3364
Option('tree', help="Check the working tree related to"
3365
" the current directory.")]
2359
takes_args = ['branch?']
2360
takes_options = ['verbose']
3367
def run(self, path=None, verbose=False, branch=False, repo=False,
3369
from bzrlib.check import check_dwim
3372
if not branch and not repo and not tree:
3373
branch = repo = tree = True
3374
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2362
def run(self, branch=None, verbose=False):
2363
from bzrlib.check import check
2365
branch = Branch.open_containing('.')[0]
2367
branch = Branch.open(branch)
2368
check(branch, verbose)
3377
2371
class cmd_upgrade(Command):
3378
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3380
When the default format has changed after a major new release of
3381
Bazaar, you may be informed during certain operations that you
3382
should upgrade. Upgrading to a newer format may improve performance
3383
or make new features available. It may however limit interoperability
3384
with older repositories or with older versions of Bazaar.
3386
If you wish to upgrade to a particular format rather than the
3387
current default, that can be specified using the --format option.
3388
As a consequence, you can use the upgrade command this way to
3389
"downgrade" to an earlier format, though some conversions are
3390
a one way process (e.g. changing from the 1.x default to the
3391
2.x default) so downgrading is not always possible.
3393
A backup.bzr.~#~ directory is created at the start of the conversion
3394
process (where # is a number). By default, this is left there on
3395
completion. If the conversion fails, delete the new .bzr directory
3396
and rename this one back in its place. Use the --clean option to ask
3397
for the backup.bzr directory to be removed on successful conversion.
3398
Alternatively, you can delete it by hand if everything looks good
3401
If the location given is a shared repository, dependent branches
3402
are also converted provided the repository converts successfully.
3403
If the conversion of a branch fails, remaining branches are still
3406
For more information on upgrades, see the Bazaar Upgrade Guide,
3407
http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
2372
"""Upgrade branch storage to current format.
2374
The check command or bzr developers may sometimes advise you to run
2375
this command. When the default format has changed you may also be warned
2376
during other operations to upgrade.
3410
_see_also = ['check', 'reconcile', 'formats']
2379
_see_also = ['check']
3411
2380
takes_args = ['url?']
3412
2381
takes_options = [
3413
RegistryOption('format',
3414
help='Upgrade to a specific format. See "bzr help'
3415
' formats" for details.',
3416
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3417
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3418
value_switches=True, title='Branch format'),
3420
help='Remove the backup.bzr directory if successful.'),
3422
help="Show what would be done, but don't actually do anything."),
2382
RegistryOption('format',
2383
help='Upgrade to a specific format. See "bzr help'
2384
' formats" for details.',
2385
registry=bzrdir.format_registry,
2386
converter=bzrdir.format_registry.make_bzrdir,
2387
value_switches=True, title='Branch format'),
3425
def run(self, url='.', format=None, clean=False, dry_run=False):
2390
def run(self, url='.', format=None):
3426
2391
from bzrlib.upgrade import upgrade
3427
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3429
if len(exceptions) == 1:
3430
# Compatibility with historical behavior
2393
format = bzrdir.format_registry.make_bzrdir('default')
2394
upgrade(url, format)
3436
2397
class cmd_whoami(Command):
3437
__doc__ = """Show or set bzr user id.
2398
"""Show or set bzr user id.
3440
2401
Show the email of the current user::
3692
2557
short_name='x',
3693
2558
help='Exclude tests that match this regular'
3694
2559
' expression.'),
3696
help='Output test progress via subunit.'),
3697
2560
Option('strict', help='Fail on missing dependencies or '
3698
2561
'known failures.'),
3699
Option('load-list', type=str, argname='TESTLISTFILE',
3700
help='Load a test id list from a text file.'),
3701
ListOption('debugflag', type=str, short_name='E',
3702
help='Turn on a selftest debug flag.'),
3703
ListOption('starting-with', type=str, argname='TESTID',
3704
param_name='starting_with', short_name='s',
3706
'Load only the tests starting with TESTID.'),
3708
2563
encoding_type = 'replace'
3711
Command.__init__(self)
3712
self.additional_selftest_args = {}
3714
2565
def run(self, testspecs_list=None, verbose=False, one=False,
3715
2566
transport=None, benchmark=None,
2567
lsprof_timed=None, cache_dir=None,
3717
2568
first=False, list_only=False,
3718
randomize=None, exclude=None, strict=False,
3719
load_list=None, debugflag=None, starting_with=None, subunit=False,
3720
parallel=None, lsprof_tests=False):
3721
from bzrlib import tests
2569
randomize=None, exclude=None, strict=False):
2571
from bzrlib.tests import selftest
2572
import bzrlib.benchmarks as benchmarks
2573
from bzrlib.benchmarks import tree_creator
2575
if cache_dir is not None:
2576
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2578
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2579
print ' %s (%s python%s)' % (
2581
bzrlib.version_string,
2582
'.'.join(map(str, sys.version_info)),
3723
2585
if testspecs_list is not None:
3724
2586
pattern = '|'.join(testspecs_list)
3729
from bzrlib.tests import SubUnitBzrRunner
3731
raise errors.BzrCommandError("subunit not available. subunit "
3732
"needs to be installed to use --subunit.")
3733
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3734
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3735
# stdout, which would corrupt the subunit stream.
3736
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3737
# following code can be deleted when it's sufficiently deployed
3738
# -- vila/mgz 20100514
3739
if (sys.platform == "win32"
3740
and getattr(sys.stdout, 'fileno', None) is not None):
3742
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3744
self.additional_selftest_args.setdefault(
3745
'suite_decorators', []).append(parallel)
3747
raise errors.BzrCommandError(
3748
"--benchmark is no longer supported from bzr 2.2; "
3749
"use bzr-usertest instead")
3750
test_suite_factory = None
3751
selftest_kwargs = {"verbose": verbose,
3753
"stop_on_failure": one,
3754
"transport": transport,
3755
"test_suite_factory": test_suite_factory,
3756
"lsprof_timed": lsprof_timed,
3757
"lsprof_tests": lsprof_tests,
3758
"matching_tests_first": first,
3759
"list_only": list_only,
3760
"random_seed": randomize,
3761
"exclude_pattern": exclude,
3763
"load_list": load_list,
3764
"debug_flags": debugflag,
3765
"starting_with": starting_with
3767
selftest_kwargs.update(self.additional_selftest_args)
3769
# Make deprecation warnings visible, unless -Werror is set
3770
cleanup = symbol_versioning.activate_deprecation_warnings(
2590
test_suite_factory = benchmarks.test_suite
2591
# Unless user explicitly asks for quiet, be verbose in benchmarks
2592
verbose = not is_quiet()
2593
# TODO: should possibly lock the history file...
2594
benchfile = open(".perf_history", "at", buffering=1)
2596
test_suite_factory = None
3773
result = tests.selftest(**selftest_kwargs)
2599
result = selftest(verbose=verbose,
2601
stop_on_failure=one,
2602
transport=transport,
2603
test_suite_factory=test_suite_factory,
2604
lsprof_timed=lsprof_timed,
2605
bench_history=benchfile,
2606
matching_tests_first=first,
2607
list_only=list_only,
2608
random_seed=randomize,
2609
exclude_pattern=exclude,
2613
if benchfile is not None:
2616
info('tests passed')
2618
info('tests failed')
3776
2619
return int(not result)
3779
2622
class cmd_version(Command):
3780
__doc__ = """Show version of bzr."""
2623
"""Show version of bzr."""
3782
2625
encoding_type = 'replace'
3784
Option("short", help="Print just the version number."),
3787
2627
@display_command
3788
def run(self, short=False):
3789
2629
from bzrlib.version import show_version
3791
self.outf.write(bzrlib.version_string + '\n')
3793
show_version(to_file=self.outf)
2630
show_version(to_file=self.outf)
3796
2633
class cmd_rocks(Command):
3797
__doc__ = """Statement of optimism."""
2634
"""Statement of optimism."""
3801
2638
@display_command
3803
self.outf.write("It sure does!\n")
2640
print "It sure does!"
3806
2643
class cmd_find_merge_base(Command):
3807
__doc__ = """Find and print a base revision for merging two branches."""
2644
"""Find and print a base revision for merging two branches."""
3808
2645
# TODO: Options to specify revisions on either side, as if
3809
2646
# merging only part of the history.
3810
2647
takes_args = ['branch', 'other']
3813
2650
@display_command
3814
2651
def run(self, branch, other):
3815
2652
from bzrlib.revision import ensure_null
3817
2654
branch1 = Branch.open_containing(branch)[0]
3818
2655
branch2 = Branch.open_containing(other)[0]
3819
self.add_cleanup(branch1.lock_read().unlock)
3820
self.add_cleanup(branch2.lock_read().unlock)
3821
2657
last1 = ensure_null(branch1.last_revision())
3822
2658
last2 = ensure_null(branch2.last_revision())
3824
2660
graph = branch1.repository.get_graph(branch2.repository)
3825
2661
base_rev_id = graph.find_unique_lca(last1, last2)
3827
self.outf.write('merge base is revision %s\n' % base_rev_id)
2663
print 'merge base is revision %s' % base_rev_id
3830
2666
class cmd_merge(Command):
3831
__doc__ = """Perform a three-way merge.
3833
The source of the merge can be specified either in the form of a branch,
3834
or in the form of a path to a file containing a merge directive generated
3835
with bzr send. If neither is specified, the default is the upstream branch
3836
or the branch most recently merged using --remember.
3838
When merging from a branch, by default bzr will try to merge in all new
3839
work from the other branch, automatically determining an appropriate base
3840
revision. If this fails, you may need to give an explicit base.
3842
To pick a different ending revision, pass "--revision OTHER". bzr will
3843
try to merge in all new work up to and including revision OTHER.
3845
If you specify two values, "--revision BASE..OTHER", only revisions BASE
3846
through OTHER, excluding BASE but including OTHER, will be merged. If this
3847
causes some revisions to be skipped, i.e. if the destination branch does
3848
not already contain revision BASE, such a merge is commonly referred to as
3851
Revision numbers are always relative to the source branch.
2667
"""Perform a three-way merge.
2669
The branch is the branch you will merge from. By default, it will merge
2670
the latest revision. If you specify a revision, that revision will be
2671
merged. If you specify two revisions, the first will be used as a BASE,
2672
and the second one as OTHER. Revision numbers are always relative to the
2675
By default, bzr will try to merge in all new work from the other
2676
branch, automatically determining an appropriate base. If this
2677
fails, you may need to give an explicit base.
3853
2679
Merge will do its best to combine the changes in two branches, but there
3854
2680
are some kinds of problems only a human can fix. When it encounters those,
3855
2681
it will mark a conflict. A conflict means that you need to fix something,
3946
2753
allow_pending = True
3947
2754
verified = 'inapplicable'
3948
2755
tree = WorkingTree.open_containing(directory)[0]
3951
basis_tree = tree.revision_tree(tree.last_revision())
3952
except errors.NoSuchRevision:
3953
basis_tree = tree.basis_tree()
3955
# die as quickly as possible if there are uncommitted changes
3957
if tree.has_changes():
3958
raise errors.UncommittedChanges(tree)
3960
view_info = _get_view_info_for_change_reporter(tree)
3961
2756
change_reporter = delta._ChangeReporter(
3962
unversioned_filter=tree.is_ignored, view_info=view_info)
3963
pb = ui.ui_factory.nested_progress_bar()
3964
self.add_cleanup(pb.finished)
3965
self.add_cleanup(tree.lock_write().unlock)
3966
if location is not None:
3968
mergeable = bundle.read_mergeable_from_url(location,
3969
possible_transports=possible_transports)
3970
except errors.NotABundle:
2757
unversioned_filter=tree.is_ignored)
2760
pb = ui.ui_factory.nested_progress_bar()
2761
cleanups.append(pb.finished)
2763
cleanups.append(tree.unlock)
2764
if location is not None:
2765
mergeable, other_transport = _get_mergeable_helper(location)
2768
raise errors.BzrCommandError('Cannot use --uncommitted'
2769
' with bundles or merge directives.')
2771
if revision is not None:
2772
raise errors.BzrCommandError(
2773
'Cannot use -r with merge directives or bundles')
2774
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2776
possible_transports.append(other_transport)
2778
if merger is None and uncommitted:
2779
if revision is not None and len(revision) > 0:
2780
raise errors.BzrCommandError('Cannot use --uncommitted and'
2781
' --revision at the same time.')
2782
location = self._select_branch_location(tree, location)[0]
2783
other_tree, other_path = WorkingTree.open_containing(location)
2784
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2786
allow_pending = False
2789
merger, allow_pending = self._get_merger_from_branch(tree,
2790
location, revision, remember, possible_transports, pb)
2792
merger.merge_type = merge_type
2793
merger.reprocess = reprocess
2794
merger.show_base = show_base
2795
merger.change_reporter = change_reporter
2796
self.sanity_check_merger(merger)
2797
if (merger.base_rev_id == merger.other_rev_id and
2798
merger.other_rev_id != None):
2799
note('Nothing to do.')
2802
if merger.interesting_files is not None:
2803
raise errors.BzrCommandError('Cannot pull individual files')
2804
if (merger.base_rev_id == tree.last_revision()):
2805
result = tree.pull(merger.other_branch, False,
2806
merger.other_rev_id)
2807
result.report(self.outf)
2809
merger.check_basis(not force)
2810
conflict_count = merger.do_merge()
2812
merger.set_pending()
2813
if verified == 'failed':
2814
warning('Preview patch does not match changes')
2815
if conflict_count != 0:
3974
raise errors.BzrCommandError('Cannot use --uncommitted'
3975
' with bundles or merge directives.')
3977
if revision is not None:
3978
raise errors.BzrCommandError(
3979
'Cannot use -r with merge directives or bundles')
3980
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3983
if merger is None and uncommitted:
3984
if revision is not None and len(revision) > 0:
3985
raise errors.BzrCommandError('Cannot use --uncommitted and'
3986
' --revision at the same time.')
3987
merger = self.get_merger_from_uncommitted(tree, location, None)
3988
allow_pending = False
3991
merger, allow_pending = self._get_merger_from_branch(tree,
3992
location, revision, remember, possible_transports, None)
3994
merger.merge_type = merge_type
3995
merger.reprocess = reprocess
3996
merger.show_base = show_base
3997
self.sanity_check_merger(merger)
3998
if (merger.base_rev_id == merger.other_rev_id and
3999
merger.other_rev_id is not None):
4000
note('Nothing to do.')
4002
if pull and not preview:
4003
if merger.interesting_files is not None:
4004
raise errors.BzrCommandError('Cannot pull individual files')
4005
if (merger.base_rev_id == tree.last_revision()):
4006
result = tree.pull(merger.other_branch, False,
4007
merger.other_rev_id)
4008
result.report(self.outf)
4010
if merger.this_basis is None:
4011
raise errors.BzrCommandError(
4012
"This branch has no commits."
4013
" (perhaps you would prefer 'bzr pull')")
4015
return self._do_preview(merger)
4017
return self._do_interactive(merger)
4019
return self._do_merge(merger, change_reporter, allow_pending,
4022
def _get_preview(self, merger):
4023
tree_merger = merger.make_merger()
4024
tt = tree_merger.make_preview_transform()
4025
self.add_cleanup(tt.finalize)
4026
result_tree = tt.get_preview_tree()
4029
def _do_preview(self, merger):
4030
from bzrlib.diff import show_diff_trees
4031
result_tree = self._get_preview(merger)
4032
path_encoding = osutils.get_diff_header_encoding()
4033
show_diff_trees(merger.this_tree, result_tree, self.outf,
4034
old_label='', new_label='',
4035
path_encoding=path_encoding)
4037
def _do_merge(self, merger, change_reporter, allow_pending, verified):
4038
merger.change_reporter = change_reporter
4039
conflict_count = merger.do_merge()
4041
merger.set_pending()
4042
if verified == 'failed':
4043
warning('Preview patch does not match changes')
4044
if conflict_count != 0:
4049
def _do_interactive(self, merger):
4050
"""Perform an interactive merge.
4052
This works by generating a preview tree of the merge, then using
4053
Shelver to selectively remove the differences between the working tree
4054
and the preview tree.
4056
from bzrlib import shelf_ui
4057
result_tree = self._get_preview(merger)
4058
writer = bzrlib.option.diff_writer_registry.get()
4059
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4060
reporter=shelf_ui.ApplyReporter(),
4061
diff_writer=writer(sys.stdout))
2820
for cleanup in reversed(cleanups):
4067
2823
def sanity_check_merger(self, merger):
4068
2824
if (merger.show_base and
4069
2825
not merger.merge_type is _mod_merge.Merge3Merger):
4070
2826
raise errors.BzrCommandError("Show-base is not supported for this"
4071
2827
" merge type. %s" % merger.merge_type)
4072
if merger.reprocess is None:
4073
if merger.show_base:
4074
merger.reprocess = False
4076
# Use reprocess if the merger supports it
4077
merger.reprocess = merger.merge_type.supports_reprocess
4078
2828
if merger.reprocess and not merger.merge_type.supports_reprocess:
4079
2829
raise errors.BzrCommandError("Conflict reduction is not supported"
4080
2830
" for merge type %s." %
4225
2962
def run(self, file_list=None, merge_type=None, show_base=False,
4226
2963
reprocess=False):
4227
from bzrlib.conflicts import restore
4228
2964
if merge_type is None:
4229
2965
merge_type = _mod_merge.Merge3Merger
4230
tree, file_list = WorkingTree.open_containing_paths(file_list)
4231
self.add_cleanup(tree.lock_write().unlock)
4232
parents = tree.get_parent_ids()
4233
if len(parents) != 2:
4234
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4235
" merges. Not cherrypicking or"
4237
repository = tree.branch.repository
4238
interesting_ids = None
4240
conflicts = tree.conflicts()
4241
if file_list is not None:
4242
interesting_ids = set()
4243
for filename in file_list:
4244
file_id = tree.path2id(filename)
4246
raise errors.NotVersionedError(filename)
4247
interesting_ids.add(file_id)
4248
if tree.kind(file_id) != "directory":
4251
for name, ie in tree.inventory.iter_entries(file_id):
4252
interesting_ids.add(ie.file_id)
4253
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4255
# Remerge only supports resolving contents conflicts
4256
allowed_conflicts = ('text conflict', 'contents conflict')
4257
restore_files = [c.path for c in conflicts
4258
if c.typestring in allowed_conflicts]
4259
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4260
tree.set_conflicts(ConflictList(new_conflicts))
4261
if file_list is not None:
4262
restore_files = file_list
4263
for filename in restore_files:
2966
tree, file_list = tree_files(file_list)
2969
parents = tree.get_parent_ids()
2970
if len(parents) != 2:
2971
raise errors.BzrCommandError("Sorry, remerge only works after normal"
2972
" merges. Not cherrypicking or"
2974
repository = tree.branch.repository
2975
graph = repository.get_graph()
2976
base_revision = graph.find_unique_lca(parents[0], parents[1])
2977
base_tree = repository.revision_tree(base_revision)
2978
other_tree = repository.revision_tree(parents[1])
2979
interesting_ids = None
2981
conflicts = tree.conflicts()
2982
if file_list is not None:
2983
interesting_ids = set()
2984
for filename in file_list:
2985
file_id = tree.path2id(filename)
2987
raise errors.NotVersionedError(filename)
2988
interesting_ids.add(file_id)
2989
if tree.kind(file_id) != "directory":
2992
for name, ie in tree.inventory.iter_entries(file_id):
2993
interesting_ids.add(ie.file_id)
2994
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2996
# Remerge only supports resolving contents conflicts
2997
allowed_conflicts = ('text conflict', 'contents conflict')
2998
restore_files = [c.path for c in conflicts
2999
if c.typestring in allowed_conflicts]
3000
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3001
tree.set_conflicts(ConflictList(new_conflicts))
3002
if file_list is not None:
3003
restore_files = file_list
3004
for filename in restore_files:
3006
restore(tree.abspath(filename))
3007
except errors.NotConflicted:
3009
# Disable pending merges, because the file texts we are remerging
3010
# have not had those merges performed. If we use the wrong parents
3011
# list, we imply that the working tree text has seen and rejected
3012
# all the changes from the other tree, when in fact those changes
3013
# have not yet been seen.
3014
tree.set_parent_ids(parents[:1])
4265
restore(tree.abspath(filename))
4266
except errors.NotConflicted:
4268
# Disable pending merges, because the file texts we are remerging
4269
# have not had those merges performed. If we use the wrong parents
4270
# list, we imply that the working tree text has seen and rejected
4271
# all the changes from the other tree, when in fact those changes
4272
# have not yet been seen.
4273
tree.set_parent_ids(parents[:1])
4275
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4276
merger.interesting_ids = interesting_ids
4277
merger.merge_type = merge_type
4278
merger.show_base = show_base
4279
merger.reprocess = reprocess
4280
conflicts = merger.do_merge()
3016
conflicts = _mod_merge.merge_inner(
3017
tree.branch, other_tree, base_tree,
3019
interesting_ids=interesting_ids,
3020
other_rev_id=parents[1],
3021
merge_type=merge_type,
3022
show_base=show_base,
3023
reprocess=reprocess)
3025
tree.set_parent_ids(parents)
4282
tree.set_parent_ids(parents)
4283
3028
if conflicts > 0:
4499
3199
" or specified.")
4500
3200
display_url = urlutils.unescape_for_display(parent,
4501
3201
self.outf.encoding)
4502
message("Using saved parent location: "
4503
+ display_url + "\n")
3202
self.outf.write("Using last location: " + display_url + "\n")
4505
3204
remote_branch = Branch.open(other_branch)
4506
3205
if remote_branch.base == local_branch.base:
4507
3206
remote_branch = local_branch
4509
self.add_cleanup(remote_branch.lock_read().unlock)
4511
local_revid_range = _revision_range_to_revid_range(
4512
_get_revision_range(my_revision, local_branch,
4515
remote_revid_range = _revision_range_to_revid_range(
4516
_get_revision_range(revision,
4517
remote_branch, self.name()))
4519
local_extra, remote_extra = find_unmerged(
4520
local_branch, remote_branch, restrict,
4521
backward=not reverse,
4522
include_merges=include_merges,
4523
local_revid_range=local_revid_range,
4524
remote_revid_range=remote_revid_range)
4526
if log_format is None:
4527
registry = log.log_formatter_registry
4528
log_format = registry.get_default(local_branch)
4529
lf = log_format(to_file=self.outf,
4531
show_timezone='original')
4534
if local_extra and not theirs_only:
4535
message("You have %d extra revision(s):\n" %
4537
for revision in iter_log_revisions(local_extra,
4538
local_branch.repository,
4540
lf.log_revision(revision)
4541
printed_local = True
4544
printed_local = False
4546
if remote_extra and not mine_only:
4547
if printed_local is True:
4549
message("You are missing %d revision(s):\n" %
4551
for revision in iter_log_revisions(remote_extra,
4552
remote_branch.repository,
4554
lf.log_revision(revision)
4557
if mine_only and not local_extra:
4558
# We checked local, and found nothing extra
4559
message('This branch is up to date.\n')
4560
elif theirs_only and not remote_extra:
4561
# We checked remote, and found nothing extra
4562
message('Other branch is up to date.\n')
4563
elif not (mine_only or theirs_only or local_extra or
4565
# We checked both branches, and neither one had extra
4567
message("Branches are up to date.\n")
3207
local_branch.lock_read()
3209
remote_branch.lock_read()
3211
local_extra, remote_extra = find_unmerged(local_branch,
3213
if log_format is None:
3214
registry = log.log_formatter_registry
3215
log_format = registry.get_default(local_branch)
3216
lf = log_format(to_file=self.outf,
3218
show_timezone='original')
3219
if reverse is False:
3220
local_extra.reverse()
3221
remote_extra.reverse()
3222
if local_extra and not theirs_only:
3223
self.outf.write("You have %d extra revision(s):\n" %
3225
for revision in iter_log_revisions(local_extra,
3226
local_branch.repository,
3228
lf.log_revision(revision)
3229
printed_local = True
3231
printed_local = False
3232
if remote_extra and not mine_only:
3233
if printed_local is True:
3234
self.outf.write("\n\n\n")
3235
self.outf.write("You are missing %d revision(s):\n" %
3237
for revision in iter_log_revisions(remote_extra,
3238
remote_branch.repository,
3240
lf.log_revision(revision)
3241
if not remote_extra and not local_extra:
3243
self.outf.write("Branches are up to date.\n")
3247
remote_branch.unlock()
3249
local_branch.unlock()
4569
3250
if not status_code and parent is None and other_branch is not None:
4570
self.add_cleanup(local_branch.lock_write().unlock)
4571
# handle race conditions - a parent might be set while we run.
4572
if local_branch.get_parent() is None:
4573
local_branch.set_parent(remote_branch.base)
3251
local_branch.lock_write()
3253
# handle race conditions - a parent might be set while we run.
3254
if local_branch.get_parent() is None:
3255
local_branch.set_parent(remote_branch.base)
3257
local_branch.unlock()
4574
3258
return status_code
4577
3261
class cmd_pack(Command):
4578
__doc__ = """Compress the data within a repository.
4580
This operation compresses the data within a bazaar repository. As
4581
bazaar supports automatic packing of repository, this operation is
4582
normally not required to be done manually.
4584
During the pack operation, bazaar takes a backup of existing repository
4585
data, i.e. pack files. This backup is eventually removed by bazaar
4586
automatically when it is safe to do so. To save disk space by removing
4587
the backed up pack files, the --clean-obsolete-packs option may be
4590
Warning: If you use --clean-obsolete-packs and your machine crashes
4591
during or immediately after repacking, you may be left with a state
4592
where the deletion has been written to disk but the new packs have not
4593
been. In this case the repository may be unusable.
3262
"""Compress the data within a repository."""
4596
3264
_see_also = ['repositories']
4597
3265
takes_args = ['branch_or_repo?']
4599
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4602
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3267
def run(self, branch_or_repo='.'):
4603
3268
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4605
3270
branch = dir.open_branch()
4606
3271
repository = branch.repository
4607
3272
except errors.NotBranchError:
4608
3273
repository = dir.open_repository()
4609
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4612
3277
class cmd_plugins(Command):
4613
__doc__ = """List the installed plugins.
4615
This command displays the list of installed plugins including
4616
version of plugin and a short description of each.
4618
--verbose shows the path where each plugin is located.
3278
"""List the installed plugins.
3280
This command displays the list of installed plugins including the
3281
path where each one is located and a short description of each.
4620
3283
A plugin is an external component for Bazaar that extends the
4621
3284
revision control system, by adding or replacing code in Bazaar.
5012
3594
class cmd_serve(Command):
5013
__doc__ = """Run the bzr server."""
3595
"""Run the bzr server."""
5015
3597
aliases = ['server']
5017
3599
takes_options = [
5019
3601
help='Serve on stdin/out for use from inetd or sshd.'),
5020
RegistryOption('protocol',
5021
help="Protocol to serve.",
5022
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
5023
value_switches=True),
5025
3603
help='Listen for connections on nominated port of the form '
5026
3604
'[hostname:]portnumber. Passing 0 as the port number will '
5027
'result in a dynamically allocated port. The default port '
5028
'depends on the protocol.',
3605
'result in a dynamically allocated port. The default port is '
5030
custom_help('directory',
5031
help='Serve contents of this directory.'),
3609
help='Serve contents of this directory.',
5032
3611
Option('allow-writes',
5033
3612
help='By default the server is a readonly server. Supplying '
5034
3613
'--allow-writes enables write access to the contents of '
5035
'the served directory and below. Note that ``bzr serve`` '
5036
'does not perform authentication, so unless some form of '
5037
'external authentication is arranged supplying this '
5038
'option leads to global uncontrolled write access to your '
3614
'the served directory and below.'
5043
def get_host_and_port(self, port):
5044
"""Return the host and port to run the smart server on.
5046
If 'port' is None, None will be returned for the host and port.
5048
If 'port' has a colon in it, the string before the colon will be
5049
interpreted as the host.
5051
:param port: A string of the port to run the server on.
5052
:return: A tuple of (host, port), where 'host' is a host name or IP,
5053
and port is an integer TCP/IP port.
5056
if port is not None:
5058
host, port = port.split(':')
5062
def run(self, port=None, inet=False, directory=None, allow_writes=False,
5064
from bzrlib import transport
3618
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3619
from bzrlib.smart import medium, server
3620
from bzrlib.transport import get_transport
3621
from bzrlib.transport.chroot import ChrootServer
3622
from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
5065
3623
if directory is None:
5066
3624
directory = os.getcwd()
5067
if protocol is None:
5068
protocol = transport.transport_server_registry.get()
5069
host, port = self.get_host_and_port(port)
5070
3625
url = urlutils.local_path_to_url(directory)
5071
3626
if not allow_writes:
5072
3627
url = 'readonly+' + url
5073
t = transport.get_transport(url)
5074
protocol(t, host, port, inet)
3628
chroot_server = ChrootServer(get_transport(url))
3629
chroot_server.setUp()
3630
t = get_transport(chroot_server.get_url())
3632
smart_server = medium.SmartServerPipeStreamMedium(
3633
sys.stdin, sys.stdout, t)
3635
host = BZR_DEFAULT_INTERFACE
3637
port = BZR_DEFAULT_PORT
3640
host, port = port.split(':')
3642
smart_server = server.SmartTCPServer(t, host=host, port=port)
3643
print 'listening on port: ', smart_server.port
3645
# for the duration of this server, no UI output is permitted.
3646
# note that this may cause problems with blackbox tests. This should
3647
# be changed with care though, as we dont want to use bandwidth sending
3648
# progress over stderr to smart server clients!
3649
old_factory = ui.ui_factory
3651
ui.ui_factory = ui.SilentUIFactory()
3652
smart_server.serve()
3654
ui.ui_factory = old_factory
5077
3657
class cmd_join(Command):
5078
__doc__ = """Combine a tree into its containing tree.
5080
This command requires the target tree to be in a rich-root format.
3658
"""Combine a subtree into its containing tree.
3660
This command is for experimental use only. It requires the target tree
3661
to be in dirstate-with-subtree format, which cannot be converted into
5082
3664
The TREE argument should be an independent tree, inside another tree, but
5083
3665
not part of it. (Such trees can be produced by "bzr split", but also by
5084
3666
running "bzr branch" with the target inside a tree.)
5086
The result is a combined tree, with the subtree no longer an independent
3668
The result is a combined tree, with the subtree no longer an independant
5087
3669
part. This is marked as a merge of the subtree into the containing tree,
5088
3670
and all history is preserved.
3672
If --reference is specified, the subtree retains its independence. It can
3673
be branched by itself, and can be part of multiple projects at the same
3674
time. But operations performed in the containing tree, such as commit
3675
and merge, will recurse into the subtree.
5091
3678
_see_also = ['split']
5092
3679
takes_args = ['tree']
5093
3680
takes_options = [
5094
Option('reference', help='Join by reference.', hidden=True),
3681
Option('reference', help='Join by reference.'),
5097
3685
def run(self, tree, reference=False):
5098
3686
sub_tree = WorkingTree.open(tree)
5335
3902
'rather than the one containing the working directory.',
5336
3903
short_name='f',
5338
Option('output', short_name='o',
5339
help='Write merge directive to this file or directory; '
5340
'use - for stdout.',
3905
Option('output', short_name='o', help='Write directive to this file.',
5343
help='Refuse to send if there are uncommitted changes in'
5344
' the working tree, --no-strict disables the check.'),
5345
3907
Option('mail-to', help='Mail the request to this address.',
5349
Option('body', help='Body for the email.', type=unicode),
5350
RegistryOption('format',
5351
help='Use the specified output format.',
5352
lazy_registry=('bzrlib.send', 'format_registry')),
3911
RegistryOption.from_kwargs('format',
3912
'Use the specified output format.',
3913
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
3914
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5355
3917
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5356
3918
no_patch=False, revision=None, remember=False, output=None,
5357
format=None, mail_to=None, message=None, body=None,
5358
strict=None, **kwargs):
5359
from bzrlib.send import send
5360
return send(submit_branch, revision, public_branch, remember,
5361
format, no_bundle, no_patch, output,
5362
kwargs.get('from', '.'), mail_to, message, body,
3919
format='4', mail_to=None, message=None, **kwargs):
3920
return self._run(submit_branch, revision, public_branch, remember,
3921
format, no_bundle, no_patch, output,
3922
kwargs.get('from', '.'), mail_to, message)
3924
def _run(self, submit_branch, revision, public_branch, remember, format,
3925
no_bundle, no_patch, output, from_, mail_to, message):
3926
from bzrlib.revision import NULL_REVISION
3928
outfile = StringIO()
3932
outfile = open(output, 'wb')
3934
branch = Branch.open_containing(from_)[0]
3936
config = branch.get_config()
3938
mail_to = config.get_user_option('submit_to')
3940
raise errors.BzrCommandError('No mail-to address'
3942
mail_client = config.get_mail_client()
3943
if remember and submit_branch is None:
3944
raise errors.BzrCommandError(
3945
'--remember requires a branch to be specified.')
3946
stored_submit_branch = branch.get_submit_branch()
3947
remembered_submit_branch = False
3948
if submit_branch is None:
3949
submit_branch = stored_submit_branch
3950
remembered_submit_branch = True
3952
if stored_submit_branch is None or remember:
3953
branch.set_submit_branch(submit_branch)
3954
if submit_branch is None:
3955
submit_branch = branch.get_parent()
3956
remembered_submit_branch = True
3957
if submit_branch is None:
3958
raise errors.BzrCommandError('No submit branch known or'
3960
if remembered_submit_branch:
3961
note('Using saved location: %s', submit_branch)
3963
stored_public_branch = branch.get_public_branch()
3964
if public_branch is None:
3965
public_branch = stored_public_branch
3966
elif stored_public_branch is None or remember:
3967
branch.set_public_branch(public_branch)
3968
if no_bundle and public_branch is None:
3969
raise errors.BzrCommandError('No public branch specified or'
3971
base_revision_id = None
3973
if revision is not None:
3974
if len(revision) > 2:
3975
raise errors.BzrCommandError('bzr send takes '
3976
'at most two one revision identifiers')
3977
revision_id = revision[-1].in_history(branch).rev_id
3978
if len(revision) == 2:
3979
base_revision_id = revision[0].in_history(branch).rev_id
3980
if revision_id is None:
3981
revision_id = branch.last_revision()
3982
if revision_id == NULL_REVISION:
3983
raise errors.BzrCommandError('No revisions to submit.')
3985
directive = merge_directive.MergeDirective2.from_objects(
3986
branch.repository, revision_id, time.time(),
3987
osutils.local_time_offset(), submit_branch,
3988
public_branch=public_branch, include_patch=not no_patch,
3989
include_bundle=not no_bundle, message=message,
3990
base_revision_id=base_revision_id)
3991
elif format == '0.9':
3994
patch_type = 'bundle'
3996
raise errors.BzrCommandError('Format 0.9 does not'
3997
' permit bundle with no patch')
4003
directive = merge_directive.MergeDirective.from_objects(
4004
branch.repository, revision_id, time.time(),
4005
osutils.local_time_offset(), submit_branch,
4006
public_branch=public_branch, patch_type=patch_type,
4009
outfile.writelines(directive.to_lines())
4011
subject = '[MERGE] '
4012
if message is not None:
4015
revision = branch.repository.get_revision(revision_id)
4016
subject += revision.get_summary()
4017
mail_client.compose_merge_request(mail_to, subject,
5367
4024
class cmd_bundle_revisions(cmd_send):
5368
__doc__ = """Create a merge-directive for submitting changes.
4026
"""Create a merge-directive for submiting changes.
5370
4028
A merge directive provides many things needed for requesting merges:
5447
4101
Tags are stored in the branch. Tags are copied from one branch to another
5448
4102
along when you branch, push, pull or merge.
5450
It is an error to give a tag name that already exists unless you pass
4104
It is an error to give a tag name that already exists unless you pass
5451
4105
--force, in which case the tag is moved to point to the new revision.
5453
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5454
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5456
If no tag name is specified it will be determined through the
5457
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5458
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5462
4108
_see_also = ['commit', 'tags']
5463
takes_args = ['tag_name?']
4109
takes_args = ['tag_name']
5464
4110
takes_options = [
5465
4111
Option('delete',
5466
4112
help='Delete this tag rather than placing it.',
5468
custom_help('directory',
5469
help='Branch in which to place the tag.'),
4115
help='Branch in which to place the tag.',
5470
4119
Option('force',
5471
4120
help='Replace existing tags.',
5476
def run(self, tag_name=None,
4125
def run(self, tag_name,
5482
4131
branch, relpath = Branch.open_containing(directory)
5483
self.add_cleanup(branch.lock_write().unlock)
5485
if tag_name is None:
5486
raise errors.BzrCommandError("No tag specified to delete.")
5487
branch.tags.delete_tag(tag_name)
5488
note('Deleted tag %s.' % tag_name)
5491
if len(revision) != 1:
5492
raise errors.BzrCommandError(
5493
"Tags can only be placed on a single revision, "
5495
revision_id = revision[0].as_revision_id(branch)
4135
branch.tags.delete_tag(tag_name)
4136
self.outf.write('Deleted tag %s.\n' % tag_name)
5497
revision_id = branch.last_revision()
5498
if tag_name is None:
5499
tag_name = branch.automatic_tag_name(revision_id)
5500
if tag_name is None:
5501
raise errors.BzrCommandError(
5502
"Please specify a tag name.")
5503
if (not force) and branch.tags.has_tag(tag_name):
5504
raise errors.TagAlreadyExists(tag_name)
5505
branch.tags.set_tag(tag_name, revision_id)
5506
note('Created tag %s.' % tag_name)
4139
if len(revision) != 1:
4140
raise errors.BzrCommandError(
4141
"Tags can only be placed on a single revision, "
4143
revision_id = revision[0].in_history(branch).rev_id
4145
revision_id = branch.last_revision()
4146
if (not force) and branch.tags.has_tag(tag_name):
4147
raise errors.TagAlreadyExists(tag_name)
4148
branch.tags.set_tag(tag_name, revision_id)
4149
self.outf.write('Created tag %s.\n' % tag_name)
5509
4154
class cmd_tags(Command):
5510
__doc__ = """List tags.
5512
This command shows a table of tag names and the revisions they reference.
4157
This tag shows a table of tag names and the revisions they reference.
5515
4160
_see_also = ['tag']
5516
4161
takes_options = [
5517
custom_help('directory',
5518
help='Branch whose tags should be displayed.'),
5519
RegistryOption('sort',
5520
'Sort tags by different criteria.', title='Sorting',
5521
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
4163
help='Branch whose tags should be displayed.',
5527
4169
@display_command
5528
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5529
from bzrlib.tag import tag_sort_methods
5530
4173
branch, relpath = Branch.open_containing(directory)
5532
tags = branch.tags.get_tag_dict().items()
5536
self.add_cleanup(branch.lock_read().unlock)
5538
graph = branch.repository.get_graph()
5539
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5540
revid1, revid2 = rev1.rev_id, rev2.rev_id
5541
# only show revisions between revid1 and revid2 (inclusive)
5542
tags = [(tag, revid) for tag, revid in tags if
5543
graph.is_between(revid, revid1, revid2)]
5545
sort = tag_sort_methods.get()
5548
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5549
for index, (tag, revid) in enumerate(tags):
5551
revno = branch.revision_id_to_dotted_revno(revid)
5552
if isinstance(revno, tuple):
5553
revno = '.'.join(map(str, revno))
5554
except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
5555
# Bad tag data/merges can lead to tagged revisions
5556
# which are not in this branch. Fail gracefully ...
5558
tags[index] = (tag, revno)
5560
for tag, revspec in tags:
5561
self.outf.write('%-20s %s\n' % (tag, revspec))
4174
for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4175
self.outf.write('%-20s %s\n' % (tag_name, target))
5564
4178
class cmd_reconfigure(Command):
5565
__doc__ = """Reconfigure the type of a bzr directory.
4179
"""Reconfigure the type of a bzr directory.
5567
4181
A target configuration must be specified.
5575
4189
If none of these is available, --bind-to must be specified.
5578
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5579
4192
takes_args = ['location?']
5581
RegistryOption.from_kwargs(
5583
title='Target type',
5584
help='The type to reconfigure the directory to.',
5585
value_switches=True, enum_switch=False,
5586
branch='Reconfigure to be an unbound branch with no working tree.',
5587
tree='Reconfigure to be an unbound branch with a working tree.',
5588
checkout='Reconfigure to be a bound branch with a working tree.',
5589
lightweight_checkout='Reconfigure to be a lightweight'
5590
' checkout (with no local history).',
5591
standalone='Reconfigure to be a standalone branch '
5592
'(i.e. stop using shared repository).',
5593
use_shared='Reconfigure to use a shared repository.',
5594
with_trees='Reconfigure repository to create '
5595
'working trees on branches by default.',
5596
with_no_trees='Reconfigure repository to not create '
5597
'working trees on branches by default.'
5599
Option('bind-to', help='Branch to bind checkout to.', type=str),
5601
help='Perform reconfiguration even if local changes'
5603
Option('stacked-on',
5604
help='Reconfigure a branch to be stacked on another branch.',
5608
help='Reconfigure a branch to be unstacked. This '
5609
'may require copying substantial data into it.',
4193
takes_options = [RegistryOption.from_kwargs('target_type',
4194
title='Target type',
4195
help='The type to reconfigure the directory to.',
4196
value_switches=True, enum_switch=False,
4197
branch='Reconfigure to a branch.',
4198
tree='Reconfigure to a tree.',
4199
checkout='Reconfigure to a checkout.'),
4200
Option('bind-to', help='Branch to bind checkout to.',
4203
help='Perform reconfiguration even if local changes'
5613
def run(self, location=None, target_type=None, bind_to=None, force=False,
4207
def run(self, location=None, target_type=None, bind_to=None, force=False):
5616
4208
directory = bzrdir.BzrDir.open(location)
5617
if stacked_on and unstacked:
5618
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5619
elif stacked_on is not None:
5620
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5622
reconfigure.ReconfigureUnstacked().apply(directory)
5623
# At the moment you can use --stacked-on and a different
5624
# reconfiguration shape at the same time; there seems no good reason
5626
4209
if target_type is None:
5627
if stacked_on or unstacked:
5630
raise errors.BzrCommandError('No target configuration '
4210
raise errors.BzrCommandError('No target configuration specified')
5632
4211
elif target_type == 'branch':
5633
4212
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5634
4213
elif target_type == 'tree':
5635
4214
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5636
4215
elif target_type == 'checkout':
5637
reconfiguration = reconfigure.Reconfigure.to_checkout(
5639
elif target_type == 'lightweight-checkout':
5640
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5642
elif target_type == 'use-shared':
5643
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5644
elif target_type == 'standalone':
5645
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5646
elif target_type == 'with-trees':
5647
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5649
elif target_type == 'with-no-trees':
5650
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
4216
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
5652
4218
reconfiguration.apply(force)
5655
class cmd_switch(Command):
5656
__doc__ = """Set the branch of a checkout and update.
5658
For lightweight checkouts, this changes the branch being referenced.
5659
For heavyweight checkouts, this checks that there are no local commits
5660
versus the current bound branch, then it makes the local branch a mirror
5661
of the new location and binds to it.
5663
In both cases, the working tree is updated and uncommitted changes
5664
are merged. The user can commit or revert these as they desire.
5666
Pending merges need to be committed or reverted before using switch.
5668
The path to the branch to switch to can be specified relative to the parent
5669
directory of the current branch. For example, if you are currently in a
5670
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5673
Bound branches use the nickname of its master branch unless it is set
5674
locally, in which case switching will update the local nickname to be
5678
takes_args = ['to_location?']
5679
takes_options = ['directory',
5681
help='Switch even if local commits will be lost.'),
5683
Option('create-branch', short_name='b',
5684
help='Create the target branch from this one before'
5685
' switching to it.'),
5688
def run(self, to_location=None, force=False, create_branch=False,
5689
revision=None, directory=u'.'):
5690
from bzrlib import switch
5691
tree_location = directory
5692
revision = _get_one_revision('switch', revision)
5693
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5694
if to_location is None:
5695
if revision is None:
5696
raise errors.BzrCommandError('You must supply either a'
5697
' revision or a location')
5698
to_location = tree_location
5700
branch = control_dir.open_branch()
5701
had_explicit_nick = branch.get_config().has_explicit_nickname()
5702
except errors.NotBranchError:
5704
had_explicit_nick = False
5707
raise errors.BzrCommandError('cannot create branch without'
5709
to_location = directory_service.directories.dereference(
5711
if '/' not in to_location and '\\' not in to_location:
5712
# This path is meant to be relative to the existing branch
5713
this_url = self._get_branch_location(control_dir)
5714
to_location = urlutils.join(this_url, '..', to_location)
5715
to_branch = branch.bzrdir.sprout(to_location,
5716
possible_transports=[branch.bzrdir.root_transport],
5717
source_branch=branch).open_branch()
5720
to_branch = Branch.open(to_location)
5721
except errors.NotBranchError:
5722
this_url = self._get_branch_location(control_dir)
5723
to_branch = Branch.open(
5724
urlutils.join(this_url, '..', to_location))
5725
if revision is not None:
5726
revision = revision.as_revision_id(to_branch)
5727
switch.switch(control_dir, to_branch, force, revision_id=revision)
5728
if had_explicit_nick:
5729
branch = control_dir.open_branch() #get the new branch!
5730
branch.nick = to_branch.nick
5731
note('Switched to branch: %s',
5732
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5734
def _get_branch_location(self, control_dir):
5735
"""Return location of branch for this control dir."""
5737
this_branch = control_dir.open_branch()
5738
# This may be a heavy checkout, where we want the master branch
5739
master_location = this_branch.get_bound_location()
5740
if master_location is not None:
5741
return master_location
5742
# If not, use a local sibling
5743
return this_branch.base
5744
except errors.NotBranchError:
5745
format = control_dir.find_branch_format()
5746
if getattr(format, 'get_reference', None) is not None:
5747
return format.get_reference(control_dir)
5749
return control_dir.root_transport.base
5752
class cmd_view(Command):
5753
__doc__ = """Manage filtered views.
5755
Views provide a mask over the tree so that users can focus on
5756
a subset of a tree when doing their work. After creating a view,
5757
commands that support a list of files - status, diff, commit, etc -
5758
effectively have that list of files implicitly given each time.
5759
An explicit list of files can still be given but those files
5760
must be within the current view.
5762
In most cases, a view has a short life-span: it is created to make
5763
a selected change and is deleted once that change is committed.
5764
At other times, you may wish to create one or more named views
5765
and switch between them.
5767
To disable the current view without deleting it, you can switch to
5768
the pseudo view called ``off``. This can be useful when you need
5769
to see the whole tree for an operation or two (e.g. merge) but
5770
want to switch back to your view after that.
5773
To define the current view::
5775
bzr view file1 dir1 ...
5777
To list the current view::
5781
To delete the current view::
5785
To disable the current view without deleting it::
5787
bzr view --switch off
5789
To define a named view and switch to it::
5791
bzr view --name view-name file1 dir1 ...
5793
To list a named view::
5795
bzr view --name view-name
5797
To delete a named view::
5799
bzr view --name view-name --delete
5801
To switch to a named view::
5803
bzr view --switch view-name
5805
To list all views defined::
5809
To delete all views::
5811
bzr view --delete --all
5815
takes_args = ['file*']
5818
help='Apply list or delete action to all views.',
5821
help='Delete the view.',
5824
help='Name of the view to define, list or delete.',
5828
help='Name of the view to switch to.',
5833
def run(self, file_list,
5839
tree, file_list = WorkingTree.open_containing_paths(file_list,
5841
current_view, view_dict = tree.views.get_view_info()
5846
raise errors.BzrCommandError(
5847
"Both --delete and a file list specified")
5849
raise errors.BzrCommandError(
5850
"Both --delete and --switch specified")
5852
tree.views.set_view_info(None, {})
5853
self.outf.write("Deleted all views.\n")
5855
raise errors.BzrCommandError("No current view to delete")
5857
tree.views.delete_view(name)
5858
self.outf.write("Deleted '%s' view.\n" % name)
5861
raise errors.BzrCommandError(
5862
"Both --switch and a file list specified")
5864
raise errors.BzrCommandError(
5865
"Both --switch and --all specified")
5866
elif switch == 'off':
5867
if current_view is None:
5868
raise errors.BzrCommandError("No current view to disable")
5869
tree.views.set_view_info(None, view_dict)
5870
self.outf.write("Disabled '%s' view.\n" % (current_view))
5872
tree.views.set_view_info(switch, view_dict)
5873
view_str = views.view_display_str(tree.views.lookup_view())
5874
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5877
self.outf.write('Views defined:\n')
5878
for view in sorted(view_dict):
5879
if view == current_view:
5883
view_str = views.view_display_str(view_dict[view])
5884
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5886
self.outf.write('No views defined.\n')
5889
# No name given and no current view set
5892
raise errors.BzrCommandError(
5893
"Cannot change the 'off' pseudo view")
5894
tree.views.set_view(name, sorted(file_list))
5895
view_str = views.view_display_str(tree.views.lookup_view())
5896
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5900
# No name given and no current view set
5901
self.outf.write('No current view.\n')
5903
view_str = views.view_display_str(tree.views.lookup_view(name))
5904
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5907
class cmd_hooks(Command):
5908
__doc__ = """Show hooks."""
5913
for hook_key in sorted(hooks.known_hooks.keys()):
5914
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5915
self.outf.write("%s:\n" % type(some_hooks).__name__)
5916
for hook_name, hook_point in sorted(some_hooks.items()):
5917
self.outf.write(" %s:\n" % (hook_name,))
5918
found_hooks = list(hook_point)
5920
for hook in found_hooks:
5921
self.outf.write(" %s\n" %
5922
(some_hooks.get_hook_name(hook),))
5924
self.outf.write(" <no hooks installed>\n")
5927
class cmd_remove_branch(Command):
5928
__doc__ = """Remove a branch.
5930
This will remove the branch from the specified location but
5931
will keep any working tree or repository in place.
5935
Remove the branch at repo/trunk::
5937
bzr remove-branch repo/trunk
5941
takes_args = ["location?"]
5943
aliases = ["rmbranch"]
5945
def run(self, location=None):
5946
if location is None:
5948
branch = Branch.open_containing(location)[0]
5949
branch.bzrdir.destroy_branch()
5952
class cmd_shelve(Command):
5953
__doc__ = """Temporarily set aside some changes from the current tree.
5955
Shelve allows you to temporarily put changes you've made "on the shelf",
5956
ie. out of the way, until a later time when you can bring them back from
5957
the shelf with the 'unshelve' command. The changes are stored alongside
5958
your working tree, and so they aren't propagated along with your branch nor
5959
will they survive its deletion.
5961
If shelve --list is specified, previously-shelved changes are listed.
5963
Shelve is intended to help separate several sets of changes that have
5964
been inappropriately mingled. If you just want to get rid of all changes
5965
and you don't need to restore them later, use revert. If you want to
5966
shelve all text changes at once, use shelve --all.
5968
If filenames are specified, only the changes to those files will be
5969
shelved. Other files will be left untouched.
5971
If a revision is specified, changes since that revision will be shelved.
5973
You can put multiple items on the shelf, and by default, 'unshelve' will
5974
restore the most recently shelved changes.
5976
For complicated changes, it is possible to edit the changes in a separate
5977
editor program to decide what the file remaining in the working copy
5978
should look like. To do this, add the configuration option
5980
change_editor = PROGRAM @new_path @old_path
5982
where @new_path is replaced with the path of the new version of the
5983
file and @old_path is replaced with the path of the old version of
5984
the file. The PROGRAM should save the new file with the desired
5985
contents of the file in the working tree.
5989
takes_args = ['file*']
5994
Option('all', help='Shelve all changes.'),
5996
RegistryOption('writer', 'Method to use for writing diffs.',
5997
bzrlib.option.diff_writer_registry,
5998
value_switches=True, enum_switch=False),
6000
Option('list', help='List shelved changes.'),
6002
help='Destroy removed changes instead of shelving them.'),
6004
_see_also = ['unshelve', 'configuration']
6006
def run(self, revision=None, all=False, file_list=None, message=None,
6007
writer=None, list=False, destroy=False, directory=None):
6009
return self.run_for_list(directory=directory)
6010
from bzrlib.shelf_ui import Shelver
6012
writer = bzrlib.option.diff_writer_registry.get()
6014
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6015
file_list, message, destroy=destroy, directory=directory)
6020
except errors.UserAbort:
6023
def run_for_list(self, directory=None):
6024
if directory is None:
6026
tree = WorkingTree.open_containing(directory)[0]
6027
self.add_cleanup(tree.lock_read().unlock)
6028
manager = tree.get_shelf_manager()
6029
shelves = manager.active_shelves()
6030
if len(shelves) == 0:
6031
note('No shelved changes.')
6033
for shelf_id in reversed(shelves):
6034
message = manager.get_metadata(shelf_id).get('message')
6036
message = '<no message>'
6037
self.outf.write('%3d: %s\n' % (shelf_id, message))
6041
class cmd_unshelve(Command):
6042
__doc__ = """Restore shelved changes.
6044
By default, the most recently shelved changes are restored. However if you
6045
specify a shelf by id those changes will be restored instead. This works
6046
best when the changes don't depend on each other.
6049
takes_args = ['shelf_id?']
6052
RegistryOption.from_kwargs(
6053
'action', help="The action to perform.",
6054
enum_switch=False, value_switches=True,
6055
apply="Apply changes and remove from the shelf.",
6056
dry_run="Show changes, but do not apply or remove them.",
6057
preview="Instead of unshelving the changes, show the diff that "
6058
"would result from unshelving.",
6059
delete_only="Delete changes without applying them.",
6060
keep="Apply changes but don't delete them.",
6063
_see_also = ['shelve']
6065
def run(self, shelf_id=None, action='apply', directory=u'.'):
6066
from bzrlib.shelf_ui import Unshelver
6067
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6071
unshelver.tree.unlock()
6074
class cmd_clean_tree(Command):
6075
__doc__ = """Remove unwanted files from working tree.
6077
By default, only unknown files, not ignored files, are deleted. Versioned
6078
files are never deleted.
6080
Another class is 'detritus', which includes files emitted by bzr during
6081
normal operations and selftests. (The value of these files decreases with
6084
If no options are specified, unknown files are deleted. Otherwise, option
6085
flags are respected, and may be combined.
6087
To check what clean-tree will do, use --dry-run.
6089
takes_options = ['directory',
6090
Option('ignored', help='Delete all ignored files.'),
6091
Option('detritus', help='Delete conflict files, merge and revert'
6092
' backups, and failed selftest dirs.'),
6094
help='Delete files unknown to bzr (default).'),
6095
Option('dry-run', help='Show files to delete instead of'
6097
Option('force', help='Do not prompt before deleting.')]
6098
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6099
force=False, directory=u'.'):
6100
from bzrlib.clean_tree import clean_tree
6101
if not (unknown or ignored or detritus):
6105
clean_tree(directory, unknown=unknown, ignored=ignored,
6106
detritus=detritus, dry_run=dry_run, no_prompt=force)
6109
class cmd_reference(Command):
6110
__doc__ = """list, view and set branch locations for nested trees.
6112
If no arguments are provided, lists the branch locations for nested trees.
6113
If one argument is provided, display the branch location for that tree.
6114
If two arguments are provided, set the branch location for that tree.
6119
takes_args = ['path?', 'location?']
6121
def run(self, path=None, location=None):
6123
if path is not None:
6125
tree, branch, relpath =(
6126
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6127
if path is not None:
6130
tree = branch.basis_tree()
6132
info = branch._get_all_reference_info().iteritems()
6133
self._display_reference_info(tree, branch, info)
6135
file_id = tree.path2id(path)
6137
raise errors.NotVersionedError(path)
6138
if location is None:
6139
info = [(file_id, branch.get_reference_info(file_id))]
6140
self._display_reference_info(tree, branch, info)
6142
branch.set_reference_info(file_id, path, location)
6144
def _display_reference_info(self, tree, branch, info):
6146
for file_id, (path, location) in info:
6148
path = tree.id2path(file_id)
6149
except errors.NoSuchId:
6151
ref_list.append((path, location))
6152
for path, location in sorted(ref_list):
6153
self.outf.write('%s %s\n' % (path, location))
6156
def _register_lazy_builtins():
6157
# register lazy builtins from other modules; called at startup and should
6158
# be only called once.
6159
for (name, aliases, module_name) in [
6160
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6161
('cmd_config', [], 'bzrlib.config'),
6162
('cmd_dpush', [], 'bzrlib.foreign'),
6163
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6164
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6165
('cmd_conflicts', [], 'bzrlib.conflicts'),
6166
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6167
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6169
builtin_command_registry.register_lazy(name, aliases, module_name)
4221
def _create_prefix(cur_transport):
4222
needed = [cur_transport]
4223
# Recurse upwards until we can create a directory successfully
4225
new_transport = cur_transport.clone('..')
4226
if new_transport.base == cur_transport.base:
4227
raise errors.BzrCommandError(
4228
"Failed to create path prefix for %s."
4229
% cur_transport.base)
4231
new_transport.mkdir('.')
4232
except errors.NoSuchFile:
4233
needed.append(new_transport)
4234
cur_transport = new_transport
4237
# Now we only need to create child directories
4239
cur_transport = needed.pop()
4240
cur_transport.ensure_base()
4243
def _get_mergeable_helper(location):
4244
"""Get a merge directive or bundle if 'location' points to one.
4246
Try try to identify a bundle and returns its mergeable form. If it's not,
4247
we return the tried transport anyway so that it can reused to access the
4250
:param location: can point to a bundle or a branch.
4252
:return: mergeable, transport
4255
url = urlutils.normalize_url(location)
4256
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4257
location_transport = transport.get_transport(url)
4260
# There may be redirections but we ignore the intermediate
4261
# and final transports used
4262
read = bundle.read_mergeable_from_transport
4263
mergeable, t = read(location_transport, filename)
4264
except errors.NotABundle:
4265
# Continue on considering this url a Branch but adjust the
4266
# location_transport
4267
location_transport = location_transport.clone(filename)
4268
return mergeable, location_transport
4271
# these get imported and then picked up by the scan for cmd_*
4272
# TODO: Some more consistent way to split command definitions across files;
4273
# we do need to load at least some information about them to know of
4274
# aliases. ideally we would avoid loading the implementation until the
4275
# details were needed.
4276
from bzrlib.cmd_version_info import cmd_version_info
4277
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4278
from bzrlib.bundle.commands import (
4281
from bzrlib.sign_my_commits import cmd_sign_my_commits
4282
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4283
cmd_weave_plan_merge, cmd_weave_merge_text