29
33
from bzrlib import (
40
config as _mod_config,
39
45
merge as _mod_merge,
43
50
revision as _mod_revision,
50
59
from bzrlib.branch import Branch
51
60
from bzrlib.conflicts import ConflictList
52
from bzrlib.revisionspec import RevisionSpec
61
from bzrlib.transport import memory
62
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
53
63
from bzrlib.smtp_connection import SMTPConnection
54
64
from bzrlib.workingtree import WorkingTree
65
from bzrlib.i18n import gettext, ngettext
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]))
68
from bzrlib.commands import (
70
builtin_command_registry,
73
from bzrlib.option import (
80
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
86
def _get_branch_location(control_dir):
87
"""Return location of branch for this control dir."""
89
this_branch = control_dir.open_branch()
90
# This may be a heavy checkout, where we want the master branch
91
master_location = this_branch.get_bound_location()
92
if master_location is not None:
93
return master_location
94
# If not, use a local sibling
95
return this_branch.base
96
except errors.NotBranchError:
97
format = control_dir.find_branch_format()
98
if getattr(format, 'get_reference', None) is not None:
99
return format.get_reference(control_dir)
101
return control_dir.root_transport.base
104
def lookup_new_sibling_branch(control_dir, location):
105
"""Lookup the location for a new sibling branch.
107
:param control_dir: Control directory relative to which to look up
109
:param location: Name of the new branch
110
:return: Full location to the new branch
112
location = directory_service.directories.dereference(location)
113
if '/' not in location and '\\' not in location:
114
# This path is meant to be relative to the existing branch
115
this_url = _get_branch_location(control_dir)
116
# Perhaps the target control dir supports colocated branches?
118
root = controldir.ControlDir.open(this_url,
119
possible_transports=[control_dir.user_transport])
120
except errors.NotBranchError:
123
colocated = root._format.colocated_branches
126
return urlutils.join_segment_parameters(this_url,
127
{"branch": urlutils.escape(location)})
129
return urlutils.join(this_url, '..', urlutils.escape(location))
133
def lookup_sibling_branch(control_dir, location):
134
"""Lookup sibling branch.
136
:param control_dir: Control directory relative to which to lookup the
138
:param location: Location to look up
139
:return: branch to open
142
# Perhaps it's a colocated branch?
143
return control_dir.open_branch(location)
144
except (errors.NotBranchError, errors.NoColocatedBranchSupport):
146
return Branch.open(location)
147
except errors.NotBranchError:
148
this_url = _get_branch_location(control_dir)
151
this_url, '..', urlutils.escape(location)))
154
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
155
def tree_files(file_list, default_branch=u'.', canonicalize=True,
157
return internal_tree_files(file_list, default_branch, canonicalize,
161
def tree_files_for_add(file_list):
163
Return a tree and list of absolute paths from a file list.
165
Similar to tree_files, but add handles files a bit differently, so it a
166
custom implementation. In particular, MutableTreeTree.smart_add expects
167
absolute paths, which it immediately converts to relative paths.
169
# FIXME Would be nice to just return the relative paths like
170
# internal_tree_files does, but there are a large number of unit tests
171
# that assume the current interface to mutabletree.smart_add
173
tree, relpath = WorkingTree.open_containing(file_list[0])
174
if tree.supports_views():
175
view_files = tree.views.lookup_view()
177
for filename in file_list:
178
if not osutils.is_inside_any(view_files, filename):
179
raise errors.FileOutsideView(filename, view_files)
180
file_list = file_list[:]
181
file_list[0] = tree.abspath(relpath)
183
tree = WorkingTree.open_containing(u'.')[0]
184
if tree.supports_views():
185
view_files = tree.views.lookup_view()
187
file_list = view_files
188
view_str = views.view_display_str(view_files)
189
note(gettext("Ignoring files outside view. View is %s") % view_str)
190
return tree, file_list
193
def _get_one_revision(command_name, revisions):
194
if revisions is None:
196
if len(revisions) != 1:
197
raise errors.BzrCommandError(gettext(
198
'bzr %s --revision takes exactly one revision identifier') % (
203
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
204
"""Get a revision tree. Not suitable for commands that change the tree.
206
Specifically, the basis tree in dirstate trees is coupled to the dirstate
207
and doing a commit/uncommit/pull will at best fail due to changing the
210
If tree is passed in, it should be already locked, for lifetime management
211
of the trees internal cached state.
215
if revisions is None:
217
rev_tree = tree.basis_tree()
219
rev_tree = branch.basis_tree()
221
revision = _get_one_revision(command_name, revisions)
222
rev_tree = revision.as_tree(branch)
70
226
# XXX: Bad function name; should possibly also be a class method of
71
227
# WorkingTree rather than a function.
72
def internal_tree_files(file_list, default_branch=u'.'):
228
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
229
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
73
231
"""Convert command-line paths to a WorkingTree and relative paths.
233
Deprecated: use WorkingTree.open_containing_paths instead.
75
235
This is typically used for command-line processors that take one or
76
236
more filenames, and infer the workingtree that contains them.
78
238
The filenames given are not required to exist.
80
:param file_list: Filenames to convert.
240
:param file_list: Filenames to convert.
82
242
:param default_branch: Fallback tree path to use if file_list is empty or
245
:param apply_view: if True and a view is set, apply it or check that
246
specified files are within it
85
248
:return: workingtree, [relative_paths]
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)
250
return WorkingTree.open_containing_paths(
251
file_list, default_directory='.',
256
def _get_view_info_for_change_reporter(tree):
257
"""Get the view information from a tree for change reporting."""
260
current_view = tree.views.get_view_info()[0]
261
if current_view is not None:
262
view_info = (current_view, tree.views.lookup_view())
263
except errors.ViewsNotSupported:
268
def _open_directory_or_containing_tree_or_branch(filename, directory):
269
"""Open the tree or branch containing the specified file, unless
270
the --directory option is used to specify a different branch."""
271
if directory is not None:
272
return (None, Branch.open(directory), filename)
273
return controldir.ControlDir.open_containing_tree_or_branch(filename)
99
276
# TODO: Make sure no commands unconditionally use the working directory as a
130
307
Not versioned and not matching an ignore pattern.
309
Additionally for directories, symlinks and files with a changed
310
executable bit, Bazaar indicates their type using a trailing
311
character: '/', '@' or '*' respectively. These decorations can be
312
disabled using the '--no-classify' option.
132
314
To see ignored files use 'bzr ignored'. For details on the
133
315
changes to file texts, use 'bzr diff'.
135
317
Note that --short or -S gives status flags for each item, similar
136
318
to Subversion's status command. To get output similar to svn -q,
139
321
If no arguments are specified, the status of the entire working
140
322
directory is shown. Otherwise, only the status of the specified
141
323
files or directories is reported. If a directory is given, status
142
324
is reported for everything inside that directory.
144
If a revision argument is given, the status is calculated against
145
that revision, or between two revisions if two are provided.
326
Before merges are committed, the pending merge tip revisions are
327
shown. To see all pending merge revisions, use the -v option.
328
To skip the display of pending merge information altogether, use
329
the no-pending option or specify a file/directory.
331
To compare the working directory to a specific revision, pass a
332
single revision to the revision argument.
334
To see which files have changed in a specific revision, or between
335
two revisions, pass a revision range to the revision argument.
336
This will produce the same results as calling 'bzr diff --summarize'.
148
339
# TODO: --no-recurse, --recurse options
150
341
takes_args = ['file*']
151
takes_options = ['show-ids', 'revision', 'change',
342
takes_options = ['show-ids', 'revision', 'change', 'verbose',
152
343
Option('short', help='Use short status indicators.',
154
345
Option('versioned', help='Only show versioned files.',
156
347
Option('no-pending', help='Don\'t show pending merges.',
349
Option('no-classify',
350
help='Do not mark object type using indicator.',
159
353
aliases = ['st', 'stat']
161
355
encoding_type = 'replace'
162
356
_see_also = ['diff', 'revert', 'status-flags']
165
359
def run(self, show_ids=False, file_list=None, revision=None, short=False,
166
versioned=False, no_pending=False):
360
versioned=False, no_pending=False, verbose=False,
167
362
from bzrlib.status import show_tree_status
169
364
if revision and len(revision) > 2:
170
raise errors.BzrCommandError('bzr status --revision takes exactly'
171
' one or two revision specifiers')
365
raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
366
' one or two revision specifiers'))
173
tree, file_list = tree_files(file_list)
368
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
369
# Avoid asking for specific files when that is not needed.
370
if relfile_list == ['']:
372
# Don't disable pending merges for full trees other than '.'.
373
if file_list == ['.']:
375
# A specific path within a tree was given.
376
elif relfile_list is not None:
175
378
show_tree_status(tree, show_ids=show_ids,
176
specific_files=file_list, revision=revision,
379
specific_files=relfile_list, revision=revision,
177
380
to_file=self.outf, short=short, versioned=versioned,
178
show_pending=not no_pending)
381
show_pending=(not no_pending), verbose=verbose,
382
classify=not no_classify)
181
385
class cmd_cat_revision(Command):
182
"""Write out metadata for a revision.
386
__doc__ = """Write out metadata for a revision.
184
388
The revision to print can either be specified by a specific
185
389
revision identifier, or you can use --revision.
189
393
takes_args = ['revision_id?']
190
takes_options = ['revision']
394
takes_options = ['directory', 'revision']
191
395
# cat-revision is more for frontends so should be exact
192
396
encoding = 'strict'
398
def print_revision(self, revisions, revid):
399
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
400
record = stream.next()
401
if record.storage_kind == 'absent':
402
raise errors.NoSuchRevision(revisions, revid)
403
revtext = record.get_bytes_as('fulltext')
404
self.outf.write(revtext.decode('utf-8'))
195
def run(self, revision_id=None, revision=None):
407
def run(self, revision_id=None, revision=None, directory=u'.'):
196
408
if revision_id is not None and revision is not None:
197
raise errors.BzrCommandError('You can only supply one of'
198
' revision_id or --revision')
409
raise errors.BzrCommandError(gettext('You can only supply one of'
410
' revision_id or --revision'))
199
411
if revision_id is None and revision is None:
200
raise errors.BzrCommandError('You must supply either'
201
' --revision or a revision_id')
202
b = WorkingTree.open_containing(u'.')[0].branch
204
# TODO: jam 20060112 should cat-revision always output utf-8?
205
if revision_id is not None:
206
revision_id = osutils.safe_revision_id(revision_id, warn=False)
207
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
208
elif revision is not None:
211
raise errors.BzrCommandError('You cannot specify a NULL'
213
rev_id = rev.as_revision_id(b)
214
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
412
raise errors.BzrCommandError(gettext('You must supply either'
413
' --revision or a revision_id'))
415
b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
417
revisions = b.repository.revisions
418
if revisions is None:
419
raise errors.BzrCommandError(gettext('Repository %r does not support '
420
'access to raw revision texts'))
422
b.repository.lock_read()
424
# TODO: jam 20060112 should cat-revision always output utf-8?
425
if revision_id is not None:
426
revision_id = osutils.safe_revision_id(revision_id, warn=False)
428
self.print_revision(revisions, revision_id)
429
except errors.NoSuchRevision:
430
msg = gettext("The repository {0} contains no revision {1}.").format(
431
b.repository.base, revision_id)
432
raise errors.BzrCommandError(msg)
433
elif revision is not None:
436
raise errors.BzrCommandError(
437
gettext('You cannot specify a NULL revision.'))
438
rev_id = rev.as_revision_id(b)
439
self.print_revision(revisions, rev_id)
441
b.repository.unlock()
444
class cmd_dump_btree(Command):
445
__doc__ = """Dump the contents of a btree index file to stdout.
447
PATH is a btree index file, it can be any URL. This includes things like
448
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
450
By default, the tuples stored in the index file will be displayed. With
451
--raw, we will uncompress the pages, but otherwise display the raw bytes
455
# TODO: Do we want to dump the internal nodes as well?
456
# TODO: It would be nice to be able to dump the un-parsed information,
457
# rather than only going through iter_all_entries. However, this is
458
# good enough for a start
460
encoding_type = 'exact'
461
takes_args = ['path']
462
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
463
' rather than the parsed tuples.'),
466
def run(self, path, raw=False):
467
dirname, basename = osutils.split(path)
468
t = transport.get_transport(dirname)
470
self._dump_raw_bytes(t, basename)
472
self._dump_entries(t, basename)
474
def _get_index_and_bytes(self, trans, basename):
475
"""Create a BTreeGraphIndex and raw bytes."""
476
bt = btree_index.BTreeGraphIndex(trans, basename, None)
477
bytes = trans.get_bytes(basename)
478
bt._file = cStringIO.StringIO(bytes)
479
bt._size = len(bytes)
482
def _dump_raw_bytes(self, trans, basename):
485
# We need to parse at least the root node.
486
# This is because the first page of every row starts with an
487
# uncompressed header.
488
bt, bytes = self._get_index_and_bytes(trans, basename)
489
for page_idx, page_start in enumerate(xrange(0, len(bytes),
490
btree_index._PAGE_SIZE)):
491
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
492
page_bytes = bytes[page_start:page_end]
494
self.outf.write('Root node:\n')
495
header_end, data = bt._parse_header_from_bytes(page_bytes)
496
self.outf.write(page_bytes[:header_end])
498
self.outf.write('\nPage %d\n' % (page_idx,))
499
if len(page_bytes) == 0:
500
self.outf.write('(empty)\n');
502
decomp_bytes = zlib.decompress(page_bytes)
503
self.outf.write(decomp_bytes)
504
self.outf.write('\n')
506
def _dump_entries(self, trans, basename):
508
st = trans.stat(basename)
509
except errors.TransportNotPossible:
510
# We can't stat, so we'll fake it because we have to do the 'get()'
512
bt, _ = self._get_index_and_bytes(trans, basename)
514
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
515
for node in bt.iter_all_entries():
516
# Node is made up of:
517
# (index, key, value, [references])
521
refs_as_tuples = None
523
refs_as_tuples = static_tuple.as_tuples(refs)
524
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
525
self.outf.write('%s\n' % (as_tuple,))
217
528
class cmd_remove_tree(Command):
218
"""Remove the working tree from a given branch/checkout.
529
__doc__ = """Remove the working tree from a given branch/checkout.
220
531
Since a lightweight checkout is little more than a working tree
221
532
this will refuse to run against one.
223
534
To re-create the working tree, use "bzr checkout".
225
536
_see_also = ['checkout', 'working-trees']
227
takes_args = ['location?']
229
def run(self, location='.'):
230
d = bzrdir.BzrDir.open(location)
537
takes_args = ['location*']
540
help='Remove the working tree even if it has '
541
'uncommitted or shelved changes.'),
544
def run(self, location_list, force=False):
545
if not location_list:
548
for location in location_list:
549
d = controldir.ControlDir.open(location)
552
working = d.open_workingtree()
553
except errors.NoWorkingTree:
554
raise errors.BzrCommandError(gettext("No working tree to remove"))
555
except errors.NotLocalUrl:
556
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
557
" of a remote path"))
559
if (working.has_changes()):
560
raise errors.UncommittedChanges(working)
561
if working.get_shelf_manager().last_shelf() is not None:
562
raise errors.ShelvedChanges(working)
564
if working.user_url != working.branch.user_url:
565
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
566
" from a lightweight checkout"))
568
d.destroy_workingtree()
571
class cmd_repair_workingtree(Command):
572
__doc__ = """Reset the working tree state file.
574
This is not meant to be used normally, but more as a way to recover from
575
filesystem corruption, etc. This rebuilds the working inventory back to a
576
'known good' state. Any new modifications (adding a file, renaming, etc)
577
will be lost, though modified files will still be detected as such.
579
Most users will want something more like "bzr revert" or "bzr update"
580
unless the state file has become corrupted.
582
By default this attempts to recover the current state by looking at the
583
headers of the state file. If the state file is too corrupted to even do
584
that, you can supply --revision to force the state of the tree.
587
takes_options = ['revision', 'directory',
589
help='Reset the tree even if it doesn\'t appear to be'
594
def run(self, revision=None, directory='.', force=False):
595
tree, _ = WorkingTree.open_containing(directory)
596
self.add_cleanup(tree.lock_tree_write().unlock)
600
except errors.BzrError:
601
pass # There seems to be a real error here, so we'll reset
604
raise errors.BzrCommandError(gettext(
605
'The tree does not appear to be corrupt. You probably'
606
' want "bzr revert" instead. Use "--force" if you are'
607
' sure you want to reset the working tree.'))
611
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
233
working = d.open_workingtree()
234
except errors.NoWorkingTree:
235
raise errors.BzrCommandError("No working tree to remove")
236
except errors.NotLocalUrl:
237
raise errors.BzrCommandError("You cannot remove the working tree of a "
240
working_path = working.bzrdir.root_transport.base
241
branch_path = working.branch.bzrdir.root_transport.base
242
if working_path != branch_path:
243
raise errors.BzrCommandError("You cannot remove the working tree from "
244
"a lightweight checkout")
246
d.destroy_workingtree()
613
tree.reset_state(revision_ids)
614
except errors.BzrError, e:
615
if revision_ids is None:
616
extra = (gettext(', the header appears corrupt, try passing -r -1'
617
' to set the state to the last commit'))
620
raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
249
623
class cmd_revno(Command):
250
"""Show current revision number.
624
__doc__ = """Show current revision number.
252
626
This is equal to the number of revisions on this branch.
255
629
_see_also = ['info']
256
630
takes_args = ['location?']
632
Option('tree', help='Show revno of working tree.'),
259
def run(self, location=u'.'):
260
self.outf.write(str(Branch.open_containing(location)[0].revno()))
261
self.outf.write('\n')
637
def run(self, tree=False, location=u'.', revision=None):
638
if revision is not None and tree:
639
raise errors.BzrCommandError(gettext("--tree and --revision can "
640
"not be used together"))
644
wt = WorkingTree.open_containing(location)[0]
645
self.add_cleanup(wt.lock_read().unlock)
646
except (errors.NoWorkingTree, errors.NotLocalUrl):
647
raise errors.NoWorkingTree(location)
649
revid = wt.last_revision()
651
b = Branch.open_containing(location)[0]
652
self.add_cleanup(b.lock_read().unlock)
654
if len(revision) != 1:
655
raise errors.BzrCommandError(gettext(
656
"Tags can only be placed on a single revision, "
658
revid = revision[0].as_revision_id(b)
660
revid = b.last_revision()
662
revno_t = b.revision_id_to_dotted_revno(revid)
663
except errors.NoSuchRevision:
665
revno = ".".join(str(n) for n in revno_t)
667
self.outf.write(revno + '\n')
264
670
class cmd_revision_info(Command):
265
"""Show revision number and revision id for a given revision identifier.
671
__doc__ = """Show revision number and revision id for a given revision identifier.
268
674
takes_args = ['revision_info*']
269
takes_options = ['revision']
677
custom_help('directory',
678
help='Branch to examine, '
679
'rather than the one containing the working directory.'),
680
Option('tree', help='Show revno of working tree.'),
272
def run(self, revision=None, revision_info_list=[]):
684
def run(self, revision=None, directory=u'.', tree=False,
685
revision_info_list=[]):
688
wt = WorkingTree.open_containing(directory)[0]
690
self.add_cleanup(wt.lock_read().unlock)
691
except (errors.NoWorkingTree, errors.NotLocalUrl):
693
b = Branch.open_containing(directory)[0]
694
self.add_cleanup(b.lock_read().unlock)
275
696
if revision is not None:
276
revs.extend(revision)
697
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
277
698
if revision_info_list is not None:
278
for rev in revision_info_list:
279
revs.append(RevisionSpec.from_string(rev))
281
b = Branch.open_containing(u'.')[0]
284
revs.append(RevisionSpec.from_string('-1'))
287
revision_id = rev.as_revision_id(b)
699
for rev_str in revision_info_list:
700
rev_spec = RevisionSpec.from_string(rev_str)
701
revision_ids.append(rev_spec.as_revision_id(b))
702
# No arguments supplied, default to the last revision
703
if len(revision_ids) == 0:
706
raise errors.NoWorkingTree(directory)
707
revision_ids.append(wt.last_revision())
709
revision_ids.append(b.last_revision())
713
for revision_id in revision_ids:
289
revno = '%4d' % (b.revision_id_to_revno(revision_id))
715
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
716
revno = '.'.join(str(i) for i in dotted_revno)
290
717
except errors.NoSuchRevision:
291
dotted_map = b.get_revision_id_to_revno_map()
292
revno = '.'.join(str(i) for i in dotted_map[revision_id])
293
print '%s %s' % (revno, revision_id)
719
maxlen = max(maxlen, len(revno))
720
revinfos.append([revno, revision_id])
724
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
296
727
class cmd_add(Command):
297
"""Add specified files or directories.
728
__doc__ = """Add specified files or directories.
299
730
In non-recursive mode, all the named items are added, regardless
300
731
of whether they were previously ignored. A warning is given if
542
1010
into_existing = False
544
1012
inv = tree.inventory
545
from_id = tree.path2id(rel_names[0])
1013
# 'fix' the case of a potential 'from'
1014
from_id = tree.path2id(
1015
tree.get_canonical_inventory_path(rel_names[0]))
546
1016
if (not osutils.lexists(names_list[0]) and
547
1017
from_id and inv.get_file_kind(from_id) == "directory"):
548
1018
into_existing = False
550
1020
if into_existing:
551
1021
# move into existing directory
552
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
553
self.outf.write("%s => %s\n" % pair)
1022
# All entries reference existing inventory items, so fix them up
1023
# for cicp file-systems.
1024
rel_names = tree.get_canonical_inventory_paths(rel_names)
1025
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
1027
self.outf.write("%s => %s\n" % (src, dest))
555
1029
if len(names_list) != 2:
556
raise errors.BzrCommandError('to mv multiple files the'
1030
raise errors.BzrCommandError(gettext('to mv multiple files the'
557
1031
' destination must be a versioned'
559
tree.rename_one(rel_names[0], rel_names[1], after=after)
560
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
1034
# for cicp file-systems: the src references an existing inventory
1036
src = tree.get_canonical_inventory_path(rel_names[0])
1037
# Find the canonical version of the destination: In all cases, the
1038
# parent of the target must be in the inventory, so we fetch the
1039
# canonical version from there (we do not always *use* the
1040
# canonicalized tail portion - we may be attempting to rename the
1042
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
1043
dest_parent = osutils.dirname(canon_dest)
1044
spec_tail = osutils.basename(rel_names[1])
1045
# For a CICP file-system, we need to avoid creating 2 inventory
1046
# entries that differ only by case. So regardless of the case
1047
# we *want* to use (ie, specified by the user or the file-system),
1048
# we must always choose to use the case of any existing inventory
1049
# items. The only exception to this is when we are attempting a
1050
# case-only rename (ie, canonical versions of src and dest are
1052
dest_id = tree.path2id(canon_dest)
1053
if dest_id is None or tree.path2id(src) == dest_id:
1054
# No existing item we care about, so work out what case we
1055
# are actually going to use.
1057
# If 'after' is specified, the tail must refer to a file on disk.
1059
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
1061
# pathjoin with an empty tail adds a slash, which breaks
1063
dest_parent_fq = tree.basedir
1065
dest_tail = osutils.canonical_relpath(
1067
osutils.pathjoin(dest_parent_fq, spec_tail))
1069
# not 'after', so case as specified is used
1070
dest_tail = spec_tail
1072
# Use the existing item so 'mv' fails with AlreadyVersioned.
1073
dest_tail = os.path.basename(canon_dest)
1074
dest = osutils.pathjoin(dest_parent, dest_tail)
1075
mutter("attempting to move %s => %s", src, dest)
1076
tree.rename_one(src, dest, after=after)
1078
self.outf.write("%s => %s\n" % (src, dest))
563
1081
class cmd_pull(Command):
564
"""Turn this branch into a mirror of another branch.
1082
__doc__ = """Turn this branch into a mirror of another branch.
566
This command only works on branches that have not diverged. Branches are
567
considered diverged if the destination branch's most recent commit is one
568
that has not been merged (directly or indirectly) into the parent.
1084
By default, this command only works on branches that have not diverged.
1085
Branches are considered diverged if the destination branch's most recent
1086
commit is one that has not been merged (directly or indirectly) into the
570
1089
If branches have diverged, you can use 'bzr merge' to integrate the changes
571
1090
from one into the other. Once one branch has merged, the other should
572
1091
be able to pull it again.
574
If you want to forget your local changes and just update your branch to
575
match the remote one, use pull --overwrite.
577
If there is no default location set, the first pull will set it. After
578
that, you can omit the location to use the default. To change the
579
default, use --remember. The value will only be saved if the remote
580
location can be accessed.
1093
If you want to replace your local changes and just want your branch to
1094
match the remote one, use pull --overwrite. This will work even if the two
1095
branches have diverged.
1097
If there is no default location set, the first pull will set it (use
1098
--no-remember to avoid setting it). After that, you can omit the
1099
location to use the default. To change the default, use --remember. The
1100
value will only be saved if the remote location can be accessed.
1102
The --verbose option will display the revisions pulled using the log_format
1103
configuration option. You can use a different format by overriding it with
1104
-Olog_format=<other_format>.
582
1106
Note: The location can be specified either in the form of a branch,
583
1107
or in the form of a path to a file containing a merge directive generated
587
_see_also = ['push', 'update', 'status-flags']
1111
_see_also = ['push', 'update', 'status-flags', 'send']
588
1112
takes_options = ['remember', 'overwrite', 'revision',
589
1113
custom_help('verbose',
590
1114
help='Show logs of pulled revisions.'),
1115
custom_help('directory',
592
1116
help='Branch to pull into, '
593
'rather than the one containing the working directory.',
1117
'rather than the one containing the working directory.'),
1119
help="Perform a local pull in a bound "
1120
"branch. Local pulls are not applied to "
1121
"the master branch."
1124
help="Show base revision text in conflicts.")
598
1126
takes_args = ['location?']
599
1127
encoding_type = 'replace'
601
def run(self, location=None, remember=False, overwrite=False,
1129
def run(self, location=None, remember=None, overwrite=False,
602
1130
revision=None, verbose=False,
1131
directory=None, local=False,
604
1133
# FIXME: too much stuff is in the command class
605
1134
revision_id = None
606
1135
mergeable = None
710
1249
Option('create-prefix',
711
1250
help='Create the path leading up to the branch '
712
1251
'if it does not already exist.'),
1252
custom_help('directory',
714
1253
help='Branch to push from, '
715
'rather than the one containing the working directory.',
1254
'rather than the one containing the working directory.'),
719
1255
Option('use-existing-dir',
720
1256
help='By default push will fail if the target'
721
1257
' directory exists, but does not already'
722
1258
' have a control directory. This flag will'
723
1259
' allow push to proceed.'),
1261
help='Create a stacked branch that references the public location '
1262
'of the parent branch.'),
1263
Option('stacked-on',
1264
help='Create a stacked branch that refers to another branch '
1265
'for the commit history. Only the work not present in the '
1266
'referenced branch is included in the branch created.',
1269
help='Refuse to push if there are uncommitted changes in'
1270
' the working tree, --no-strict disables the check.'),
1272
help="Don't populate the working tree, even for protocols"
1273
" that support it."),
725
1275
takes_args = ['location?']
726
1276
encoding_type = 'replace'
728
def run(self, location=None, remember=False, overwrite=False,
729
create_prefix=False, verbose=False, revision=None,
730
use_existing_dir=False,
732
# FIXME: Way too big! Put this into a function called from the
1278
def run(self, location=None, remember=None, overwrite=False,
1279
create_prefix=False, verbose=False, revision=None,
1280
use_existing_dir=False, directory=None, stacked_on=None,
1281
stacked=False, strict=None, no_tree=False):
1282
from bzrlib.push import _show_push_branch
734
1284
if directory is None:
736
br_from = Branch.open_containing(directory)[0]
737
stored_loc = br_from.get_push_location()
1286
# Get the source branch
1288
_unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
1289
# Get the tip's revision_id
1290
revision = _get_one_revision('push', revision)
1291
if revision is not None:
1292
revision_id = revision.in_history(br_from).rev_id
1295
if tree is not None and revision_id is None:
1296
tree.check_changed_or_out_of_date(
1297
strict, 'push_strict',
1298
more_error='Use --no-strict to force the push.',
1299
more_warning='Uncommitted changes will not be pushed.')
1300
# Get the stacked_on branch, if any
1301
if stacked_on is not None:
1302
stacked_on = urlutils.normalize_url(stacked_on)
1304
parent_url = br_from.get_parent()
1306
parent = Branch.open(parent_url)
1307
stacked_on = parent.get_public_branch()
1309
# I considered excluding non-http url's here, thus forcing
1310
# 'public' branches only, but that only works for some
1311
# users, so it's best to just depend on the user spotting an
1312
# error by the feedback given to them. RBC 20080227.
1313
stacked_on = parent_url
1315
raise errors.BzrCommandError(gettext(
1316
"Could not determine branch to refer to."))
1318
# Get the destination location
738
1319
if location is None:
1320
stored_loc = br_from.get_push_location()
739
1321
if stored_loc is None:
740
raise errors.BzrCommandError("No push location known or specified.")
1322
parent_loc = br_from.get_parent()
1324
raise errors.BzrCommandError(gettext(
1325
"No push location known or specified. To push to the "
1326
"parent branch (at %s), use 'bzr push :parent'." %
1327
urlutils.unescape_for_display(parent_loc,
1328
self.outf.encoding)))
1330
raise errors.BzrCommandError(gettext(
1331
"No push location known or specified."))
742
1333
display_url = urlutils.unescape_for_display(stored_loc,
743
1334
self.outf.encoding)
744
self.outf.write("Using saved location: %s\n" % display_url)
1335
note(gettext("Using saved push location: %s") % display_url)
745
1336
location = stored_loc
747
to_transport = transport.get_transport(location)
749
br_to = repository_to = dir_to = None
751
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
752
except errors.NotBranchError:
753
pass # Didn't find anything
755
# If we can open a branch, use its direct repository, otherwise see
756
# if there is a repository without a branch.
758
br_to = dir_to.open_branch()
759
except errors.NotBranchError:
760
# Didn't find a branch, can we find a repository?
762
repository_to = dir_to.find_repository()
763
except errors.NoRepositoryPresent:
766
# Found a branch, so we must have found a repository
767
repository_to = br_to.repository
769
if revision is not None:
770
if len(revision) == 1:
771
revision_id = revision[0].in_history(br_from).rev_id
773
raise errors.BzrCommandError(
774
'bzr push --revision takes one value.')
776
revision_id = br_from.last_revision()
782
# The destination doesn't exist; create it.
783
# XXX: Refactor the create_prefix/no_create_prefix code into a
784
# common helper function
786
def make_directory(transport):
790
def redirected(redirected_transport, e, redirection_notice):
791
return transport.get_transport(e.get_target_url())
794
to_transport = transport.do_catching_redirections(
795
make_directory, to_transport, redirected)
796
except errors.FileExists:
797
if not use_existing_dir:
798
raise errors.BzrCommandError("Target directory %s"
799
" already exists, but does not have a valid .bzr"
800
" directory. Supply --use-existing-dir to push"
801
" there anyway." % location)
802
except errors.NoSuchFile:
803
if not create_prefix:
804
raise errors.BzrCommandError("Parent directory of %s"
806
"\nYou may supply --create-prefix to create all"
807
" leading parent directories."
809
_create_prefix(to_transport)
810
except errors.TooManyRedirections:
811
raise errors.BzrCommandError("Too many redirections trying "
812
"to make %s." % location)
814
# Now the target directory exists, but doesn't have a .bzr
815
# directory. So we need to create it, along with any work to create
816
# all of the dependent branches, etc.
817
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
818
revision_id=revision_id)
819
br_to = dir_to.open_branch()
820
# TODO: Some more useful message about what was copied
821
note('Created new branch.')
822
# We successfully created the target, remember it
823
if br_from.get_push_location() is None or remember:
824
br_from.set_push_location(br_to.base)
825
elif repository_to is None:
826
# we have a bzrdir but no branch or repository
827
# XXX: Figure out what to do other than complain.
828
raise errors.BzrCommandError("At %s you have a valid .bzr control"
829
" directory, but not a branch or repository. This is an"
830
" unsupported configuration. Please move the target directory"
831
" out of the way and try again."
834
# We have a repository but no branch, copy the revisions, and then
836
repository_to.fetch(br_from.repository, revision_id=revision_id)
837
br_to = br_from.clone(dir_to, revision_id=revision_id)
838
note('Created new branch.')
839
if br_from.get_push_location() is None or remember:
840
br_from.set_push_location(br_to.base)
841
else: # We have a valid to branch
842
# We were able to connect to the remote location, so remember it
843
# we don't need to successfully push because of possible divergence.
844
if br_from.get_push_location() is None or remember:
845
br_from.set_push_location(br_to.base)
847
old_rh = br_to.revision_history()
850
tree_to = dir_to.open_workingtree()
851
except errors.NotLocalUrl:
852
warning("This transport does not update the working "
853
"tree of: %s. See 'bzr help working-trees' for "
854
"more information." % br_to.base)
855
push_result = br_from.push(br_to, overwrite,
856
stop_revision=revision_id)
857
except errors.NoWorkingTree:
858
push_result = br_from.push(br_to, overwrite,
859
stop_revision=revision_id)
863
push_result = br_from.push(tree_to.branch, overwrite,
864
stop_revision=revision_id)
868
except errors.DivergedBranches:
869
raise errors.BzrCommandError('These branches have diverged.'
870
' Try using "merge" and then "push".')
871
if push_result is not None:
872
push_result.report(self.outf)
874
new_rh = br_to.revision_history()
877
from bzrlib.log import show_changed_revisions
878
show_changed_revisions(br_to, old_rh, new_rh,
881
# we probably did a clone rather than a push, so a message was
1338
_show_push_branch(br_from, revision_id, location, self.outf,
1339
verbose=verbose, overwrite=overwrite, remember=remember,
1340
stacked_on=stacked_on, create_prefix=create_prefix,
1341
use_existing_dir=use_existing_dir, no_tree=no_tree)
886
1344
class cmd_branch(Command):
887
"""Create a new copy of a branch.
1345
__doc__ = """Create a new branch that is a copy of an existing branch.
889
1347
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
890
1348
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
896
1354
To retrieve the branch as of a particular revision, supply the --revision
897
1355
parameter, as in "branch foo/bar -r 5".
1357
The synonyms 'clone' and 'get' for this command are deprecated.
900
1360
_see_also = ['checkout']
901
1361
takes_args = ['from_location', 'to_location?']
902
takes_options = ['revision', Option('hardlink',
903
help='Hard-link working tree files where possible.')]
1362
takes_options = ['revision',
1363
Option('hardlink', help='Hard-link working tree files where possible.'),
1364
Option('files-from', type=str,
1365
help="Get file contents from this tree."),
1367
help="Create a branch without a working-tree."),
1369
help="Switch the checkout in the current directory "
1370
"to the new branch."),
1372
help='Create a stacked branch referring to the source branch. '
1373
'The new branch will depend on the availability of the source '
1374
'branch for all operations.'),
1375
Option('standalone',
1376
help='Do not use a shared repository, even if available.'),
1377
Option('use-existing-dir',
1378
help='By default branch will fail if the target'
1379
' directory exists, but does not already'
1380
' have a control directory. This flag will'
1381
' allow branch to proceed.'),
1383
help="Bind new branch to from location."),
904
1385
aliases = ['get', 'clone']
906
1387
def run(self, from_location, to_location=None, revision=None,
1388
hardlink=False, stacked=False, standalone=False, no_tree=False,
1389
use_existing_dir=False, switch=False, bind=False,
1391
from bzrlib import switch as _mod_switch
908
1392
from bzrlib.tag import _merge_tags_if_possible
911
elif len(revision) > 1:
912
raise errors.BzrCommandError(
913
'bzr branch --revision takes exactly 1 revision value')
915
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1393
if self.invoked_as in ['get', 'clone']:
1394
ui.ui_factory.show_user_warning(
1395
'deprecated_command',
1396
deprecated_name=self.invoked_as,
1397
recommended_name='branch',
1398
deprecated_in_version='2.4')
1399
accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
919
if len(revision) == 1 and revision[0] is not None:
920
revision_id = revision[0].as_revision_id(br_from)
922
# FIXME - wt.last_revision, fallback to branch, fall back to
923
# None or perhaps NULL_REVISION to mean copy nothing
925
revision_id = br_from.last_revision()
1401
if not (hardlink or files_from):
1402
# accelerator_tree is usually slower because you have to read N
1403
# files (no readahead, lots of seeks, etc), but allow the user to
1404
# explicitly request it
1405
accelerator_tree = None
1406
if files_from is not None and files_from != from_location:
1407
accelerator_tree = WorkingTree.open(files_from)
1408
revision = _get_one_revision('branch', revision)
1409
self.add_cleanup(br_from.lock_read().unlock)
1410
if revision is not None:
1411
revision_id = revision.as_revision_id(br_from)
1413
# FIXME - wt.last_revision, fallback to branch, fall back to
1414
# None or perhaps NULL_REVISION to mean copy nothing
1416
revision_id = br_from.last_revision()
1417
if to_location is None:
1418
to_location = getattr(br_from, "name", None)
926
1419
if to_location is None:
927
1420
to_location = urlutils.derive_to_location(from_location)
928
to_transport = transport.get_transport(to_location)
1421
to_transport = transport.get_transport(to_location)
1423
to_transport.mkdir('.')
1424
except errors.FileExists:
930
to_transport.mkdir('.')
931
except errors.FileExists:
932
raise errors.BzrCommandError('Target directory "%s" already'
933
' exists.' % to_location)
934
except errors.NoSuchFile:
935
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1426
to_dir = controldir.ControlDir.open_from_transport(
1428
except errors.NotBranchError:
1429
if not use_existing_dir:
1430
raise errors.BzrCommandError(gettext('Target directory "%s" '
1431
'already exists.') % to_location)
1436
to_dir.open_branch()
1437
except errors.NotBranchError:
1440
raise errors.AlreadyBranchError(to_location)
1441
except errors.NoSuchFile:
1442
raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
938
1448
# preserve whatever source format we have.
939
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1449
to_dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
940
1450
possible_transports=[to_transport],
941
1451
accelerator_tree=accelerator_tree,
943
branch = dir.open_branch()
1452
hardlink=hardlink, stacked=stacked,
1453
force_new_repo=standalone,
1454
create_tree_if_local=not no_tree,
1455
source_branch=br_from)
1456
branch = to_dir.open_branch(
1457
possible_transports=[
1458
br_from.bzrdir.root_transport, to_transport])
944
1459
except errors.NoSuchRevision:
945
1460
to_transport.delete_tree('.')
946
msg = "The branch %s has no revision %s." % (from_location, revision[0])
1461
msg = gettext("The branch {0} has no revision {1}.").format(
1462
from_location, revision)
947
1463
raise errors.BzrCommandError(msg)
948
_merge_tags_if_possible(br_from, branch)
949
note('Branched %d revision(s).' % branch.revno())
1466
to_repo = to_dir.open_repository()
1467
except errors.NoRepositoryPresent:
1468
to_repo = to_dir.create_repository()
1469
to_repo.fetch(br_from.repository, revision_id=revision_id)
1470
branch = br_from.sprout(to_dir, revision_id=revision_id)
1471
_merge_tags_if_possible(br_from, branch)
1472
# If the source branch is stacked, the new branch may
1473
# be stacked whether we asked for that explicitly or not.
1474
# We therefore need a try/except here and not just 'if stacked:'
1476
note(gettext('Created new stacked branch referring to %s.') %
1477
branch.get_stacked_on_url())
1478
except (errors.NotStacked, errors.UnstackableBranchFormat,
1479
errors.UnstackableRepositoryFormat), e:
1480
note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
1482
# Bind to the parent
1483
parent_branch = Branch.open(from_location)
1484
branch.bind(parent_branch)
1485
note(gettext('New branch bound to %s') % from_location)
1487
# Switch to the new branch
1488
wt, _ = WorkingTree.open_containing('.')
1489
_mod_switch.switch(wt.bzrdir, branch)
1490
note(gettext('Switched to branch: %s'),
1491
urlutils.unescape_for_display(branch.base, 'utf-8'))
1494
class cmd_branches(Command):
1495
__doc__ = """List the branches available at the current location.
1497
This command will print the names of all the branches at the current
1501
takes_args = ['location?']
1503
Option('recursive', short_name='R',
1504
help='Recursively scan for branches rather than '
1505
'just looking in the specified location.')]
1507
def run(self, location=".", recursive=False):
1509
t = transport.get_transport(location)
1510
if not t.listable():
1511
raise errors.BzrCommandError(
1512
"Can't scan this type of location.")
1513
for b in controldir.ControlDir.find_branches(t):
1514
self.outf.write("%s\n" % urlutils.unescape_for_display(
1515
urlutils.relative_url(t.base, b.base),
1516
self.outf.encoding).rstrip("/"))
1518
dir = controldir.ControlDir.open_containing(location)[0]
1520
active_branch = dir.open_branch(name="")
1521
except errors.NotBranchError:
1522
active_branch = None
1523
branches = dir.get_branches()
1525
for name, branch in branches.iteritems():
1528
active = (active_branch is not None and
1529
active_branch.base == branch.base)
1530
names[name] = active
1531
# Only mention the current branch explicitly if it's not
1532
# one of the colocated branches
1533
if not any(names.values()) and active_branch is not None:
1534
self.outf.write("* %s\n" % gettext("(default)"))
1535
for name in sorted(names.keys()):
1536
active = names[name]
1541
self.outf.write("%s %s\n" % (
1542
prefix, name.encode(self.outf.encoding)))
954
1545
class cmd_checkout(Command):
955
"""Create a new checkout of an existing branch.
1546
__doc__ = """Create a new checkout of an existing branch.
957
1548
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
958
1549
the branch found in '.'. This is useful if you have removed the working tree
959
1550
or if it was never created - i.e. if you pushed the branch to its current
960
1551
location using SFTP.
962
1553
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
963
1554
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
964
1555
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1036
1628
@display_command
1037
1629
def run(self, dir=u'.'):
1038
1630
tree = WorkingTree.open_containing(dir)[0]
1041
new_inv = tree.inventory
1042
old_tree = tree.basis_tree()
1043
old_tree.lock_read()
1045
old_inv = old_tree.inventory
1046
renames = list(_mod_tree.find_renames(old_inv, new_inv))
1048
for old_name, new_name in renames:
1049
self.outf.write("%s => %s\n" % (old_name, new_name))
1631
self.add_cleanup(tree.lock_read().unlock)
1632
new_inv = tree.inventory
1633
old_tree = tree.basis_tree()
1634
self.add_cleanup(old_tree.lock_read().unlock)
1635
old_inv = old_tree.inventory
1637
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1638
for f, paths, c, v, p, n, k, e in iterator:
1639
if paths[0] == paths[1]:
1643
renames.append(paths)
1645
for old_name, new_name in renames:
1646
self.outf.write("%s => %s\n" % (old_name, new_name))
1056
1649
class cmd_update(Command):
1057
"""Update a tree to have the latest code committed to its branch.
1059
This will perform a merge into the working tree, and may generate
1060
conflicts. If you have any local changes, you will still
1061
need to commit them after the update for the update to be complete.
1063
If you want to discard your local changes, you can just do a
1064
'bzr revert' instead of 'bzr commit' after the update.
1650
__doc__ = """Update a working tree to a new revision.
1652
This will perform a merge of the destination revision (the tip of the
1653
branch, or the specified revision) into the working tree, and then make
1654
that revision the basis revision for the working tree.
1656
You can use this to visit an older revision, or to update a working tree
1657
that is out of date from its branch.
1659
If there are any uncommitted changes in the tree, they will be carried
1660
across and remain as uncommitted changes after the update. To discard
1661
these changes, use 'bzr revert'. The uncommitted changes may conflict
1662
with the changes brought in by the change in basis revision.
1664
If the tree's branch is bound to a master branch, bzr will also update
1665
the branch from the master.
1667
You cannot update just a single file or directory, because each Bazaar
1668
working tree has just a single basis revision. If you want to restore a
1669
file that has been removed locally, use 'bzr revert' instead of 'bzr
1670
update'. If you want to restore a file to its state in a previous
1671
revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
1672
out the old content of that file to a new location.
1674
The 'dir' argument, if given, must be the location of the root of a
1675
working tree to update. By default, the working tree that contains the
1676
current working directory is used.
1067
1679
_see_also = ['pull', 'working-trees', 'status-flags']
1068
1680
takes_args = ['dir?']
1681
takes_options = ['revision',
1683
help="Show base revision text in conflicts."),
1069
1685
aliases = ['up']
1071
def run(self, dir='.'):
1072
tree = WorkingTree.open_containing(dir)[0]
1687
def run(self, dir=None, revision=None, show_base=None):
1688
if revision is not None and len(revision) != 1:
1689
raise errors.BzrCommandError(gettext(
1690
"bzr update --revision takes exactly one revision"))
1692
tree = WorkingTree.open_containing('.')[0]
1694
tree, relpath = WorkingTree.open_containing(dir)
1697
raise errors.BzrCommandError(gettext(
1698
"bzr update can only update a whole tree, "
1699
"not a file or subdirectory"))
1700
branch = tree.branch
1073
1701
possible_transports = []
1074
master = tree.branch.get_master_branch(
1702
master = branch.get_master_branch(
1075
1703
possible_transports=possible_transports)
1076
1704
if master is not None:
1705
branch_location = master.base
1077
1706
tree.lock_write()
1708
branch_location = tree.branch.base
1079
1709
tree.lock_tree_write()
1710
self.add_cleanup(tree.unlock)
1711
# get rid of the final '/' and be ready for display
1712
branch_location = urlutils.unescape_for_display(
1713
branch_location.rstrip('/'),
1715
existing_pending_merges = tree.get_parent_ids()[1:]
1719
# may need to fetch data into a heavyweight checkout
1720
# XXX: this may take some time, maybe we should display a
1722
old_tip = branch.update(possible_transports)
1723
if revision is not None:
1724
revision_id = revision[0].as_revision_id(branch)
1726
revision_id = branch.last_revision()
1727
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1728
revno = branch.revision_id_to_dotted_revno(revision_id)
1729
note(gettext("Tree is up to date at revision {0} of branch {1}"
1730
).format('.'.join(map(str, revno)), branch_location))
1732
view_info = _get_view_info_for_change_reporter(tree)
1733
change_reporter = delta._ChangeReporter(
1734
unversioned_filter=tree.is_ignored,
1735
view_info=view_info)
1081
existing_pending_merges = tree.get_parent_ids()[1:]
1082
last_rev = _mod_revision.ensure_null(tree.last_revision())
1083
if last_rev == _mod_revision.ensure_null(
1084
tree.branch.last_revision()):
1085
# may be up to date, check master too.
1086
if master is None or last_rev == _mod_revision.ensure_null(
1087
master.last_revision()):
1088
revno = tree.branch.revision_id_to_revno(last_rev)
1089
note("Tree is up to date at revision %d." % (revno,))
1091
1737
conflicts = tree.update(
1092
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1093
possible_transports=possible_transports)
1094
revno = tree.branch.revision_id_to_revno(
1095
_mod_revision.ensure_null(tree.last_revision()))
1096
note('Updated to revision %d.' % (revno,))
1097
if tree.get_parent_ids()[1:] != existing_pending_merges:
1098
note('Your local commits will now show as pending merges with '
1099
"'bzr status', and can be committed with 'bzr commit'.")
1739
possible_transports=possible_transports,
1740
revision=revision_id,
1742
show_base=show_base)
1743
except errors.NoSuchRevision, e:
1744
raise errors.BzrCommandError(gettext(
1745
"branch has no revision %s\n"
1746
"bzr update --revision only works"
1747
" for a revision in the branch history")
1749
revno = tree.branch.revision_id_to_dotted_revno(
1750
_mod_revision.ensure_null(tree.last_revision()))
1751
note(gettext('Updated to revision {0} of branch {1}').format(
1752
'.'.join(map(str, revno)), branch_location))
1753
parent_ids = tree.get_parent_ids()
1754
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1755
note(gettext('Your local commits will now show as pending merges with '
1756
"'bzr status', and can be committed with 'bzr commit'."))
1108
1763
class cmd_info(Command):
1109
"""Show information about a working tree, branch or repository.
1764
__doc__ = """Show information about a working tree, branch or repository.
1111
1766
This command will show all known locations and formats associated to the
1112
tree, branch or repository. Statistical information is included with
1767
tree, branch or repository.
1769
In verbose mode, statistical information is included with each report.
1770
To see extended statistic information, use a verbosity level of 2 or
1771
higher by specifying the verbose option multiple times, e.g. -vv.
1115
1773
Branches and working trees will also report any missing revisions.
1777
Display information on the format and related locations:
1781
Display the above together with extended format information and
1782
basic statistics (like the number of files in the working tree and
1783
number of revisions in the branch and repository):
1787
Display the above together with number of committers to the branch:
1117
1791
_see_also = ['revno', 'working-trees', 'repositories']
1118
1792
takes_args = ['location?']
1122
1796
@display_command
1123
1797
def run(self, location=None, verbose=False):
1799
noise_level = get_verbosity_level()
1127
1801
noise_level = 0
1128
1802
from bzrlib.info import show_bzrdir_info
1129
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1803
show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
1130
1804
verbose=noise_level, outfile=self.outf)
1133
1807
class cmd_remove(Command):
1134
"""Remove files or directories.
1136
This makes bzr stop tracking changes to the specified files and
1137
delete them if they can easily be recovered using revert.
1139
You can specify one or more files, and/or --new. If you specify --new,
1140
only 'added' files will be removed. If you specify both, then new files
1141
in the specified directories will be removed. If the directories are
1142
also new, they will also be removed.
1808
__doc__ = """Remove files or directories.
1810
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1811
delete them if they can easily be recovered using revert otherwise they
1812
will be backed up (adding an extention of the form .~#~). If no options or
1813
parameters are given Bazaar will scan for files that are being tracked by
1814
Bazaar but missing in your tree and stop tracking them for you.
1144
1816
takes_args = ['file*']
1145
1817
takes_options = ['verbose',
1146
Option('new', help='Remove newly-added files.'),
1818
Option('new', help='Only remove files that have never been committed.'),
1147
1819
RegistryOption.from_kwargs('file-deletion-strategy',
1148
1820
'The file deletion mode to be used.',
1149
1821
title='Deletion Strategy', value_switches=True, enum_switch=False,
1150
safe='Only delete files if they can be'
1151
' safely recovered (default).',
1152
keep="Don't delete any files.",
1822
safe='Backup changed files (default).',
1823
keep='Delete from bzr but leave the working copy.',
1824
no_backup='Don\'t backup changed files.',
1153
1825
force='Delete all the specified files, even if they can not be '
1154
'recovered and even if they are non-empty directories.')]
1826
'recovered and even if they are non-empty directories. '
1827
'(deprecated, use no-backup)')]
1828
aliases = ['rm', 'del']
1156
1829
encoding_type = 'replace'
1158
1831
def run(self, file_list, verbose=False, new=False,
1159
1832
file_deletion_strategy='safe'):
1160
tree, file_list = tree_files(file_list)
1833
if file_deletion_strategy == 'force':
1834
note(gettext("(The --force option is deprecated, rather use --no-backup "
1836
file_deletion_strategy = 'no-backup'
1838
tree, file_list = WorkingTree.open_containing_paths(file_list)
1162
1840
if file_list is not None:
1163
1841
file_list = [f for f in file_list]
1165
raise errors.BzrCommandError('Specify one or more files to'
1166
' remove, or use --new.')
1843
self.add_cleanup(tree.lock_write().unlock)
1844
# Heuristics should probably all move into tree.remove_smart or
1169
1847
added = tree.changes_from(tree.basis_tree(),
1170
1848
specific_files=file_list).added
1171
1849
file_list = sorted([f[0] for f in added], reverse=True)
1172
1850
if len(file_list) == 0:
1173
raise errors.BzrCommandError('No matching files.')
1851
raise errors.BzrCommandError(gettext('No matching files.'))
1852
elif file_list is None:
1853
# missing files show up in iter_changes(basis) as
1854
# versioned-with-no-kind.
1856
for change in tree.iter_changes(tree.basis_tree()):
1857
# Find paths in the working tree that have no kind:
1858
if change[1][1] is not None and change[6][1] is None:
1859
missing.append(change[1][1])
1860
file_list = sorted(missing, reverse=True)
1861
file_deletion_strategy = 'keep'
1174
1862
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1175
1863
keep_files=file_deletion_strategy=='keep',
1176
force=file_deletion_strategy=='force')
1864
force=(file_deletion_strategy=='no-backup'))
1179
1867
class cmd_file_id(Command):
1180
"""Print file_id of a particular file or directory.
1868
__doc__ = """Print file_id of a particular file or directory.
1182
1870
The file_id is assigned when the file is first added and remains the
1183
1871
same through all revisions where the file exists, even when it is
1348
2052
to_transport.ensure_base()
1349
2053
except errors.NoSuchFile:
1350
2054
if not create_prefix:
1351
raise errors.BzrCommandError("Parent directory of %s"
2055
raise errors.BzrCommandError(gettext("Parent directory of %s"
1352
2056
" does not exist."
1353
2057
"\nYou may supply --create-prefix to create all"
1354
" leading parent directories."
2058
" leading parent directories.")
1356
_create_prefix(to_transport)
2060
to_transport.create_prefix()
1359
existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
2063
a_bzrdir = controldir.ControlDir.open_from_transport(to_transport)
1360
2064
except errors.NotBranchError:
1361
2065
# really a NotBzrDir error...
1362
create_branch = bzrdir.BzrDir.create_branch_convenience
2066
create_branch = controldir.ControlDir.create_branch_convenience
2068
force_new_tree = False
2070
force_new_tree = None
1363
2071
branch = create_branch(to_transport.base, format=format,
1364
possible_transports=[to_transport])
2072
possible_transports=[to_transport],
2073
force_new_tree=force_new_tree)
2074
a_bzrdir = branch.bzrdir
1366
2076
from bzrlib.transport.local import LocalTransport
1367
if existing_bzrdir.has_branch():
2077
if a_bzrdir.has_branch():
1368
2078
if (isinstance(to_transport, LocalTransport)
1369
and not existing_bzrdir.has_workingtree()):
2079
and not a_bzrdir.has_workingtree()):
1370
2080
raise errors.BranchExistsWithoutWorkingTree(location)
1371
2081
raise errors.AlreadyBranchError(location)
1373
branch = existing_bzrdir.create_branch()
1374
existing_bzrdir.create_workingtree()
2082
branch = a_bzrdir.create_branch()
2083
if not no_tree and not a_bzrdir.has_workingtree():
2084
a_bzrdir.create_workingtree()
1375
2085
if append_revisions_only:
1377
2087
branch.set_append_revisions_only(True)
1378
2088
except errors.UpgradeRequired:
1379
raise errors.BzrCommandError('This branch format cannot be set'
1380
' to append-revisions-only. Try --experimental-branch6')
2089
raise errors.BzrCommandError(gettext('This branch format cannot be set'
2090
' to append-revisions-only. Try --default.'))
2092
from bzrlib.info import describe_layout, describe_format
2094
tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
2095
except (errors.NoWorkingTree, errors.NotLocalUrl):
2097
repository = branch.repository
2098
layout = describe_layout(repository, branch, tree).lower()
2099
format = describe_format(a_bzrdir, repository, branch, tree)
2100
self.outf.write(gettext("Created a {0} (format: {1})\n").format(
2102
if repository.is_shared():
2103
#XXX: maybe this can be refactored into transport.path_or_url()
2104
url = repository.bzrdir.root_transport.external_url()
2106
url = urlutils.local_path_from_url(url)
2107
except errors.InvalidURL:
2109
self.outf.write(gettext("Using shared repository: %s\n") % url)
1383
2112
class cmd_init_repository(Command):
1384
"""Create a shared repository to hold branches.
2113
__doc__ = """Create a shared repository for branches to share storage space.
1386
2115
New branches created under the repository directory will store their
1387
revisions in the repository, not in the branch directory.
2116
revisions in the repository, not in the branch directory. For branches
2117
with shared history, this reduces the amount of storage needed and
2118
speeds up the creation of new branches.
1389
If the --no-trees option is used then the branches in the repository
1390
will not have working trees by default.
2120
If the --no-trees option is given then the branches in the repository
2121
will not have working trees by default. They will still exist as
2122
directories on disk, but they will not have separate copies of the
2123
files at a certain revision. This can be useful for repositories that
2124
store branches which are interacted with through checkouts or remote
2125
branches, such as on a server.
1393
Create a shared repositories holding just branches::
2128
Create a shared repository holding just branches::
1395
2130
bzr init-repo --no-trees repo
1396
2131
bzr init repo/trunk
1645
2431
return int(limitstring)
1646
2432
except ValueError:
1647
msg = "The limit argument must be an integer."
2433
msg = gettext("The limit argument must be an integer.")
2434
raise errors.BzrCommandError(msg)
2437
def _parse_levels(s):
2441
msg = gettext("The levels argument must be an integer.")
1648
2442
raise errors.BzrCommandError(msg)
1651
2445
class cmd_log(Command):
1652
"""Show log of a branch, file, or directory.
1654
By default show the log of the branch containing the working directory.
1656
To request a range of logs, you can use the command -r begin..end
1657
-r revision requests a specific revision, -r ..end or -r begin.. are
1661
Log the current branch::
1669
Log the last 10 revisions of a branch::
1671
bzr log -r -10.. http://server/branch
2446
__doc__ = """Show historical log for a branch or subset of a branch.
2448
log is bzr's default tool for exploring the history of a branch.
2449
The branch to use is taken from the first parameter. If no parameters
2450
are given, the branch containing the working directory is logged.
2451
Here are some simple examples::
2453
bzr log log the current branch
2454
bzr log foo.py log a file in its branch
2455
bzr log http://server/branch log a branch on a server
2457
The filtering, ordering and information shown for each revision can
2458
be controlled as explained below. By default, all revisions are
2459
shown sorted (topologically) so that newer revisions appear before
2460
older ones and descendants always appear before ancestors. If displayed,
2461
merged revisions are shown indented under the revision in which they
2466
The log format controls how information about each revision is
2467
displayed. The standard log formats are called ``long``, ``short``
2468
and ``line``. The default is long. See ``bzr help log-formats``
2469
for more details on log formats.
2471
The following options can be used to control what information is
2474
-l N display a maximum of N revisions
2475
-n N display N levels of revisions (0 for all, 1 for collapsed)
2476
-v display a status summary (delta) for each revision
2477
-p display a diff (patch) for each revision
2478
--show-ids display revision-ids (and file-ids), not just revnos
2480
Note that the default number of levels to display is a function of the
2481
log format. If the -n option is not used, the standard log formats show
2482
just the top level (mainline).
2484
Status summaries are shown using status flags like A, M, etc. To see
2485
the changes explained using words like ``added`` and ``modified``
2486
instead, use the -vv option.
2490
To display revisions from oldest to newest, use the --forward option.
2491
In most cases, using this option will have little impact on the total
2492
time taken to produce a log, though --forward does not incrementally
2493
display revisions like --reverse does when it can.
2495
:Revision filtering:
2497
The -r option can be used to specify what revision or range of revisions
2498
to filter against. The various forms are shown below::
2500
-rX display revision X
2501
-rX.. display revision X and later
2502
-r..Y display up to and including revision Y
2503
-rX..Y display from X to Y inclusive
2505
See ``bzr help revisionspec`` for details on how to specify X and Y.
2506
Some common examples are given below::
2508
-r-1 show just the tip
2509
-r-10.. show the last 10 mainline revisions
2510
-rsubmit:.. show what's new on this branch
2511
-rancestor:path.. show changes since the common ancestor of this
2512
branch and the one at location path
2513
-rdate:yesterday.. show changes since yesterday
2515
When logging a range of revisions using -rX..Y, log starts at
2516
revision Y and searches back in history through the primary
2517
("left-hand") parents until it finds X. When logging just the
2518
top level (using -n1), an error is reported if X is not found
2519
along the way. If multi-level logging is used (-n0), X may be
2520
a nested merge revision and the log will be truncated accordingly.
2524
If parameters are given and the first one is not a branch, the log
2525
will be filtered to show only those revisions that changed the
2526
nominated files or directories.
2528
Filenames are interpreted within their historical context. To log a
2529
deleted file, specify a revision range so that the file existed at
2530
the end or start of the range.
2532
Historical context is also important when interpreting pathnames of
2533
renamed files/directories. Consider the following example:
2535
* revision 1: add tutorial.txt
2536
* revision 2: modify tutorial.txt
2537
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2541
* ``bzr log guide.txt`` will log the file added in revision 1
2543
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2545
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2546
the original file in revision 2.
2548
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2549
was no file called guide.txt in revision 2.
2551
Renames are always followed by log. By design, there is no need to
2552
explicitly ask for this (and no way to stop logging a file back
2553
until it was last renamed).
2557
The --match option can be used for finding revisions that match a
2558
regular expression in a commit message, committer, author or bug.
2559
Specifying the option several times will match any of the supplied
2560
expressions. --match-author, --match-bugs, --match-committer and
2561
--match-message can be used to only match a specific field.
2565
GUI tools and IDEs are often better at exploring history than command
2566
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2567
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2568
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2569
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2571
You may find it useful to add the aliases below to ``bazaar.conf``::
2575
top = log -l10 --line
2578
``bzr tip`` will then show the latest revision while ``bzr top``
2579
will show the last 10 mainline revisions. To see the details of a
2580
particular revision X, ``bzr show -rX``.
2582
If you are interested in looking deeper into a particular merge X,
2583
use ``bzr log -n0 -rX``.
2585
``bzr log -v`` on a branch with lots of history is currently
2586
very slow. A fix for this issue is currently under development.
2587
With or without that fix, it is recommended that a revision range
2588
be given when using the -v option.
2590
bzr has a generic full-text matching plugin, bzr-search, that can be
2591
used to find revisions matching user names, commit messages, etc.
2592
Among other features, this plugin can find all revisions containing
2593
a list of words but not others.
2595
When exploring non-mainline history on large projects with deep
2596
history, the performance of log can be greatly improved by installing
2597
the historycache plugin. This plugin buffers historical information
2598
trading disk space for faster speed.
1674
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1676
takes_args = ['location?']
2600
takes_args = ['file*']
2601
_see_also = ['log-formats', 'revisionspec']
1677
2602
takes_options = [
1678
2603
Option('forward',
1679
2604
help='Show from oldest to newest.'),
1682
help='Display timezone as local, original, or utc.'),
1683
2606
custom_help('verbose',
1684
2607
help='Show files changed in each revision.'),
2611
type=bzrlib.option._parse_revision_str,
2613
help='Show just the specified revision.'
2614
' See also "help revisionspec".'),
2616
RegistryOption('authors',
2617
'What names to list as authors - first, all or committer.',
2619
lazy_registry=('bzrlib.log', 'author_list_registry'),
2623
help='Number of levels to display - 0 for all, 1 for flat.',
2625
type=_parse_levels),
1688
2626
Option('message',
1690
2627
help='Show revisions whose message matches this '
1691
2628
'regular expression.',
1693
2631
Option('limit',
1694
2632
short_name='l',
1695
2633
help='Limit the output to the first N revisions.',
1697
2635
type=_parse_limit),
2638
help='Show changes made in each revision as a patch.'),
2639
Option('include-merged',
2640
help='Show merged revisions like --levels 0 does.'),
2641
Option('include-merges', hidden=True,
2642
help='Historical alias for --include-merged.'),
2643
Option('omit-merges',
2644
help='Do not report commits with more than one parent.'),
2645
Option('exclude-common-ancestry',
2646
help='Display only the revisions that are not part'
2647
' of both ancestries (require -rX..Y).'
2649
Option('signatures',
2650
help='Show digital signature validity.'),
2653
help='Show revisions whose properties match this '
2656
ListOption('match-message',
2657
help='Show revisions whose message matches this '
2660
ListOption('match-committer',
2661
help='Show revisions whose committer matches this '
2664
ListOption('match-author',
2665
help='Show revisions whose authors match this '
2668
ListOption('match-bugs',
2669
help='Show revisions whose bugs match this '
1699
2673
encoding_type = 'replace'
1701
2675
@display_command
1702
def run(self, location=None, timezone='original',
2676
def run(self, file_list=None, timezone='original',
1704
2678
show_ids=False,
1707
2682
log_format=None,
1710
from bzrlib.log import show_log
2687
include_merged=None,
2689
exclude_common_ancestry=False,
2693
match_committer=None,
2697
include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2699
from bzrlib.log import (
2701
make_log_request_dict,
2702
_get_info_for_log_files,
1711
2704
direction = (forward and 'forward') or 'reverse'
1716
# find the file id to log:
1718
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1722
tree = b.basis_tree()
1723
file_id = tree.path2id(fp)
2705
if symbol_versioning.deprecated_passed(include_merges):
2706
ui.ui_factory.show_user_warning(
2707
'deprecated_command_option',
2708
deprecated_name='--include-merges',
2709
recommended_name='--include-merged',
2710
deprecated_in_version='2.5',
2711
command=self.invoked_as)
2712
if include_merged is None:
2713
include_merged = include_merges
2715
raise errors.BzrCommandError(gettext(
2716
'{0} and {1} are mutually exclusive').format(
2717
'--include-merges', '--include-merged'))
2718
if include_merged is None:
2719
include_merged = False
2720
if (exclude_common_ancestry
2721
and (revision is None or len(revision) != 2)):
2722
raise errors.BzrCommandError(gettext(
2723
'--exclude-common-ancestry requires -r with two revisions'))
2728
raise errors.BzrCommandError(gettext(
2729
'{0} and {1} are mutually exclusive').format(
2730
'--levels', '--include-merged'))
2732
if change is not None:
2734
raise errors.RangeInChangeOption()
2735
if revision is not None:
2736
raise errors.BzrCommandError(gettext(
2737
'{0} and {1} are mutually exclusive').format(
2738
'--revision', '--change'))
2743
filter_by_dir = False
2745
# find the file ids to log and check for directory filtering
2746
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2747
revision, file_list, self.add_cleanup)
2748
for relpath, file_id, kind in file_info_list:
1724
2749
if file_id is None:
1725
raise errors.BzrCommandError(
1726
"Path does not have any revision history: %s" %
2750
raise errors.BzrCommandError(gettext(
2751
"Path unknown at end or start of revision range: %s") %
2753
# If the relpath is the top of the tree, we log everything
2758
file_ids.append(file_id)
2759
filter_by_dir = filter_by_dir or (
2760
kind in ['directory', 'tree-reference'])
1730
# FIXME ? log the current subdir only RBC 20060203
2763
# FIXME ? log the current subdir only RBC 20060203
1731
2764
if revision is not None \
1732
2765
and len(revision) > 0 and revision[0].get_branch():
1733
2766
location = revision[0].get_branch()
1736
dir, relpath = bzrdir.BzrDir.open_containing(location)
2769
dir, relpath = controldir.ControlDir.open_containing(location)
1737
2770
b = dir.open_branch()
1741
if revision is None:
1744
elif len(revision) == 1:
1745
rev1 = rev2 = revision[0].in_history(b)
1746
elif len(revision) == 2:
1747
if revision[1].get_branch() != revision[0].get_branch():
1748
# b is taken from revision[0].get_branch(), and
1749
# show_log will use its revision_history. Having
1750
# different branches will lead to weird behaviors.
1751
raise errors.BzrCommandError(
1752
"Log doesn't accept two revisions in different"
1754
rev1 = revision[0].in_history(b)
1755
rev2 = revision[1].in_history(b)
1757
raise errors.BzrCommandError(
1758
'bzr log --revision takes one or two values.')
1760
if log_format is None:
1761
log_format = log.log_formatter_registry.get_default(b)
1763
lf = log_format(show_ids=show_ids, to_file=self.outf,
1764
show_timezone=timezone)
1770
direction=direction,
1771
start_revision=rev1,
2771
self.add_cleanup(b.lock_read().unlock)
2772
rev1, rev2 = _get_revision_range(revision, b, self.name())
2774
if b.get_config().validate_signatures_in_log():
2778
if not gpg.GPGStrategy.verify_signatures_available():
2779
raise errors.GpgmeNotInstalled(None)
2781
# Decide on the type of delta & diff filtering to use
2782
# TODO: add an --all-files option to make this configurable & consistent
2790
diff_type = 'partial'
2794
# Build the log formatter
2795
if log_format is None:
2796
log_format = log.log_formatter_registry.get_default(b)
2797
# Make a non-encoding output to include the diffs - bug 328007
2798
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2799
lf = log_format(show_ids=show_ids, to_file=self.outf,
2800
to_exact_file=unencoded_output,
2801
show_timezone=timezone,
2802
delta_format=get_verbosity_level(),
2804
show_advice=levels is None,
2805
author_list_handler=authors)
2807
# Choose the algorithm for doing the logging. It's annoying
2808
# having multiple code paths like this but necessary until
2809
# the underlying repository format is faster at generating
2810
# deltas or can provide everything we need from the indices.
2811
# The default algorithm - match-using-deltas - works for
2812
# multiple files and directories and is faster for small
2813
# amounts of history (200 revisions say). However, it's too
2814
# slow for logging a single file in a repository with deep
2815
# history, i.e. > 10K revisions. In the spirit of "do no
2816
# evil when adding features", we continue to use the
2817
# original algorithm - per-file-graph - for the "single
2818
# file that isn't a directory without showing a delta" case.
2819
partial_history = revision and b.repository._format.supports_chks
2820
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2821
or delta_type or partial_history)
2825
match_dict[''] = match
2827
match_dict['message'] = match_message
2829
match_dict['committer'] = match_committer
2831
match_dict['author'] = match_author
2833
match_dict['bugs'] = match_bugs
2835
# Build the LogRequest and execute it
2836
if len(file_ids) == 0:
2838
rqst = make_log_request_dict(
2839
direction=direction, specific_fileids=file_ids,
2840
start_revision=rev1, end_revision=rev2, limit=limit,
2841
message_search=message, delta_type=delta_type,
2842
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2843
exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2844
signature=signatures, omit_merges=omit_merges,
2846
Logger(b, rqst).show(lf)
2849
def _get_revision_range(revisionspec_list, branch, command_name):
2850
"""Take the input of a revision option and turn it into a revision range.
2852
It returns RevisionInfo objects which can be used to obtain the rev_id's
2853
of the desired revisions. It does some user input validations.
2855
if revisionspec_list is None:
2858
elif len(revisionspec_list) == 1:
2859
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2860
elif len(revisionspec_list) == 2:
2861
start_spec = revisionspec_list[0]
2862
end_spec = revisionspec_list[1]
2863
if end_spec.get_branch() != start_spec.get_branch():
2864
# b is taken from revision[0].get_branch(), and
2865
# show_log will use its revision_history. Having
2866
# different branches will lead to weird behaviors.
2867
raise errors.BzrCommandError(gettext(
2868
"bzr %s doesn't accept two revisions in different"
2869
" branches.") % command_name)
2870
if start_spec.spec is None:
2871
# Avoid loading all the history.
2872
rev1 = RevisionInfo(branch, None, None)
2874
rev1 = start_spec.in_history(branch)
2875
# Avoid loading all of history when we know a missing
2876
# end of range means the last revision ...
2877
if end_spec.spec is None:
2878
last_revno, last_revision_id = branch.last_revision_info()
2879
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2881
rev2 = end_spec.in_history(branch)
2883
raise errors.BzrCommandError(gettext(
2884
'bzr %s --revision takes one or two values.') % command_name)
2888
def _revision_range_to_revid_range(revision_range):
2891
if revision_range[0] is not None:
2892
rev_id1 = revision_range[0].rev_id
2893
if revision_range[1] is not None:
2894
rev_id2 = revision_range[1].rev_id
2895
return rev_id1, rev_id2
1779
2897
def get_log_format(long=False, short=False, line=False, default='long'):
1780
2898
log_format = default
1799
2917
@display_command
1800
2918
def run(self, filename):
1801
2919
tree, relpath = WorkingTree.open_containing(filename)
2920
file_id = tree.path2id(relpath)
1802
2921
b = tree.branch
1803
file_id = tree.path2id(relpath)
1804
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2922
self.add_cleanup(b.lock_read().unlock)
2923
touching_revs = log.find_touching_revisions(b, file_id)
2924
for revno, revision_id, what in touching_revs:
1805
2925
self.outf.write("%6d %s\n" % (revno, what))
1808
2928
class cmd_ls(Command):
1809
"""List files in a tree.
2929
__doc__ = """List files in a tree.
1812
2932
_see_also = ['status', 'cat']
1813
2933
takes_args = ['path?']
1814
# TODO: Take a revision or remote path and list that tree instead.
1815
2934
takes_options = [
1818
Option('non-recursive',
1819
help='Don\'t recurse into subdirectories.'),
2937
Option('recursive', short_name='R',
2938
help='Recurse into subdirectories.'),
1820
2939
Option('from-root',
1821
2940
help='Print paths relative to the root of the branch.'),
1822
Option('unknown', help='Print unknown files.'),
1823
Option('versioned', help='Print versioned files.'),
1824
Option('ignored', help='Print ignored files.'),
1826
help='Write an ascii NUL (\\0) separator '
1827
'between files rather than a newline.'),
2941
Option('unknown', short_name='u',
2942
help='Print unknown files.'),
2943
Option('versioned', help='Print versioned files.',
2945
Option('ignored', short_name='i',
2946
help='Print ignored files.'),
2947
Option('kind', short_name='k',
1829
2948
help='List entries of a particular kind: file, directory, symlink.',
1833
2954
@display_command
1834
2955
def run(self, revision=None, verbose=False,
1835
non_recursive=False, from_root=False,
2956
recursive=False, from_root=False,
1836
2957
unknown=False, versioned=False, ignored=False,
1837
null=False, kind=None, show_ids=False, path=None):
2958
null=False, kind=None, show_ids=False, path=None, directory=None):
1839
2960
if kind and kind not in ('file', 'directory', 'symlink'):
1840
raise errors.BzrCommandError('invalid kind specified')
2961
raise errors.BzrCommandError(gettext('invalid kind specified'))
1842
2963
if verbose and null:
1843
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2964
raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
1844
2965
all = not (unknown or versioned or ignored)
1846
2967
selection = {'I':ignored, '?':unknown, 'V':versioned}
1848
2969
if path is None:
1853
raise errors.BzrCommandError('cannot specify both --from-root'
2973
raise errors.BzrCommandError(gettext('cannot specify both --from-root'
1857
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2976
tree, branch, relpath = \
2977
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2979
# Calculate the prefix to use
1863
if revision is not None:
1864
tree = branch.repository.revision_tree(
1865
revision[0].as_revision_id(branch))
1867
tree = branch.basis_tree()
1871
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1872
if fp.startswith(relpath):
1873
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1874
if non_recursive and '/' in fp:
1876
if not all and not selection[fc]:
1878
if kind is not None and fkind != kind:
1881
kindch = entry.kind_character()
1882
outstring = '%-8s %s%s' % (fc, fp, kindch)
1883
if show_ids and fid is not None:
1884
outstring = "%-50s %s" % (outstring, fid)
1885
self.outf.write(outstring + '\n')
1887
self.outf.write(fp + '\0')
1890
self.outf.write(fid)
1891
self.outf.write('\0')
1899
self.outf.write('%-50s %s\n' % (fp, my_id))
1901
self.outf.write(fp + '\n')
2983
prefix = relpath + '/'
2984
elif fs_path != '.' and not fs_path.endswith('/'):
2985
prefix = fs_path + '/'
2987
if revision is not None or tree is None:
2988
tree = _get_one_revision_tree('ls', revision, branch=branch)
2991
if isinstance(tree, WorkingTree) and tree.supports_views():
2992
view_files = tree.views.lookup_view()
2995
view_str = views.view_display_str(view_files)
2996
note(gettext("Ignoring files outside view. View is %s") % view_str)
2998
self.add_cleanup(tree.lock_read().unlock)
2999
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
3000
from_dir=relpath, recursive=recursive):
3001
# Apply additional masking
3002
if not all and not selection[fc]:
3004
if kind is not None and fkind != kind:
3009
fullpath = osutils.pathjoin(relpath, fp)
3012
views.check_path_in_view(tree, fullpath)
3013
except errors.FileOutsideView:
3018
fp = osutils.pathjoin(prefix, fp)
3019
kindch = entry.kind_character()
3020
outstring = fp + kindch
3021
ui.ui_factory.clear_term()
3023
outstring = '%-8s %s' % (fc, outstring)
3024
if show_ids and fid is not None:
3025
outstring = "%-50s %s" % (outstring, fid)
3026
self.outf.write(outstring + '\n')
3028
self.outf.write(fp + '\0')
3031
self.outf.write(fid)
3032
self.outf.write('\0')
3040
self.outf.write('%-50s %s\n' % (outstring, my_id))
3042
self.outf.write(outstring + '\n')
1906
3045
class cmd_unknowns(Command):
1907
"""List unknown files.
3046
__doc__ = """List unknown files.
1911
3050
_see_also = ['ls']
3051
takes_options = ['directory']
1913
3053
@display_command
1915
for f in WorkingTree.open_containing(u'.')[0].unknowns():
3054
def run(self, directory=u'.'):
3055
for f in WorkingTree.open_containing(directory)[0].unknowns():
1916
3056
self.outf.write(osutils.quotefn(f) + '\n')
1919
3059
class cmd_ignore(Command):
1920
"""Ignore specified files or patterns.
3060
__doc__ = """Ignore specified files or patterns.
3062
See ``bzr help patterns`` for details on the syntax of patterns.
3064
If a .bzrignore file does not exist, the ignore command
3065
will create one and add the specified files or patterns to the newly
3066
created file. The ignore command will also automatically add the
3067
.bzrignore file to be versioned. Creating a .bzrignore file without
3068
the use of the ignore command will require an explicit add command.
1922
3070
To remove patterns from the ignore list, edit the .bzrignore file.
1924
Trailing slashes on patterns are ignored.
1925
If the pattern contains a slash or is a regular expression, it is compared
1926
to the whole path from the branch root. Otherwise, it is compared to only
1927
the last component of the path. To match a file only in the root
1928
directory, prepend './'.
1930
Ignore patterns specifying absolute paths are not allowed.
1932
Ignore patterns may include globbing wildcards such as::
1934
? - Matches any single character except '/'
1935
* - Matches 0 or more characters except '/'
1936
/**/ - Matches 0 or more directories in a path
1937
[a-z] - Matches a single character from within a group of characters
1939
Ignore patterns may also be Python regular expressions.
1940
Regular expression ignore patterns are identified by a 'RE:' prefix
1941
followed by the regular expression. Regular expression ignore patterns
1942
may not include named or numbered groups.
1944
Note: ignore patterns containing shell wildcards must be quoted from
3071
After adding, editing or deleting that file either indirectly by
3072
using this command or directly by using an editor, be sure to commit
3075
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
3076
the global ignore file can be found in the application data directory as
3077
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
3078
Global ignores are not touched by this command. The global ignore file
3079
can be edited directly using an editor.
3081
Patterns prefixed with '!' are exceptions to ignore patterns and take
3082
precedence over regular ignores. Such exceptions are used to specify
3083
files that should be versioned which would otherwise be ignored.
3085
Patterns prefixed with '!!' act as regular ignore patterns, but have
3086
precedence over the '!' exception patterns.
3090
* Ignore patterns containing shell wildcards must be quoted from
3093
* Ignore patterns starting with "#" act as comments in the ignore file.
3094
To ignore patterns that begin with that character, use the "RE:" prefix.
1948
3097
Ignore the top level Makefile::
1950
3099
bzr ignore ./Makefile
1952
Ignore class files in all directories::
3101
Ignore .class files in all directories...::
1954
3103
bzr ignore "*.class"
3105
...but do not ignore "special.class"::
3107
bzr ignore "!special.class"
3109
Ignore files whose name begins with the "#" character::
1956
3113
Ignore .o files under the lib directory::
1958
3115
bzr ignore "lib/**/*.o"
1964
3121
Ignore everything but the "debian" toplevel directory::
1966
3123
bzr ignore "RE:(?!debian/).*"
3125
Ignore everything except the "local" toplevel directory,
3126
but always ignore autosave files ending in ~, even under local/::
3129
bzr ignore "!./local"
1969
_see_also = ['status', 'ignored']
3133
_see_also = ['status', 'ignored', 'patterns']
1970
3134
takes_args = ['name_pattern*']
1972
Option('old-default-rules',
1973
help='Write out the ignore rules bzr < 0.9 always used.')
3135
takes_options = ['directory',
3136
Option('default-rules',
3137
help='Display the default ignore rules that bzr uses.')
1976
def run(self, name_pattern_list=None, old_default_rules=None):
1977
from bzrlib.atomicfile import AtomicFile
1978
if old_default_rules is not None:
1979
# dump the rules and exit
1980
for pattern in ignores.OLD_DEFAULTS:
3140
def run(self, name_pattern_list=None, default_rules=None,
3142
from bzrlib import ignores
3143
if default_rules is not None:
3144
# dump the default rules and exit
3145
for pattern in ignores.USER_DEFAULTS:
3146
self.outf.write("%s\n" % pattern)
1983
3148
if not name_pattern_list:
1984
raise errors.BzrCommandError("ignore requires at least one "
1985
"NAME_PATTERN or --old-default-rules")
1986
name_pattern_list = [globbing.normalize_pattern(p)
3149
raise errors.BzrCommandError(gettext("ignore requires at least one "
3150
"NAME_PATTERN or --default-rules."))
3151
name_pattern_list = [globbing.normalize_pattern(p)
1987
3152
for p in name_pattern_list]
3154
bad_patterns_count = 0
3155
for p in name_pattern_list:
3156
if not globbing.Globster.is_pattern_valid(p):
3157
bad_patterns_count += 1
3158
bad_patterns += ('\n %s' % p)
3160
msg = (ngettext('Invalid ignore pattern found. %s',
3161
'Invalid ignore patterns found. %s',
3162
bad_patterns_count) % bad_patterns)
3163
ui.ui_factory.show_error(msg)
3164
raise errors.InvalidPattern('')
1988
3165
for name_pattern in name_pattern_list:
1989
if (name_pattern[0] == '/' or
3166
if (name_pattern[0] == '/' or
1990
3167
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1991
raise errors.BzrCommandError(
1992
"NAME_PATTERN should not be an absolute path")
1993
tree, relpath = WorkingTree.open_containing(u'.')
1994
ifn = tree.abspath('.bzrignore')
1995
if os.path.exists(ifn):
1998
igns = f.read().decode('utf-8')
2004
# TODO: If the file already uses crlf-style termination, maybe
2005
# we should use that for the newly added lines?
2007
if igns and igns[-1] != '\n':
2009
for name_pattern in name_pattern_list:
2010
igns += name_pattern + '\n'
2012
f = AtomicFile(ifn, 'wb')
2014
f.write(igns.encode('utf-8'))
2019
if not tree.path2id('.bzrignore'):
2020
tree.add(['.bzrignore'])
3168
raise errors.BzrCommandError(gettext(
3169
"NAME_PATTERN should not be an absolute path"))
3170
tree, relpath = WorkingTree.open_containing(directory)
3171
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2022
3172
ignored = globbing.Globster(name_pattern_list)
3174
self.add_cleanup(tree.lock_read().unlock)
2025
3175
for entry in tree.list_files():
2027
3177
if id is not None:
2028
3178
filename = entry[0]
2029
3179
if ignored.match(filename):
2030
matches.append(filename.encode('utf-8'))
3180
matches.append(filename)
2032
3181
if len(matches) > 0:
2033
print "Warning: the following files are version controlled and" \
2034
" match your ignore pattern:\n%s" % ("\n".join(matches),)
3182
self.outf.write(gettext("Warning: the following files are version "
3183
"controlled and match your ignore pattern:\n%s"
3184
"\nThese files will continue to be version controlled"
3185
" unless you 'bzr remove' them.\n") % ("\n".join(matches),))
2036
3188
class cmd_ignored(Command):
2037
"""List ignored files and the patterns that matched them.
3189
__doc__ = """List ignored files and the patterns that matched them.
3191
List all the ignored files and the ignore pattern that caused the file to
3194
Alternatively, to list just the files::
2040
3199
encoding_type = 'replace'
2041
_see_also = ['ignore']
3200
_see_also = ['ignore', 'ls']
3201
takes_options = ['directory']
2043
3203
@display_command
2045
tree = WorkingTree.open_containing(u'.')[0]
2048
for path, file_class, kind, file_id, entry in tree.list_files():
2049
if file_class != 'I':
2051
## XXX: Slightly inefficient since this was already calculated
2052
pat = tree.is_ignored(path)
2053
self.outf.write('%-50s %s\n' % (path, pat))
3204
def run(self, directory=u'.'):
3205
tree = WorkingTree.open_containing(directory)[0]
3206
self.add_cleanup(tree.lock_read().unlock)
3207
for path, file_class, kind, file_id, entry in tree.list_files():
3208
if file_class != 'I':
3210
## XXX: Slightly inefficient since this was already calculated
3211
pat = tree.is_ignored(path)
3212
self.outf.write('%-50s %s\n' % (path, pat))
2058
3215
class cmd_lookup_revision(Command):
2059
"""Lookup the revision-id from a revision-number
3216
__doc__ = """Lookup the revision-id from a revision-number
2062
3219
bzr lookup-revision 33
2065
3222
takes_args = ['revno']
3223
takes_options = ['directory']
2067
3225
@display_command
2068
def run(self, revno):
3226
def run(self, revno, directory=u'.'):
2070
3228
revno = int(revno)
2071
3229
except ValueError:
2072
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2074
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3230
raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3232
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3233
self.outf.write("%s\n" % revid)
2077
3236
class cmd_export(Command):
2078
"""Export current or past revision to a destination directory or archive.
3237
__doc__ = """Export current or past revision to a destination directory or archive.
2080
3239
If no revision is specified this exports the last committed revision.
2103
3262
================= =========================
2105
takes_args = ['dest', 'branch?']
3265
takes_args = ['dest', 'branch_or_subdir?']
3266
takes_options = ['directory',
2107
3267
Option('format',
2108
3268
help="Type of file to export to.",
3271
Option('filters', help='Apply content filters to export the '
3272
'convenient form.'),
2113
3275
help="Name of the root directory inside the exported file."),
3276
Option('per-file-timestamps',
3277
help='Set modification time of files to that of the last '
3278
'revision in which it was changed.'),
3279
Option('uncommitted',
3280
help='Export the working tree contents rather than that of the '
2115
def run(self, dest, branch=None, revision=None, format=None, root=None):
3283
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
3284
root=None, filters=False, per_file_timestamps=False, uncommitted=False,
2116
3286
from bzrlib.export import export
2119
tree = WorkingTree.open_containing(u'.')[0]
2122
b = Branch.open(branch)
2124
if revision is None:
2125
# should be tree.last_revision FIXME
2126
rev_id = b.last_revision()
2128
if len(revision) != 1:
2129
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2130
rev_id = revision[0].as_revision_id(b)
2131
t = b.repository.revision_tree(rev_id)
3288
if branch_or_subdir is None:
3289
branch_or_subdir = directory
3291
(tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
3293
if tree is not None:
3294
self.add_cleanup(tree.lock_read().unlock)
3298
raise errors.BzrCommandError(
3299
gettext("--uncommitted requires a working tree"))
3302
export_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2133
export(t, dest, format, root)
3304
export(export_tree, dest, format, root, subdir, filtered=filters,
3305
per_file_timestamps=per_file_timestamps)
2134
3306
except errors.NoSuchExportFormat, e:
2135
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3307
raise errors.BzrCommandError(
3308
gettext('Unsupported export format: %s') % e.format)
2138
3311
class cmd_cat(Command):
2139
"""Write the contents of a file as of a given revision to standard output.
3312
__doc__ = """Write the contents of a file as of a given revision to standard output.
2141
3314
If no revision is nominated, the last revision is used.
2143
3316
Note: Take care to redirect standard output when using this command on a
2147
3320
_see_also = ['ls']
3321
takes_options = ['directory',
2149
3322
Option('name-from-revision', help='The path name in the old tree.'),
3323
Option('filters', help='Apply content filters to display the '
3324
'convenience form.'),
2152
3327
takes_args = ['filename']
2153
3328
encoding_type = 'exact'
2155
3330
@display_command
2156
def run(self, filename, revision=None, name_from_revision=False):
3331
def run(self, filename, revision=None, name_from_revision=False,
3332
filters=False, directory=None):
2157
3333
if revision is not None and len(revision) != 1:
2158
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2159
" one revision specifier")
3334
raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3335
" one revision specifier"))
2160
3336
tree, branch, relpath = \
2161
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2164
return self._run(tree, branch, relpath, filename, revision,
3337
_open_directory_or_containing_tree_or_branch(filename, directory)
3338
self.add_cleanup(branch.lock_read().unlock)
3339
return self._run(tree, branch, relpath, filename, revision,
3340
name_from_revision, filters)
2169
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
3342
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2170
3344
if tree is None:
2171
3345
tree = b.basis_tree()
2172
if revision is None:
2173
revision_id = b.last_revision()
2175
revision_id = revision[0].as_revision_id(b)
3346
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3347
self.add_cleanup(rev_tree.lock_read().unlock)
2177
cur_file_id = tree.path2id(relpath)
2178
rev_tree = b.repository.revision_tree(revision_id)
2179
3349
old_file_id = rev_tree.path2id(relpath)
3351
# TODO: Split out this code to something that generically finds the
3352
# best id for a path across one or more trees; it's like
3353
# find_ids_across_trees but restricted to find just one. -- mbp
2181
3355
if name_from_revision:
3356
# Try in revision if requested
2182
3357
if old_file_id is None:
2183
raise errors.BzrCommandError("%r is not present in revision %s"
2184
% (filename, revision_id))
2186
rev_tree.print_file(old_file_id)
2187
elif cur_file_id is not None:
2188
rev_tree.print_file(cur_file_id)
2189
elif old_file_id is not None:
2190
rev_tree.print_file(old_file_id)
2192
raise errors.BzrCommandError("%r is not present in revision %s" %
2193
(filename, revision_id))
3358
raise errors.BzrCommandError(gettext(
3359
"{0!r} is not present in revision {1}").format(
3360
filename, rev_tree.get_revision_id()))
3362
actual_file_id = old_file_id
3364
cur_file_id = tree.path2id(relpath)
3365
if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3366
actual_file_id = cur_file_id
3367
elif old_file_id is not None:
3368
actual_file_id = old_file_id
3370
raise errors.BzrCommandError(gettext(
3371
"{0!r} is not present in revision {1}").format(
3372
filename, rev_tree.get_revision_id()))
3374
from bzrlib.filter_tree import ContentFilterTree
3375
filter_tree = ContentFilterTree(rev_tree,
3376
rev_tree._content_filter_stack)
3377
content = filter_tree.get_file_text(actual_file_id)
3379
content = rev_tree.get_file_text(actual_file_id)
3381
self.outf.write(content)
2196
3384
class cmd_local_time_offset(Command):
2197
"""Show the offset in seconds from GMT to local time."""
3385
__doc__ = """Show the offset in seconds from GMT to local time."""
2199
3387
@display_command
2201
print osutils.local_time_offset()
3389
self.outf.write("%s\n" % osutils.local_time_offset())
2205
3393
class cmd_commit(Command):
2206
"""Commit changes into a new revision.
2208
If no arguments are given, the entire tree is committed.
2210
If selected files are specified, only changes to those files are
2211
committed. If a directory is specified then the directory and everything
2212
within it is committed.
2214
If author of the change is not the same person as the committer, you can
2215
specify the author's name using the --author option. The name should be
2216
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2218
A selected-file commit may fail in some cases where the committed
2219
tree would be invalid. Consider::
2224
bzr commit foo -m "committing foo"
2225
bzr mv foo/bar foo/baz
2228
bzr commit foo/bar -m "committing bar but not baz"
2230
In the example above, the last commit will fail by design. This gives
2231
the user the opportunity to decide whether they want to commit the
2232
rename at the same time, separately first, or not at all. (As a general
2233
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2235
Note: A selected-file commit after a merge is not yet supported.
3394
__doc__ = """Commit changes into a new revision.
3396
An explanatory message needs to be given for each commit. This is
3397
often done by using the --message option (getting the message from the
3398
command line) or by using the --file option (getting the message from
3399
a file). If neither of these options is given, an editor is opened for
3400
the user to enter the message. To see the changed files in the
3401
boilerplate text loaded into the editor, use the --show-diff option.
3403
By default, the entire tree is committed and the person doing the
3404
commit is assumed to be the author. These defaults can be overridden
3409
If selected files are specified, only changes to those files are
3410
committed. If a directory is specified then the directory and
3411
everything within it is committed.
3413
When excludes are given, they take precedence over selected files.
3414
For example, to commit only changes within foo, but not changes
3417
bzr commit foo -x foo/bar
3419
A selective commit after a merge is not yet supported.
3423
If the author of the change is not the same person as the committer,
3424
you can specify the author's name using the --author option. The
3425
name should be in the same format as a committer-id, e.g.
3426
"John Doe <jdoe@example.com>". If there is more than one author of
3427
the change you can specify the option multiple times, once for each
3432
A common mistake is to forget to add a new file or directory before
3433
running the commit command. The --strict option checks for unknown
3434
files and aborts the commit if any are found. More advanced pre-commit
3435
checks can be implemented by defining hooks. See ``bzr help hooks``
3440
If you accidentially commit the wrong changes or make a spelling
3441
mistake in the commit message say, you can use the uncommit command
3442
to undo it. See ``bzr help uncommit`` for details.
3444
Hooks can also be configured to run after a commit. This allows you
3445
to trigger updates to external systems like bug trackers. The --fixes
3446
option can be used to record the association between a revision and
3447
one or more bugs. See ``bzr help bugs`` for details.
2237
# TODO: Run hooks on tree to-be-committed, and after commit.
2239
# TODO: Strict commit that fails if there are deleted files.
2240
# (what does "deleted files" mean ??)
2242
# TODO: Give better message for -s, --summary, used by tla people
2244
# XXX: verbose currently does nothing
2246
_see_also = ['bugs', 'uncommit']
3450
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
2247
3451
takes_args = ['selected*']
2248
3452
takes_options = [
3453
ListOption('exclude', type=str, short_name='x',
3454
help="Do not consider changes made to a given path."),
2249
3455
Option('message', type=unicode,
2250
3456
short_name='m',
2251
3457
help="Description of the new revision."),
2329
3561
if fixes is None:
2331
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
3563
bug_property = bugtracker.encode_fixes_bug_urls(
3564
self._iter_bug_fix_urls(fixes, tree.branch))
2332
3565
if bug_property:
2333
3566
properties['bugs'] = bug_property
2335
3568
if local and not tree.branch.get_bound_location():
2336
3569
raise errors.LocalRequiresBoundBranch()
3571
if message is not None:
3573
file_exists = osutils.lexists(message)
3574
except UnicodeError:
3575
# The commit message contains unicode characters that can't be
3576
# represented in the filesystem encoding, so that can't be a
3581
'The commit message is a file name: "%(f)s".\n'
3582
'(use --file "%(f)s" to take commit message from that file)'
3584
ui.ui_factory.show_warning(warning_msg)
3586
message = message.replace('\r\n', '\n')
3587
message = message.replace('\r', '\n')
3589
raise errors.BzrCommandError(gettext(
3590
"please specify either --message or --file"))
2338
3592
def get_message(commit_obj):
2339
3593
"""Callback to get commit message"""
2340
my_message = message
2341
if my_message is None and not file:
2342
t = make_commit_message_template_encoded(tree,
3597
my_message = f.read().decode(osutils.get_user_encoding())
3600
elif message is not None:
3601
my_message = message
3603
# No message supplied: make one up.
3604
# text is the status of the tree
3605
text = make_commit_message_template_encoded(tree,
2343
3606
selected_list, diff=show_diff,
2344
output_encoding=bzrlib.user_encoding)
2345
my_message = edit_commit_message_encoded(t)
2346
if my_message is None:
2347
raise errors.BzrCommandError("please specify a commit"
2348
" message with either --message or --file")
2349
elif my_message and file:
2350
raise errors.BzrCommandError(
2351
"please specify either --message or --file")
2353
my_message = codecs.open(file, 'rt',
2354
bzrlib.user_encoding).read()
2355
if my_message == "":
2356
raise errors.BzrCommandError("empty commit message specified")
3607
output_encoding=osutils.get_user_encoding())
3608
# start_message is the template generated from hooks
3609
# XXX: Warning - looks like hooks return unicode,
3610
# make_commit_message_template_encoded returns user encoding.
3611
# We probably want to be using edit_commit_message instead to
3613
my_message = set_commit_message(commit_obj)
3614
if my_message is None:
3615
start_message = generate_commit_message_template(commit_obj)
3616
my_message = edit_commit_message_encoded(text,
3617
start_message=start_message)
3618
if my_message is None:
3619
raise errors.BzrCommandError(gettext("please specify a commit"
3620
" message with either --message or --file"))
3621
if my_message == "":
3622
raise errors.BzrCommandError(gettext("Empty commit message specified."
3623
" Please specify a commit message with either"
3624
" --message or --file or leave a blank message"
3625
" with --message \"\"."))
2357
3626
return my_message
3628
# The API permits a commit with a filter of [] to mean 'select nothing'
3629
# but the command line should not do that.
3630
if not selected_list:
3631
selected_list = None
2360
3633
tree.commit(message_callback=get_message,
2361
3634
specific_files=selected_list,
2362
3635
allow_pointless=unchanged, strict=strict, local=local,
2363
3636
reporter=None, verbose=verbose, revprops=properties,
3637
authors=author, timestamp=commit_stamp,
3639
exclude=tree.safe_relpath_files(exclude),
2365
3641
except PointlessCommit:
2366
# FIXME: This should really happen before the file is read in;
2367
# perhaps prepare the commit; get the message; then actually commit
2368
raise errors.BzrCommandError("no changes to commit."
2369
" use --unchanged to commit anyhow")
3642
raise errors.BzrCommandError(gettext("No changes to commit."
3643
" Please 'bzr add' the files you want to commit, or use"
3644
" --unchanged to force an empty commit."))
2370
3645
except ConflictsInTree:
2371
raise errors.BzrCommandError('Conflicts detected in working '
3646
raise errors.BzrCommandError(gettext('Conflicts detected in working '
2372
3647
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2374
3649
except StrictCommitFailed:
2375
raise errors.BzrCommandError("Commit refused because there are"
2376
" unknown files in the working tree.")
3650
raise errors.BzrCommandError(gettext("Commit refused because there are"
3651
" unknown files in the working tree."))
2377
3652
except errors.BoundBranchOutOfDate, e:
2378
raise errors.BzrCommandError(str(e) + "\n"
2379
'To commit to master branch, run update and then commit.\n'
2380
'You can also pass --local to commit to continue working '
3653
e.extra_help = (gettext("\n"
3654
'To commit to master branch, run update and then commit.\n'
3655
'You can also pass --local to commit to continue working '
2384
3660
class cmd_check(Command):
2385
"""Validate consistency of branch history.
2387
This command checks various invariants about the branch storage to
2388
detect data corruption or bzr bugs.
2392
revisions: This is just the number of revisions checked. It doesn't
2394
versionedfiles: This is just the number of versionedfiles checked. It
2395
doesn't indicate a problem.
2396
unreferenced ancestors: Texts that are ancestors of other texts, but
2397
are not properly referenced by the revision ancestry. This is a
2398
subtle problem that Bazaar can work around.
2399
unique file texts: This is the total number of unique file contents
2400
seen in the checked revisions. It does not indicate a problem.
2401
repeated file texts: This is the total number of repeated texts seen
2402
in the checked revisions. Texts can be repeated when their file
2403
entries are modified, but the file contents are not. It does not
3661
__doc__ = """Validate working tree structure, branch consistency and repository history.
3663
This command checks various invariants about branch and repository storage
3664
to detect data corruption or bzr bugs.
3666
The working tree and branch checks will only give output if a problem is
3667
detected. The output fields of the repository check are:
3670
This is just the number of revisions checked. It doesn't
3674
This is just the number of versionedfiles checked. It
3675
doesn't indicate a problem.
3677
unreferenced ancestors
3678
Texts that are ancestors of other texts, but
3679
are not properly referenced by the revision ancestry. This is a
3680
subtle problem that Bazaar can work around.
3683
This is the total number of unique file contents
3684
seen in the checked revisions. It does not indicate a problem.
3687
This is the total number of repeated texts seen
3688
in the checked revisions. Texts can be repeated when their file
3689
entries are modified, but the file contents are not. It does not
3692
If no restrictions are specified, all Bazaar data that is found at the given
3693
location will be checked.
3697
Check the tree and branch at 'foo'::
3699
bzr check --tree --branch foo
3701
Check only the repository at 'bar'::
3703
bzr check --repo bar
3705
Check everything at 'baz'::
2407
3710
_see_also = ['reconcile']
2408
takes_args = ['branch?']
2409
takes_options = ['verbose']
3711
takes_args = ['path?']
3712
takes_options = ['verbose',
3713
Option('branch', help="Check the branch related to the"
3714
" current directory."),
3715
Option('repo', help="Check the repository related to the"
3716
" current directory."),
3717
Option('tree', help="Check the working tree related to"
3718
" the current directory.")]
2411
def run(self, branch=None, verbose=False):
2412
from bzrlib.check import check
2414
branch_obj = Branch.open_containing('.')[0]
2416
branch_obj = Branch.open(branch)
2417
check(branch_obj, verbose)
2418
# bit hacky, check the tree parent is accurate
2421
tree = WorkingTree.open_containing('.')[0]
2423
tree = WorkingTree.open(branch)
2424
except (errors.NoWorkingTree, errors.NotLocalUrl):
2427
# This is a primitive 'check' for tree state. Currently this is not
2428
# integrated into the main check logic as yet.
2431
tree_basis = tree.basis_tree()
2432
tree_basis.lock_read()
2434
repo_basis = tree.branch.repository.revision_tree(
2435
tree.last_revision())
2436
if len(list(repo_basis.iter_changes(tree_basis))):
2437
raise errors.BzrCheckError(
2438
"Mismatched basis inventory content.")
3720
def run(self, path=None, verbose=False, branch=False, repo=False,
3722
from bzrlib.check import check_dwim
3725
if not branch and not repo and not tree:
3726
branch = repo = tree = True
3727
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2446
3730
class cmd_upgrade(Command):
2447
"""Upgrade branch storage to current format.
2449
The check command or bzr developers may sometimes advise you to run
2450
this command. When the default format has changed you may also be warned
2451
during other operations to upgrade.
3731
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3733
When the default format has changed after a major new release of
3734
Bazaar, you may be informed during certain operations that you
3735
should upgrade. Upgrading to a newer format may improve performance
3736
or make new features available. It may however limit interoperability
3737
with older repositories or with older versions of Bazaar.
3739
If you wish to upgrade to a particular format rather than the
3740
current default, that can be specified using the --format option.
3741
As a consequence, you can use the upgrade command this way to
3742
"downgrade" to an earlier format, though some conversions are
3743
a one way process (e.g. changing from the 1.x default to the
3744
2.x default) so downgrading is not always possible.
3746
A backup.bzr.~#~ directory is created at the start of the conversion
3747
process (where # is a number). By default, this is left there on
3748
completion. If the conversion fails, delete the new .bzr directory
3749
and rename this one back in its place. Use the --clean option to ask
3750
for the backup.bzr directory to be removed on successful conversion.
3751
Alternatively, you can delete it by hand if everything looks good
3754
If the location given is a shared repository, dependent branches
3755
are also converted provided the repository converts successfully.
3756
If the conversion of a branch fails, remaining branches are still
3759
For more information on upgrades, see the Bazaar Upgrade Guide,
3760
http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
2454
_see_also = ['check']
3763
_see_also = ['check', 'reconcile', 'formats']
2455
3764
takes_args = ['url?']
2456
3765
takes_options = [
2457
RegistryOption('format',
2458
help='Upgrade to a specific format. See "bzr help'
2459
' formats" for details.',
2460
registry=bzrdir.format_registry,
2461
converter=bzrdir.format_registry.make_bzrdir,
2462
value_switches=True, title='Branch format'),
3766
RegistryOption('format',
3767
help='Upgrade to a specific format. See "bzr help'
3768
' formats" for details.',
3769
lazy_registry=('bzrlib.controldir', 'format_registry'),
3770
converter=lambda name: controldir.format_registry.make_bzrdir(name),
3771
value_switches=True, title='Branch format'),
3773
help='Remove the backup.bzr directory if successful.'),
3775
help="Show what would be done, but don't actually do anything."),
2465
def run(self, url='.', format=None):
3778
def run(self, url='.', format=None, clean=False, dry_run=False):
2466
3779
from bzrlib.upgrade import upgrade
2468
format = bzrdir.format_registry.make_bzrdir('default')
2469
upgrade(url, format)
3780
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3782
if len(exceptions) == 1:
3783
# Compatibility with historical behavior
2472
3789
class cmd_whoami(Command):
2473
"""Show or set bzr user id.
3790
__doc__ = """Show or set bzr user id.
2476
3793
Show the email of the current user::
2612
4022
'throughout the test suite.',
2613
4023
type=get_transport_type),
2614
4024
Option('benchmark',
2615
help='Run the benchmarks rather than selftests.'),
4025
help='Run the benchmarks rather than selftests.',
2616
4027
Option('lsprof-timed',
2617
4028
help='Generate lsprof output for benchmarked'
2618
4029
' sections of code.'),
2619
Option('cache-dir', type=str,
2620
help='Cache intermediate benchmark output in this '
4030
Option('lsprof-tests',
4031
help='Generate lsprof output for each test.'),
2622
4032
Option('first',
2623
4033
help='Run all tests, but run specified tests first.',
2624
4034
short_name='f',
2626
4036
Option('list-only',
2627
4037
help='List the tests instead of running them.'),
4038
RegistryOption('parallel',
4039
help="Run the test suite in parallel.",
4040
lazy_registry=('bzrlib.tests', 'parallel_registry'),
4041
value_switches=False,
2628
4043
Option('randomize', type=str, argname="SEED",
2629
4044
help='Randomize the order of tests using the given'
2630
4045
' seed or "now" for the current time.'),
2631
Option('exclude', type=str, argname="PATTERN",
2633
help='Exclude tests that match this regular'
4046
ListOption('exclude', type=str, argname="PATTERN",
4048
help='Exclude tests that match this regular'
4051
help='Output test progress via subunit.'),
2635
4052
Option('strict', help='Fail on missing dependencies or '
2636
4053
'known failures.'),
2637
4054
Option('load-list', type=str, argname='TESTLISTFILE',
2638
4055
help='Load a test id list from a text file.'),
2639
4056
ListOption('debugflag', type=str, short_name='E',
2640
4057
help='Turn on a selftest debug flag.'),
2641
Option('starting-with', type=str, argname='TESTID',
2643
help='Load only the tests starting with TESTID.'),
4058
ListOption('starting-with', type=str, argname='TESTID',
4059
param_name='starting_with', short_name='s',
4061
'Load only the tests starting with TESTID.'),
4063
help="By default we disable fsync and fdatasync"
4064
" while running the test suite.")
2645
4066
encoding_type = 'replace'
4069
Command.__init__(self)
4070
self.additional_selftest_args = {}
2647
4072
def run(self, testspecs_list=None, verbose=False, one=False,
2648
4073
transport=None, benchmark=None,
2649
lsprof_timed=None, cache_dir=None,
2650
4075
first=False, list_only=False,
2651
4076
randomize=None, exclude=None, strict=False,
2652
load_list=None, debugflag=None, starting_with=None):
2654
from bzrlib.tests import selftest
2655
import bzrlib.benchmarks as benchmarks
2656
from bzrlib.benchmarks import tree_creator
2658
if cache_dir is not None:
2659
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2661
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2662
print ' %s (%s python%s)' % (
2664
bzrlib.version_string,
2665
bzrlib._format_version_tuple(sys.version_info),
4077
load_list=None, debugflag=None, starting_with=None, subunit=False,
4078
parallel=None, lsprof_tests=False,
4081
# During selftest, disallow proxying, as it can cause severe
4082
# performance penalties and is only needed for thread
4083
# safety. The selftest command is assumed to not use threads
4084
# too heavily. The call should be as early as possible, as
4085
# error reporting for past duplicate imports won't have useful
4087
lazy_import.disallow_proxying()
4089
from bzrlib import tests
2668
4091
if testspecs_list is not None:
2669
4092
pattern = '|'.join(testspecs_list)
4097
from bzrlib.tests import SubUnitBzrRunner
4099
raise errors.BzrCommandError(gettext("subunit not available. subunit "
4100
"needs to be installed to use --subunit."))
4101
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
4102
# On Windows, disable automatic conversion of '\n' to '\r\n' in
4103
# stdout, which would corrupt the subunit stream.
4104
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
4105
# following code can be deleted when it's sufficiently deployed
4106
# -- vila/mgz 20100514
4107
if (sys.platform == "win32"
4108
and getattr(sys.stdout, 'fileno', None) is not None):
4110
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4112
self.additional_selftest_args.setdefault(
4113
'suite_decorators', []).append(parallel)
2673
test_suite_factory = benchmarks.test_suite
2674
# Unless user explicitly asks for quiet, be verbose in benchmarks
2675
verbose = not is_quiet()
2676
# TODO: should possibly lock the history file...
2677
benchfile = open(".perf_history", "at", buffering=1)
4115
raise errors.BzrCommandError(gettext(
4116
"--benchmark is no longer supported from bzr 2.2; "
4117
"use bzr-usertest instead"))
4118
test_suite_factory = None
4120
exclude_pattern = None
2679
test_suite_factory = None
4122
exclude_pattern = '(' + '|'.join(exclude) + ')'
4124
self._disable_fsync()
4125
selftest_kwargs = {"verbose": verbose,
4127
"stop_on_failure": one,
4128
"transport": transport,
4129
"test_suite_factory": test_suite_factory,
4130
"lsprof_timed": lsprof_timed,
4131
"lsprof_tests": lsprof_tests,
4132
"matching_tests_first": first,
4133
"list_only": list_only,
4134
"random_seed": randomize,
4135
"exclude_pattern": exclude_pattern,
4137
"load_list": load_list,
4138
"debug_flags": debugflag,
4139
"starting_with": starting_with
4141
selftest_kwargs.update(self.additional_selftest_args)
4143
# Make deprecation warnings visible, unless -Werror is set
4144
cleanup = symbol_versioning.activate_deprecation_warnings(
2682
result = selftest(verbose=verbose,
2684
stop_on_failure=one,
2685
transport=transport,
2686
test_suite_factory=test_suite_factory,
2687
lsprof_timed=lsprof_timed,
2688
bench_history=benchfile,
2689
matching_tests_first=first,
2690
list_only=list_only,
2691
random_seed=randomize,
2692
exclude_pattern=exclude,
2694
load_list=load_list,
2695
debug_flags=debugflag,
2696
starting_with=starting_with,
4147
result = tests.selftest(**selftest_kwargs)
2699
if benchfile is not None:
2702
note('tests passed')
2704
note('tests failed')
2705
4150
return int(not result)
4152
def _disable_fsync(self):
4153
"""Change the 'os' functionality to not synchronize."""
4154
self._orig_fsync = getattr(os, 'fsync', None)
4155
if self._orig_fsync is not None:
4156
os.fsync = lambda filedes: None
4157
self._orig_fdatasync = getattr(os, 'fdatasync', None)
4158
if self._orig_fdatasync is not None:
4159
os.fdatasync = lambda filedes: None
2708
4162
class cmd_version(Command):
2709
"""Show version of bzr."""
4163
__doc__ = """Show version of bzr."""
2711
4165
encoding_type = 'replace'
2712
4166
takes_options = [
2725
4179
class cmd_rocks(Command):
2726
"""Statement of optimism."""
4180
__doc__ = """Statement of optimism."""
2730
4184
@display_command
2732
print "It sure does!"
4186
self.outf.write(gettext("It sure does!\n"))
2735
4189
class cmd_find_merge_base(Command):
2736
"""Find and print a base revision for merging two branches."""
4190
__doc__ = """Find and print a base revision for merging two branches."""
2737
4191
# TODO: Options to specify revisions on either side, as if
2738
4192
# merging only part of the history.
2739
4193
takes_args = ['branch', 'other']
2742
4196
@display_command
2743
4197
def run(self, branch, other):
2744
4198
from bzrlib.revision import ensure_null
2746
4200
branch1 = Branch.open_containing(branch)[0]
2747
4201
branch2 = Branch.open_containing(other)[0]
2752
last1 = ensure_null(branch1.last_revision())
2753
last2 = ensure_null(branch2.last_revision())
2755
graph = branch1.repository.get_graph(branch2.repository)
2756
base_rev_id = graph.find_unique_lca(last1, last2)
2758
print 'merge base is revision %s' % base_rev_id
4202
self.add_cleanup(branch1.lock_read().unlock)
4203
self.add_cleanup(branch2.lock_read().unlock)
4204
last1 = ensure_null(branch1.last_revision())
4205
last2 = ensure_null(branch2.last_revision())
4207
graph = branch1.repository.get_graph(branch2.repository)
4208
base_rev_id = graph.find_unique_lca(last1, last2)
4210
self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
2765
4213
class cmd_merge(Command):
2766
"""Perform a three-way merge.
4214
__doc__ = """Perform a three-way merge.
2768
4216
The source of the merge can be specified either in the form of a branch,
2769
4217
or in the form of a path to a file containing a merge directive generated
2770
4218
with bzr send. If neither is specified, the default is the upstream branch
2771
or the branch most recently merged using --remember.
2773
When merging a branch, by default the tip will be merged. To pick a different
2774
revision, pass --revision. If you specify two values, the first will be used as
2775
BASE and the second one as OTHER. Merging individual revisions, or a subset of
2776
available revisions, like this is commonly referred to as "cherrypicking".
2778
Revision numbers are always relative to the branch being merged.
2780
By default, bzr will try to merge in all new work from the other
2781
branch, automatically determining an appropriate base. If this
2782
fails, you may need to give an explicit base.
4219
or the branch most recently merged using --remember. The source of the
4220
merge may also be specified in the form of a path to a file in another
4221
branch: in this case, only the modifications to that file are merged into
4222
the current working tree.
4224
When merging from a branch, by default bzr will try to merge in all new
4225
work from the other branch, automatically determining an appropriate base
4226
revision. If this fails, you may need to give an explicit base.
4228
To pick a different ending revision, pass "--revision OTHER". bzr will
4229
try to merge in all new work up to and including revision OTHER.
4231
If you specify two values, "--revision BASE..OTHER", only revisions BASE
4232
through OTHER, excluding BASE but including OTHER, will be merged. If this
4233
causes some revisions to be skipped, i.e. if the destination branch does
4234
not already contain revision BASE, such a merge is commonly referred to as
4235
a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4236
cherrypicks. The changes look like a normal commit, and the history of the
4237
changes from the other branch is not stored in the commit.
4239
Revision numbers are always relative to the source branch.
2784
4241
Merge will do its best to combine the changes in two branches, but there
2785
4242
are some kinds of problems only a human can fix. When it encounters those,
2786
4243
it will mark a conflict. A conflict means that you need to fix something,
2787
before you should commit.
4244
before you can commit.
2789
4246
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2791
If there is no default branch set, the first merge will set it. After
2792
that, you can omit the branch to use the default. To change the
2793
default, use --remember. The value will only be saved if the remote
2794
location can be accessed.
4248
If there is no default branch set, the first merge will set it (use
4249
--no-remember to avoid setting it). After that, you can omit the branch
4250
to use the default. To change the default, use --remember. The value will
4251
only be saved if the remote location can be accessed.
2796
4253
The results of the merge are placed into the destination working
2797
4254
directory, where they can be reviewed (with bzr diff), tested, and then
2798
4255
committed to record the result of the merge.
2800
4257
merge refuses to run if there are any uncommitted changes, unless
4258
--force is given. If --force is given, then the changes from the source
4259
will be merged with the current working tree, including any uncommitted
4260
changes in the tree. The --force option can also be used to create a
4261
merge revision which has more than two parents.
4263
If one would like to merge changes from the working tree of the other
4264
branch without merging any committed revisions, the --uncommitted option
4267
To select only some changes to merge, use "merge -i", which will prompt
4268
you to apply each diff hunk and file change, similar to "shelve".
2804
To merge the latest revision from bzr.dev::
4271
To merge all new revisions from bzr.dev::
2806
4273
bzr merge ../bzr.dev
2861
4336
allow_pending = True
2862
4337
verified = 'inapplicable'
2863
4339
tree = WorkingTree.open_containing(directory)[0]
4340
if tree.branch.revno() == 0:
4341
raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4342
'https://bugs.launchpad.net/bzr/+bug/308562'))
4345
basis_tree = tree.revision_tree(tree.last_revision())
4346
except errors.NoSuchRevision:
4347
basis_tree = tree.basis_tree()
4349
# die as quickly as possible if there are uncommitted changes
4351
if tree.has_changes():
4352
raise errors.UncommittedChanges(tree)
4354
view_info = _get_view_info_for_change_reporter(tree)
2864
4355
change_reporter = delta._ChangeReporter(
2865
unversioned_filter=tree.is_ignored)
2868
pb = ui.ui_factory.nested_progress_bar()
2869
cleanups.append(pb.finished)
2871
cleanups.append(tree.unlock)
2872
if location is not None:
2874
mergeable = bundle.read_mergeable_from_url(location,
2875
possible_transports=possible_transports)
2876
except errors.NotABundle:
2880
raise errors.BzrCommandError('Cannot use --uncommitted'
2881
' with bundles or merge directives.')
2883
if revision is not None:
2884
raise errors.BzrCommandError(
2885
'Cannot use -r with merge directives or bundles')
2886
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2889
if merger is None and uncommitted:
2890
if revision is not None and len(revision) > 0:
2891
raise errors.BzrCommandError('Cannot use --uncommitted and'
2892
' --revision at the same time.')
2893
location = self._select_branch_location(tree, location)[0]
2894
other_tree, other_path = WorkingTree.open_containing(location)
2895
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2897
allow_pending = False
2898
if other_path != '':
2899
merger.interesting_files = [other_path]
2902
merger, allow_pending = self._get_merger_from_branch(tree,
2903
location, revision, remember, possible_transports, pb)
2905
merger.merge_type = merge_type
2906
merger.reprocess = reprocess
2907
merger.show_base = show_base
2908
self.sanity_check_merger(merger)
2909
if (merger.base_rev_id == merger.other_rev_id and
2910
merger.other_rev_id is not None):
2911
note('Nothing to do.')
4356
unversioned_filter=tree.is_ignored, view_info=view_info)
4357
pb = ui.ui_factory.nested_progress_bar()
4358
self.add_cleanup(pb.finished)
4359
self.add_cleanup(tree.lock_write().unlock)
4360
if location is not None:
4362
mergeable = bundle.read_mergeable_from_url(location,
4363
possible_transports=possible_transports)
4364
except errors.NotABundle:
4368
raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4369
' with bundles or merge directives.'))
4371
if revision is not None:
4372
raise errors.BzrCommandError(gettext(
4373
'Cannot use -r with merge directives or bundles'))
4374
merger, verified = _mod_merge.Merger.from_mergeable(tree,
4377
if merger is None and uncommitted:
4378
if revision is not None and len(revision) > 0:
4379
raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4380
' --revision at the same time.'))
4381
merger = self.get_merger_from_uncommitted(tree, location, None)
4382
allow_pending = False
4385
merger, allow_pending = self._get_merger_from_branch(tree,
4386
location, revision, remember, possible_transports, None)
4388
merger.merge_type = merge_type
4389
merger.reprocess = reprocess
4390
merger.show_base = show_base
4391
self.sanity_check_merger(merger)
4392
if (merger.base_rev_id == merger.other_rev_id and
4393
merger.other_rev_id is not None):
4394
# check if location is a nonexistent file (and not a branch) to
4395
# disambiguate the 'Nothing to do'
4396
if merger.interesting_files:
4397
if not merger.other_tree.has_filename(
4398
merger.interesting_files[0]):
4399
note(gettext("merger: ") + str(merger))
4400
raise errors.PathsDoNotExist([location])
4401
note(gettext('Nothing to do.'))
4403
if pull and not preview:
4404
if merger.interesting_files is not None:
4405
raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4406
if (merger.base_rev_id == tree.last_revision()):
4407
result = tree.pull(merger.other_branch, False,
4408
merger.other_rev_id)
4409
result.report(self.outf)
2914
if merger.interesting_files is not None:
2915
raise errors.BzrCommandError('Cannot pull individual files')
2916
if (merger.base_rev_id == tree.last_revision()):
2917
result = tree.pull(merger.other_branch, False,
2918
merger.other_rev_id)
2919
result.report(self.outf)
2921
merger.check_basis(not force)
2923
return self._do_preview(merger)
2925
return self._do_merge(merger, change_reporter, allow_pending,
2928
for cleanup in reversed(cleanups):
4411
if merger.this_basis is None:
4412
raise errors.BzrCommandError(gettext(
4413
"This branch has no commits."
4414
" (perhaps you would prefer 'bzr pull')"))
4416
return self._do_preview(merger)
4418
return self._do_interactive(merger)
4420
return self._do_merge(merger, change_reporter, allow_pending,
4423
def _get_preview(self, merger):
4424
tree_merger = merger.make_merger()
4425
tt = tree_merger.make_preview_transform()
4426
self.add_cleanup(tt.finalize)
4427
result_tree = tt.get_preview_tree()
2931
4430
def _do_preview(self, merger):
2932
4431
from bzrlib.diff import show_diff_trees
2933
tree_merger = merger.make_merger()
2934
tt = tree_merger.make_preview_transform()
2936
result_tree = tt.get_preview_tree()
2937
show_diff_trees(merger.this_tree, result_tree, self.outf,
2938
old_label='', new_label='')
4432
result_tree = self._get_preview(merger)
4433
path_encoding = osutils.get_diff_header_encoding()
4434
show_diff_trees(merger.this_tree, result_tree, self.outf,
4435
old_label='', new_label='',
4436
path_encoding=path_encoding)
2942
4438
def _do_merge(self, merger, change_reporter, allow_pending, verified):
2943
4439
merger.change_reporter = change_reporter
3087
4632
def run(self, file_list=None, merge_type=None, show_base=False,
3088
4633
reprocess=False):
4634
from bzrlib.conflicts import restore
3089
4635
if merge_type is None:
3090
4636
merge_type = _mod_merge.Merge3Merger
3091
tree, file_list = tree_files(file_list)
4637
tree, file_list = WorkingTree.open_containing_paths(file_list)
4638
self.add_cleanup(tree.lock_write().unlock)
4639
parents = tree.get_parent_ids()
4640
if len(parents) != 2:
4641
raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
4642
" merges. Not cherrypicking or"
4644
repository = tree.branch.repository
4645
interesting_ids = None
4647
conflicts = tree.conflicts()
4648
if file_list is not None:
4649
interesting_ids = set()
4650
for filename in file_list:
4651
file_id = tree.path2id(filename)
4653
raise errors.NotVersionedError(filename)
4654
interesting_ids.add(file_id)
4655
if tree.kind(file_id) != "directory":
4658
for name, ie in tree.inventory.iter_entries(file_id):
4659
interesting_ids.add(ie.file_id)
4660
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4662
# Remerge only supports resolving contents conflicts
4663
allowed_conflicts = ('text conflict', 'contents conflict')
4664
restore_files = [c.path for c in conflicts
4665
if c.typestring in allowed_conflicts]
4666
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4667
tree.set_conflicts(ConflictList(new_conflicts))
4668
if file_list is not None:
4669
restore_files = file_list
4670
for filename in restore_files:
4672
restore(tree.abspath(filename))
4673
except errors.NotConflicted:
4675
# Disable pending merges, because the file texts we are remerging
4676
# have not had those merges performed. If we use the wrong parents
4677
# list, we imply that the working tree text has seen and rejected
4678
# all the changes from the other tree, when in fact those changes
4679
# have not yet been seen.
4680
tree.set_parent_ids(parents[:1])
3094
parents = tree.get_parent_ids()
3095
if len(parents) != 2:
3096
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3097
" merges. Not cherrypicking or"
3099
repository = tree.branch.repository
3100
interesting_ids = None
3102
conflicts = tree.conflicts()
3103
if file_list is not None:
3104
interesting_ids = set()
3105
for filename in file_list:
3106
file_id = tree.path2id(filename)
3108
raise errors.NotVersionedError(filename)
3109
interesting_ids.add(file_id)
3110
if tree.kind(file_id) != "directory":
3113
for name, ie in tree.inventory.iter_entries(file_id):
3114
interesting_ids.add(ie.file_id)
3115
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3117
# Remerge only supports resolving contents conflicts
3118
allowed_conflicts = ('text conflict', 'contents conflict')
3119
restore_files = [c.path for c in conflicts
3120
if c.typestring in allowed_conflicts]
3121
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3122
tree.set_conflicts(ConflictList(new_conflicts))
3123
if file_list is not None:
3124
restore_files = file_list
3125
for filename in restore_files:
3127
restore(tree.abspath(filename))
3128
except errors.NotConflicted:
3130
# Disable pending merges, because the file texts we are remerging
3131
# have not had those merges performed. If we use the wrong parents
3132
# list, we imply that the working tree text has seen and rejected
3133
# all the changes from the other tree, when in fact those changes
3134
# have not yet been seen.
3135
pb = ui.ui_factory.nested_progress_bar()
3136
tree.set_parent_ids(parents[:1])
3138
merger = _mod_merge.Merger.from_revision_ids(pb,
3140
merger.interesting_ids = interesting_ids
3141
merger.merge_type = merge_type
3142
merger.show_base = show_base
3143
merger.reprocess = reprocess
3144
conflicts = merger.do_merge()
3146
tree.set_parent_ids(parents)
4682
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4683
merger.interesting_ids = interesting_ids
4684
merger.merge_type = merge_type
4685
merger.show_base = show_base
4686
merger.reprocess = reprocess
4687
conflicts = merger.do_merge()
4689
tree.set_parent_ids(parents)
3150
4690
if conflicts > 0:
3253
4797
class cmd_shell_complete(Command):
3254
"""Show appropriate completions for context.
4798
__doc__ = """Show appropriate completions for context.
3256
4800
For a list of all available commands, say 'bzr shell-complete'.
3258
4802
takes_args = ['context?']
3259
4803
aliases = ['s-c']
3262
4806
@display_command
3263
4807
def run(self, context=None):
3264
import shellcomplete
4808
from bzrlib import shellcomplete
3265
4809
shellcomplete.shellcomplete(context)
3268
class cmd_fetch(Command):
3269
"""Copy in history from another branch but don't merge it.
3271
This is an internal method used for pull and merge.
3274
takes_args = ['from_branch', 'to_branch']
3275
def run(self, from_branch, to_branch):
3276
from bzrlib.fetch import Fetcher
3277
from_b = Branch.open(from_branch)
3278
to_b = Branch.open(to_branch)
3279
Fetcher(to_b, from_b)
3282
4812
class cmd_missing(Command):
3283
"""Show unmerged/unpulled revisions between two branches.
4813
__doc__ = """Show unmerged/unpulled revisions between two branches.
3285
4815
OTHER_BRANCH may be local or remote.
4817
To filter on a range of revisions, you can use the command -r begin..end
4818
-r revision requests a specific revision, -r ..end or -r begin.. are
4822
1 - some missing revisions
4823
0 - no missing revisions
4827
Determine the missing revisions between this and the branch at the
4828
remembered pull location::
4832
Determine the missing revisions between this and another branch::
4834
bzr missing http://server/branch
4836
Determine the missing revisions up to a specific revision on the other
4839
bzr missing -r ..-10
4841
Determine the missing revisions up to a specific revision on this
4844
bzr missing --my-revision ..-10
3288
4847
_see_also = ['merge', 'pull']
3289
4848
takes_args = ['other_branch?']
3290
4849
takes_options = [
3291
Option('reverse', 'Reverse the order of revisions.'),
3293
'Display changes in the local branch only.'),
3294
Option('this' , 'Same as --mine-only.'),
3295
Option('theirs-only',
3296
'Display changes in the remote branch only.'),
3297
Option('other', 'Same as --theirs-only.'),
4851
Option('reverse', 'Reverse the order of revisions.'),
4853
'Display changes in the local branch only.'),
4854
Option('this' , 'Same as --mine-only.'),
4855
Option('theirs-only',
4856
'Display changes in the remote branch only.'),
4857
Option('other', 'Same as --theirs-only.'),
4861
custom_help('revision',
4862
help='Filter on other branch revisions (inclusive). '
4863
'See "help revisionspec" for details.'),
4864
Option('my-revision',
4865
type=_parse_revision_str,
4866
help='Filter on local branch revisions (inclusive). '
4867
'See "help revisionspec" for details.'),
4868
Option('include-merged',
4869
'Show all revisions in addition to the mainline ones.'),
4870
Option('include-merges', hidden=True,
4871
help='Historical alias for --include-merged.'),
3302
4873
encoding_type = 'replace'
3304
4875
@display_command
3305
4876
def run(self, other_branch=None, reverse=False, mine_only=False,
3306
theirs_only=False, log_format=None, long=False, short=False, line=False,
3307
show_ids=False, verbose=False, this=False, other=False):
4878
log_format=None, long=False, short=False, line=False,
4879
show_ids=False, verbose=False, this=False, other=False,
4880
include_merged=None, revision=None, my_revision=None,
4882
include_merges=symbol_versioning.DEPRECATED_PARAMETER):
3308
4883
from bzrlib.missing import find_unmerged, iter_log_revisions
4888
if symbol_versioning.deprecated_passed(include_merges):
4889
ui.ui_factory.show_user_warning(
4890
'deprecated_command_option',
4891
deprecated_name='--include-merges',
4892
recommended_name='--include-merged',
4893
deprecated_in_version='2.5',
4894
command=self.invoked_as)
4895
if include_merged is None:
4896
include_merged = include_merges
4898
raise errors.BzrCommandError(gettext(
4899
'{0} and {1} are mutually exclusive').format(
4900
'--include-merges', '--include-merged'))
4901
if include_merged is None:
4902
include_merged = False
3311
4904
mine_only = this
3320
4913
elif theirs_only:
3321
4914
restrict = 'remote'
3323
local_branch = Branch.open_containing(u".")[0]
4916
local_branch = Branch.open_containing(directory)[0]
4917
self.add_cleanup(local_branch.lock_read().unlock)
3324
4919
parent = local_branch.get_parent()
3325
4920
if other_branch is None:
3326
4921
other_branch = parent
3327
4922
if other_branch is None:
3328
raise errors.BzrCommandError("No peer location known"
4923
raise errors.BzrCommandError(gettext("No peer location known"
3330
4925
display_url = urlutils.unescape_for_display(parent,
3331
4926
self.outf.encoding)
3332
self.outf.write("Using last location: " + display_url + "\n")
4927
message(gettext("Using saved parent location: {0}\n").format(
3334
4930
remote_branch = Branch.open(other_branch)
3335
4931
if remote_branch.base == local_branch.base:
3336
4932
remote_branch = local_branch
3337
local_branch.lock_read()
3339
remote_branch.lock_read()
3341
local_extra, remote_extra = find_unmerged(
3342
local_branch, remote_branch, restrict)
3344
if log_format is None:
3345
registry = log.log_formatter_registry
3346
log_format = registry.get_default(local_branch)
3347
lf = log_format(to_file=self.outf,
3349
show_timezone='original')
3350
if reverse is False:
3351
if local_extra is not None:
3352
local_extra.reverse()
3353
if remote_extra is not None:
3354
remote_extra.reverse()
3357
if local_extra and not theirs_only:
3358
self.outf.write("You have %d extra revision(s):\n" %
3360
for revision in iter_log_revisions(local_extra,
3361
local_branch.repository,
3363
lf.log_revision(revision)
3364
printed_local = True
3367
printed_local = False
3369
if remote_extra and not mine_only:
3370
if printed_local is True:
3371
self.outf.write("\n\n\n")
3372
self.outf.write("You are missing %d revision(s):\n" %
3374
for revision in iter_log_revisions(remote_extra,
3375
remote_branch.repository,
3377
lf.log_revision(revision)
3380
if mine_only and not local_extra:
3381
# We checked local, and found nothing extra
3382
self.outf.write('This branch is up to date.\n')
3383
elif theirs_only and not remote_extra:
3384
# We checked remote, and found nothing extra
3385
self.outf.write('Other branch is up to date.\n')
3386
elif not (mine_only or theirs_only or local_extra or
3388
# We checked both branches, and neither one had extra
3390
self.outf.write("Branches are up to date.\n")
3392
remote_branch.unlock()
3394
local_branch.unlock()
4934
self.add_cleanup(remote_branch.lock_read().unlock)
4936
local_revid_range = _revision_range_to_revid_range(
4937
_get_revision_range(my_revision, local_branch,
4940
remote_revid_range = _revision_range_to_revid_range(
4941
_get_revision_range(revision,
4942
remote_branch, self.name()))
4944
local_extra, remote_extra = find_unmerged(
4945
local_branch, remote_branch, restrict,
4946
backward=not reverse,
4947
include_merged=include_merged,
4948
local_revid_range=local_revid_range,
4949
remote_revid_range=remote_revid_range)
4951
if log_format is None:
4952
registry = log.log_formatter_registry
4953
log_format = registry.get_default(local_branch)
4954
lf = log_format(to_file=self.outf,
4956
show_timezone='original')
4959
if local_extra and not theirs_only:
4960
message(ngettext("You have %d extra revision:\n",
4961
"You have %d extra revisions:\n",
4964
for revision in iter_log_revisions(local_extra,
4965
local_branch.repository,
4967
lf.log_revision(revision)
4968
printed_local = True
4971
printed_local = False
4973
if remote_extra and not mine_only:
4974
if printed_local is True:
4976
message(ngettext("You are missing %d revision:\n",
4977
"You are missing %d revisions:\n",
4978
len(remote_extra)) %
4980
for revision in iter_log_revisions(remote_extra,
4981
remote_branch.repository,
4983
lf.log_revision(revision)
4986
if mine_only and not local_extra:
4987
# We checked local, and found nothing extra
4988
message(gettext('This branch has no new revisions.\n'))
4989
elif theirs_only and not remote_extra:
4990
# We checked remote, and found nothing extra
4991
message(gettext('Other branch has no new revisions.\n'))
4992
elif not (mine_only or theirs_only or local_extra or
4994
# We checked both branches, and neither one had extra
4996
message(gettext("Branches are up to date.\n"))
3395
4998
if not status_code and parent is None and other_branch is not None:
3396
local_branch.lock_write()
3398
# handle race conditions - a parent might be set while we run.
3399
if local_branch.get_parent() is None:
3400
local_branch.set_parent(remote_branch.base)
3402
local_branch.unlock()
4999
self.add_cleanup(local_branch.lock_write().unlock)
5000
# handle race conditions - a parent might be set while we run.
5001
if local_branch.get_parent() is None:
5002
local_branch.set_parent(remote_branch.base)
3403
5003
return status_code
3406
5006
class cmd_pack(Command):
3407
"""Compress the data within a repository."""
5007
__doc__ = """Compress the data within a repository.
5009
This operation compresses the data within a bazaar repository. As
5010
bazaar supports automatic packing of repository, this operation is
5011
normally not required to be done manually.
5013
During the pack operation, bazaar takes a backup of existing repository
5014
data, i.e. pack files. This backup is eventually removed by bazaar
5015
automatically when it is safe to do so. To save disk space by removing
5016
the backed up pack files, the --clean-obsolete-packs option may be
5019
Warning: If you use --clean-obsolete-packs and your machine crashes
5020
during or immediately after repacking, you may be left with a state
5021
where the deletion has been written to disk but the new packs have not
5022
been. In this case the repository may be unusable.
3409
5025
_see_also = ['repositories']
3410
5026
takes_args = ['branch_or_repo?']
5028
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
3412
def run(self, branch_or_repo='.'):
3413
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
5031
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
5032
dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
3415
5034
branch = dir.open_branch()
3416
5035
repository = branch.repository
3417
5036
except errors.NotBranchError:
3418
5037
repository = dir.open_repository()
5038
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
3422
5041
class cmd_plugins(Command):
3423
"""List the installed plugins.
5042
__doc__ = """List the installed plugins.
3425
5044
This command displays the list of installed plugins including
3426
5045
version of plugin and a short description of each.
3513
5116
Option('long', help='Show commit date in annotations.'),
3517
5121
encoding_type = 'exact'
3519
5123
@display_command
3520
5124
def run(self, filename, all=False, long=False, revision=None,
3522
from bzrlib.annotate import annotate_file
5125
show_ids=False, directory=None):
5126
from bzrlib.annotate import (
3523
5129
wt, branch, relpath = \
3524
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
5130
_open_directory_or_containing_tree_or_branch(filename, directory)
3525
5131
if wt is not None:
3530
if revision is None:
3531
revision_id = branch.last_revision()
3532
elif len(revision) != 1:
3533
raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3535
revision_id = revision[0].as_revision_id(branch)
3536
tree = branch.repository.revision_tree(revision_id)
3538
file_id = wt.path2id(relpath)
3540
file_id = tree.path2id(relpath)
3542
raise errors.NotVersionedError(filename)
3543
file_version = tree.inventory[file_id].revision
3544
annotate_file(branch, file_version, file_id, long, all, self.outf,
5132
self.add_cleanup(wt.lock_read().unlock)
5134
self.add_cleanup(branch.lock_read().unlock)
5135
tree = _get_one_revision_tree('annotate', revision, branch=branch)
5136
self.add_cleanup(tree.lock_read().unlock)
5137
if wt is not None and revision is None:
5138
file_id = wt.path2id(relpath)
5140
file_id = tree.path2id(relpath)
5142
raise errors.NotVersionedError(filename)
5143
if wt is not None and revision is None:
5144
# If there is a tree and we're not annotating historical
5145
# versions, annotate the working tree's content.
5146
annotate_file_tree(wt, file_id, self.outf, long, all,
5149
annotate_file_tree(tree, file_id, self.outf, long, all,
5150
show_ids=show_ids, branch=branch)
3553
5153
class cmd_re_sign(Command):
3554
"""Create a digital signature for an existing revision."""
5154
__doc__ = """Create a digital signature for an existing revision."""
3555
5155
# TODO be able to replace existing ones.
3557
5157
hidden = True # is this right ?
3558
5158
takes_args = ['revision_id*']
3559
takes_options = ['revision']
3561
def run(self, revision_id_list=None, revision=None):
5159
takes_options = ['directory', 'revision']
5161
def run(self, revision_id_list=None, revision=None, directory=u'.'):
3562
5162
if revision_id_list is not None and revision is not None:
3563
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
5163
raise errors.BzrCommandError(gettext('You can only supply one of revision_id or --revision'))
3564
5164
if revision_id_list is None and revision is None:
3565
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3566
b = WorkingTree.open_containing(u'.')[0].branch
3569
return self._run(b, revision_id_list, revision)
5165
raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
5166
b = WorkingTree.open_containing(directory)[0].branch
5167
self.add_cleanup(b.lock_write().unlock)
5168
return self._run(b, revision_id_list, revision)
3573
5170
def _run(self, b, revision_id_list, revision):
3574
5171
import bzrlib.gpg as gpg
3575
gpg_strategy = gpg.GPGStrategy(b.get_config())
5172
gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
3576
5173
if revision_id_list is not None:
3577
5174
b.repository.start_write_group()
3816
5446
class cmd_serve(Command):
3817
"""Run the bzr server."""
5447
__doc__ = """Run the bzr server."""
3819
5449
aliases = ['server']
3821
5451
takes_options = [
3823
5453
help='Serve on stdin/out for use from inetd or sshd.'),
5454
RegistryOption('protocol',
5455
help="Protocol to serve.",
5456
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
5457
value_switches=True),
3825
5459
help='Listen for connections on nominated port of the form '
3826
5460
'[hostname:]portnumber. Passing 0 as the port number will '
3827
'result in a dynamically allocated port. The default port is '
5461
'result in a dynamically allocated port. The default port '
5462
'depends on the protocol.',
3831
help='Serve contents of this directory.',
5464
custom_help('directory',
5465
help='Serve contents of this directory.'),
3833
5466
Option('allow-writes',
3834
5467
help='By default the server is a readonly server. Supplying '
3835
5468
'--allow-writes enables write access to the contents of '
3836
'the served directory and below.'
5469
'the served directory and below. Note that ``bzr serve`` '
5470
'does not perform authentication, so unless some form of '
5471
'external authentication is arranged supplying this '
5472
'option leads to global uncontrolled write access to your '
5475
Option('client-timeout', type=float,
5476
help='Override the default idle client timeout (5min).'),
3840
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3841
from bzrlib import lockdir
3842
from bzrlib.smart import medium, server
3843
from bzrlib.transport import get_transport
3844
from bzrlib.transport.chroot import ChrootServer
5479
def get_host_and_port(self, port):
5480
"""Return the host and port to run the smart server on.
5482
If 'port' is None, None will be returned for the host and port.
5484
If 'port' has a colon in it, the string before the colon will be
5485
interpreted as the host.
5487
:param port: A string of the port to run the server on.
5488
:return: A tuple of (host, port), where 'host' is a host name or IP,
5489
and port is an integer TCP/IP port.
5492
if port is not None:
5494
host, port = port.split(':')
5498
def run(self, port=None, inet=False, directory=None, allow_writes=False,
5499
protocol=None, client_timeout=None):
5500
from bzrlib import transport
3845
5501
if directory is None:
3846
5502
directory = os.getcwd()
3847
url = urlutils.local_path_to_url(directory)
5503
if protocol is None:
5504
protocol = transport.transport_server_registry.get()
5505
host, port = self.get_host_and_port(port)
5506
url = transport.location_to_url(directory)
3848
5507
if not allow_writes:
3849
5508
url = 'readonly+' + url
3850
chroot_server = ChrootServer(get_transport(url))
3851
chroot_server.setUp()
3852
t = get_transport(chroot_server.get_url())
3854
smart_server = medium.SmartServerPipeStreamMedium(
3855
sys.stdin, sys.stdout, t)
3857
host = medium.BZR_DEFAULT_INTERFACE
3859
port = medium.BZR_DEFAULT_PORT
3862
host, port = port.split(':')
3864
smart_server = server.SmartTCPServer(t, host=host, port=port)
3865
print 'listening on port: ', smart_server.port
3867
# for the duration of this server, no UI output is permitted.
3868
# note that this may cause problems with blackbox tests. This should
3869
# be changed with care though, as we dont want to use bandwidth sending
3870
# progress over stderr to smart server clients!
3871
old_factory = ui.ui_factory
3872
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
5509
t = transport.get_transport_from_url(url)
3874
ui.ui_factory = ui.SilentUIFactory()
3875
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3876
smart_server.serve()
3878
ui.ui_factory = old_factory
3879
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
5511
protocol(t, host, port, inet, client_timeout)
5512
except TypeError, e:
5513
# We use symbol_versioning.deprecated_in just so that people
5514
# grepping can find it here.
5515
# symbol_versioning.deprecated_in((2, 5, 0))
5516
symbol_versioning.warn(
5517
'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5518
'Most likely it needs to be updated to support a'
5519
' "timeout" parameter (added in bzr 2.5.0)'
5520
% (e, protocol.__module__, protocol),
5522
protocol(t, host, port, inet)
3882
5525
class cmd_join(Command):
3883
"""Combine a subtree into its containing tree.
3885
This command is for experimental use only. It requires the target tree
3886
to be in dirstate-with-subtree format, which cannot be converted into
5526
__doc__ = """Combine a tree into its containing tree.
5528
This command requires the target tree to be in a rich-root format.
3889
5530
The TREE argument should be an independent tree, inside another tree, but
3890
5531
not part of it. (Such trees can be produced by "bzr split", but also by
3891
5532
running "bzr branch" with the target inside a tree.)
3893
The result is a combined tree, with the subtree no longer an independant
5534
The result is a combined tree, with the subtree no longer an independent
3894
5535
part. This is marked as a merge of the subtree into the containing tree,
3895
5536
and all history is preserved.
3897
If --reference is specified, the subtree retains its independence. It can
3898
be branched by itself, and can be part of multiple projects at the same
3899
time. But operations performed in the containing tree, such as commit
3900
and merge, will recurse into the subtree.
3903
5539
_see_also = ['split']
3904
5540
takes_args = ['tree']
3905
5541
takes_options = [
3906
Option('reference', help='Join by reference.'),
5542
Option('reference', help='Join by reference.', hidden=True),
3910
5545
def run(self, tree, reference=False):
3911
5546
sub_tree = WorkingTree.open(tree)
4127
5790
short_name='f',
4129
5792
Option('output', short_name='o',
4130
help='Write merge directive to this file; '
5793
help='Write merge directive to this file or directory; '
4131
5794
'use - for stdout.',
5797
help='Refuse to send if there are uncommitted changes in'
5798
' the working tree, --no-strict disables the check.'),
4133
5799
Option('mail-to', help='Mail the request to this address.',
4137
RegistryOption.from_kwargs('format',
4138
'Use the specified output format.',
4139
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4140
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5803
Option('body', help='Body for the email.', type=unicode),
5804
RegistryOption('format',
5805
help='Use the specified output format.',
5806
lazy_registry=('bzrlib.send', 'format_registry')),
4143
5809
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4144
no_patch=False, revision=None, remember=False, output=None,
4145
format='4', mail_to=None, message=None, **kwargs):
4146
return self._run(submit_branch, revision, public_branch, remember,
4147
format, no_bundle, no_patch, output,
4148
kwargs.get('from', '.'), mail_to, message)
4150
def _run(self, submit_branch, revision, public_branch, remember, format,
4151
no_bundle, no_patch, output, from_, mail_to, message):
4152
from bzrlib.revision import NULL_REVISION
4153
branch = Branch.open_containing(from_)[0]
4155
outfile = StringIO()
4159
outfile = open(output, 'wb')
4160
# we may need to write data into branch's repository to calculate
4165
config = branch.get_config()
4167
mail_to = config.get_user_option('submit_to')
4168
mail_client = config.get_mail_client()
4169
if remember and submit_branch is None:
4170
raise errors.BzrCommandError(
4171
'--remember requires a branch to be specified.')
4172
stored_submit_branch = branch.get_submit_branch()
4173
remembered_submit_branch = False
4174
if submit_branch is None:
4175
submit_branch = stored_submit_branch
4176
remembered_submit_branch = True
4178
if stored_submit_branch is None or remember:
4179
branch.set_submit_branch(submit_branch)
4180
if submit_branch is None:
4181
submit_branch = branch.get_parent()
4182
remembered_submit_branch = True
4183
if submit_branch is None:
4184
raise errors.BzrCommandError('No submit branch known or'
4186
if remembered_submit_branch:
4187
note('Using saved location: %s', submit_branch)
4190
submit_config = Branch.open(submit_branch).get_config()
4191
mail_to = submit_config.get_user_option("child_submit_to")
4193
stored_public_branch = branch.get_public_branch()
4194
if public_branch is None:
4195
public_branch = stored_public_branch
4196
elif stored_public_branch is None or remember:
4197
branch.set_public_branch(public_branch)
4198
if no_bundle and public_branch is None:
4199
raise errors.BzrCommandError('No public branch specified or'
4201
base_revision_id = None
4203
if revision is not None:
4204
if len(revision) > 2:
4205
raise errors.BzrCommandError('bzr send takes '
4206
'at most two one revision identifiers')
4207
revision_id = revision[-1].as_revision_id(branch)
4208
if len(revision) == 2:
4209
base_revision_id = revision[0].as_revision_id(branch)
4210
if revision_id is None:
4211
revision_id = branch.last_revision()
4212
if revision_id == NULL_REVISION:
4213
raise errors.BzrCommandError('No revisions to submit.')
4215
directive = merge_directive.MergeDirective2.from_objects(
4216
branch.repository, revision_id, time.time(),
4217
osutils.local_time_offset(), submit_branch,
4218
public_branch=public_branch, include_patch=not no_patch,
4219
include_bundle=not no_bundle, message=message,
4220
base_revision_id=base_revision_id)
4221
elif format == '0.9':
4224
patch_type = 'bundle'
4226
raise errors.BzrCommandError('Format 0.9 does not'
4227
' permit bundle with no patch')
4233
directive = merge_directive.MergeDirective.from_objects(
4234
branch.repository, revision_id, time.time(),
4235
osutils.local_time_offset(), submit_branch,
4236
public_branch=public_branch, patch_type=patch_type,
4239
outfile.writelines(directive.to_lines())
4241
subject = '[MERGE] '
4242
if message is not None:
4245
revision = branch.repository.get_revision(revision_id)
4246
subject += revision.get_summary()
4247
basename = directive.get_disk_name(branch)
4248
mail_client.compose_merge_request(mail_to, subject,
4249
outfile.getvalue(), basename)
5810
no_patch=False, revision=None, remember=None, output=None,
5811
format=None, mail_to=None, message=None, body=None,
5812
strict=None, **kwargs):
5813
from bzrlib.send import send
5814
return send(submit_branch, revision, public_branch, remember,
5815
format, no_bundle, no_patch, output,
5816
kwargs.get('from', '.'), mail_to, message, body,
4256
5821
class cmd_bundle_revisions(cmd_send):
4258
"""Create a merge-directive for submiting changes.
5822
__doc__ = """Create a merge-directive for submitting changes.
4260
5824
A merge directive provides many things needed for requesting merges:
4333
5901
Tags are stored in the branch. Tags are copied from one branch to another
4334
5902
along when you branch, push, pull or merge.
4336
It is an error to give a tag name that already exists unless you pass
5904
It is an error to give a tag name that already exists unless you pass
4337
5905
--force, in which case the tag is moved to point to the new revision.
5907
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5908
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5910
If no tag name is specified it will be determined through the
5911
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5912
upstream releases by reading configure.ac. See ``bzr help hooks`` for
4340
5916
_see_also = ['commit', 'tags']
4341
takes_args = ['tag_name']
5917
takes_args = ['tag_name?']
4342
5918
takes_options = [
4343
5919
Option('delete',
4344
5920
help='Delete this tag rather than placing it.',
4347
help='Branch in which to place the tag.',
5922
custom_help('directory',
5923
help='Branch in which to place the tag.'),
4351
5924
Option('force',
4352
5925
help='Replace existing tags.',
4357
def run(self, tag_name,
5930
def run(self, tag_name=None,
4363
5936
branch, relpath = Branch.open_containing(directory)
4367
branch.tags.delete_tag(tag_name)
4368
self.outf.write('Deleted tag %s.\n' % tag_name)
4371
if len(revision) != 1:
4372
raise errors.BzrCommandError(
4373
"Tags can only be placed on a single revision, "
4375
revision_id = revision[0].as_revision_id(branch)
4377
revision_id = branch.last_revision()
4378
if (not force) and branch.tags.has_tag(tag_name):
4379
raise errors.TagAlreadyExists(tag_name)
5937
self.add_cleanup(branch.lock_write().unlock)
5939
if tag_name is None:
5940
raise errors.BzrCommandError(gettext("No tag specified to delete."))
5941
branch.tags.delete_tag(tag_name)
5942
note(gettext('Deleted tag %s.') % tag_name)
5945
if len(revision) != 1:
5946
raise errors.BzrCommandError(gettext(
5947
"Tags can only be placed on a single revision, "
5949
revision_id = revision[0].as_revision_id(branch)
5951
revision_id = branch.last_revision()
5952
if tag_name is None:
5953
tag_name = branch.automatic_tag_name(revision_id)
5954
if tag_name is None:
5955
raise errors.BzrCommandError(gettext(
5956
"Please specify a tag name."))
5958
existing_target = branch.tags.lookup_tag(tag_name)
5959
except errors.NoSuchTag:
5960
existing_target = None
5961
if not force and existing_target not in (None, revision_id):
5962
raise errors.TagAlreadyExists(tag_name)
5963
if existing_target == revision_id:
5964
note(gettext('Tag %s already exists for that revision.') % tag_name)
4380
5966
branch.tags.set_tag(tag_name, revision_id)
4381
self.outf.write('Created tag %s.\n' % tag_name)
5967
if existing_target is None:
5968
note(gettext('Created tag %s.') % tag_name)
5970
note(gettext('Updated tag %s.') % tag_name)
4386
5973
class cmd_tags(Command):
5974
__doc__ = """List tags.
4389
5976
This command shows a table of tag names and the revisions they reference.
4392
5979
_see_also = ['tag']
4393
5980
takes_options = [
4395
help='Branch whose tags should be displayed.',
4399
RegistryOption.from_kwargs('sort',
5981
custom_help('directory',
5982
help='Branch whose tags should be displayed.'),
5983
RegistryOption('sort',
4400
5984
'Sort tags by different criteria.', title='Sorting',
4401
alpha='Sort tags lexicographically (default).',
4402
time='Sort tags chronologically.',
5985
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
4407
5991
@display_command
5992
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5993
from bzrlib.tag import tag_sort_methods
4413
5994
branch, relpath = Branch.open_containing(directory)
4414
5996
tags = branch.tags.get_tag_dict().items()
4417
elif sort == 'time':
4419
for tag, revid in tags:
4421
revobj = branch.repository.get_revision(revid)
4422
except errors.NoSuchRevision:
4423
timestamp = sys.maxint # place them at the end
4425
timestamp = revobj.timestamp
4426
timestamps[revid] = timestamp
4427
tags.sort(key=lambda x: timestamps[x[1]])
6000
self.add_cleanup(branch.lock_read().unlock)
6002
# Restrict to the specified range
6003
tags = self._tags_for_range(branch, revision)
6005
sort = tag_sort_methods.get()
4428
6007
if not show_ids:
4429
6008
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4430
revno_map = branch.get_revision_id_to_revno_map()
4431
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4432
for tag, revid in tags ]
6009
for index, (tag, revid) in enumerate(tags):
6011
revno = branch.revision_id_to_dotted_revno(revid)
6012
if isinstance(revno, tuple):
6013
revno = '.'.join(map(str, revno))
6014
except (errors.NoSuchRevision,
6015
errors.GhostRevisionsHaveNoRevno,
6016
errors.UnsupportedOperation):
6017
# Bad tag data/merges can lead to tagged revisions
6018
# which are not in this branch. Fail gracefully ...
6020
tags[index] = (tag, revno)
4433
6022
for tag, revspec in tags:
4434
6023
self.outf.write('%-20s %s\n' % (tag, revspec))
6025
def _tags_for_range(self, branch, revision):
6027
rev1, rev2 = _get_revision_range(revision, branch, self.name())
6028
revid1, revid2 = rev1.rev_id, rev2.rev_id
6029
# _get_revision_range will always set revid2 if it's not specified.
6030
# If revid1 is None, it means we want to start from the branch
6031
# origin which is always a valid ancestor. If revid1 == revid2, the
6032
# ancestry check is useless.
6033
if revid1 and revid1 != revid2:
6034
# FIXME: We really want to use the same graph than
6035
# branch.iter_merge_sorted_revisions below, but this is not
6036
# easily available -- vila 2011-09-23
6037
if branch.repository.get_graph().is_ancestor(revid2, revid1):
6038
# We don't want to output anything in this case...
6040
# only show revisions between revid1 and revid2 (inclusive)
6041
tagged_revids = branch.tags.get_reverse_tag_dict()
6043
for r in branch.iter_merge_sorted_revisions(
6044
start_revision_id=revid2, stop_revision_id=revid1,
6045
stop_rule='include'):
6046
revid_tags = tagged_revids.get(r[0], None)
6048
found.extend([(tag, r[0]) for tag in revid_tags])
4437
6052
class cmd_reconfigure(Command):
4438
"""Reconfigure the type of a bzr directory.
6053
__doc__ = """Reconfigure the type of a bzr directory.
4440
6055
A target configuration must be specified.
4448
6063
If none of these is available, --bind-to must be specified.
6066
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4451
6067
takes_args = ['location?']
4452
takes_options = [RegistryOption.from_kwargs('target_type',
4453
title='Target type',
4454
help='The type to reconfigure the directory to.',
4455
value_switches=True, enum_switch=False,
4456
branch='Reconfigure to a branch.',
4457
tree='Reconfigure to a tree.',
4458
checkout='Reconfigure to a checkout.',
4459
lightweight_checkout='Reconfigure to a lightweight'
4461
standalone='Reconfigure to be standalone.',
4462
use_shared='Reconfigure to use a shared repository.'),
4463
Option('bind-to', help='Branch to bind checkout to.',
4466
help='Perform reconfiguration even if local changes'
6069
RegistryOption.from_kwargs(
6072
help='The relation between branch and tree.',
6073
value_switches=True, enum_switch=False,
6074
branch='Reconfigure to be an unbound branch with no working tree.',
6075
tree='Reconfigure to be an unbound branch with a working tree.',
6076
checkout='Reconfigure to be a bound branch with a working tree.',
6077
lightweight_checkout='Reconfigure to be a lightweight'
6078
' checkout (with no local history).',
6080
RegistryOption.from_kwargs(
6082
title='Repository type',
6083
help='Location fo the repository.',
6084
value_switches=True, enum_switch=False,
6085
standalone='Reconfigure to be a standalone branch '
6086
'(i.e. stop using shared repository).',
6087
use_shared='Reconfigure to use a shared repository.',
6089
RegistryOption.from_kwargs(
6091
title='Trees in Repository',
6092
help='Whether new branches in the repository have trees.',
6093
value_switches=True, enum_switch=False,
6094
with_trees='Reconfigure repository to create '
6095
'working trees on branches by default.',
6096
with_no_trees='Reconfigure repository to not create '
6097
'working trees on branches by default.'
6099
Option('bind-to', help='Branch to bind checkout to.', type=str),
6101
help='Perform reconfiguration even if local changes'
6103
Option('stacked-on',
6104
help='Reconfigure a branch to be stacked on another branch.',
6108
help='Reconfigure a branch to be unstacked. This '
6109
'may require copying substantial data into it.',
4470
def run(self, location=None, target_type=None, bind_to=None, force=False):
4471
directory = bzrdir.BzrDir.open(location)
4472
if target_type is None:
4473
raise errors.BzrCommandError('No target configuration specified')
4474
elif target_type == 'branch':
6113
def run(self, location=None, bind_to=None, force=False,
6114
tree_type=None, repository_type=None, repository_trees=None,
6115
stacked_on=None, unstacked=None):
6116
directory = controldir.ControlDir.open(location)
6117
if stacked_on and unstacked:
6118
raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
6119
elif stacked_on is not None:
6120
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
6122
reconfigure.ReconfigureUnstacked().apply(directory)
6123
# At the moment you can use --stacked-on and a different
6124
# reconfiguration shape at the same time; there seems no good reason
6126
if (tree_type is None and
6127
repository_type is None and
6128
repository_trees is None):
6129
if stacked_on or unstacked:
6132
raise errors.BzrCommandError(gettext('No target configuration '
6134
reconfiguration = None
6135
if tree_type == 'branch':
4475
6136
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4476
elif target_type == 'tree':
6137
elif tree_type == 'tree':
4477
6138
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4478
elif target_type == 'checkout':
4479
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4481
elif target_type == 'lightweight-checkout':
6139
elif tree_type == 'checkout':
6140
reconfiguration = reconfigure.Reconfigure.to_checkout(
6142
elif tree_type == 'lightweight-checkout':
4482
6143
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4483
6144
directory, bind_to)
4484
elif target_type == 'use-shared':
6146
reconfiguration.apply(force)
6147
reconfiguration = None
6148
if repository_type == 'use-shared':
4485
6149
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
4486
elif target_type == 'standalone':
6150
elif repository_type == 'standalone':
4487
6151
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4488
reconfiguration.apply(force)
6153
reconfiguration.apply(force)
6154
reconfiguration = None
6155
if repository_trees == 'with-trees':
6156
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6158
elif repository_trees == 'with-no-trees':
6159
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6162
reconfiguration.apply(force)
6163
reconfiguration = None
4491
6166
class cmd_switch(Command):
4492
"""Set the branch of a checkout and update.
6167
__doc__ = """Set the branch of a checkout and update.
4494
6169
For lightweight checkouts, this changes the branch being referenced.
4495
6170
For heavyweight checkouts, this checks that there are no local commits
4496
6171
versus the current bound branch, then it makes the local branch a mirror
4497
6172
of the new location and binds to it.
4499
6174
In both cases, the working tree is updated and uncommitted changes
4500
6175
are merged. The user can commit or revert these as they desire.
4505
6180
directory of the current branch. For example, if you are currently in a
4506
6181
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4507
6182
/path/to/newbranch.
6184
Bound branches use the nickname of its master branch unless it is set
6185
locally, in which case switching will update the local nickname to be
4510
takes_args = ['to_location']
4511
takes_options = [Option('force',
4512
help='Switch even if local commits will be lost.')
6189
takes_args = ['to_location?']
6190
takes_options = ['directory',
6192
help='Switch even if local commits will be lost.'),
6194
Option('create-branch', short_name='b',
6195
help='Create the target branch from this one before'
6196
' switching to it.'),
4515
def run(self, to_location, force=False):
6199
def run(self, to_location=None, force=False, create_branch=False,
6200
revision=None, directory=u'.'):
4516
6201
from bzrlib import switch
4518
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
6202
tree_location = directory
6203
revision = _get_one_revision('switch', revision)
6204
control_dir = controldir.ControlDir.open_containing(tree_location)[0]
6205
if to_location is None:
6206
if revision is None:
6207
raise errors.BzrCommandError(gettext('You must supply either a'
6208
' revision or a location'))
6209
to_location = tree_location
4520
to_branch = Branch.open(to_location)
6211
branch = control_dir.open_branch()
6212
had_explicit_nick = branch.get_config().has_explicit_nickname()
4521
6213
except errors.NotBranchError:
4522
to_branch = Branch.open(
4523
control_dir.open_branch().base + '../' + to_location)
4524
switch.switch(control_dir, to_branch, force)
4525
note('Switched to branch: %s',
6215
had_explicit_nick = False
6218
raise errors.BzrCommandError(
6219
gettext('cannot create branch without source branch'))
6220
to_location = lookup_new_sibling_branch(control_dir, to_location)
6221
to_branch = branch.bzrdir.sprout(to_location,
6222
possible_transports=[branch.bzrdir.root_transport],
6223
source_branch=branch).open_branch()
6225
to_branch = lookup_sibling_branch(control_dir, to_location)
6226
if revision is not None:
6227
revision = revision.as_revision_id(to_branch)
6228
switch.switch(control_dir, to_branch, force, revision_id=revision)
6229
if had_explicit_nick:
6230
branch = control_dir.open_branch() #get the new branch!
6231
branch.nick = to_branch.nick
6232
note(gettext('Switched to branch: %s'),
4526
6233
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6237
class cmd_view(Command):
6238
__doc__ = """Manage filtered views.
6240
Views provide a mask over the tree so that users can focus on
6241
a subset of a tree when doing their work. After creating a view,
6242
commands that support a list of files - status, diff, commit, etc -
6243
effectively have that list of files implicitly given each time.
6244
An explicit list of files can still be given but those files
6245
must be within the current view.
6247
In most cases, a view has a short life-span: it is created to make
6248
a selected change and is deleted once that change is committed.
6249
At other times, you may wish to create one or more named views
6250
and switch between them.
6252
To disable the current view without deleting it, you can switch to
6253
the pseudo view called ``off``. This can be useful when you need
6254
to see the whole tree for an operation or two (e.g. merge) but
6255
want to switch back to your view after that.
6258
To define the current view::
6260
bzr view file1 dir1 ...
6262
To list the current view::
6266
To delete the current view::
6270
To disable the current view without deleting it::
6272
bzr view --switch off
6274
To define a named view and switch to it::
6276
bzr view --name view-name file1 dir1 ...
6278
To list a named view::
6280
bzr view --name view-name
6282
To delete a named view::
6284
bzr view --name view-name --delete
6286
To switch to a named view::
6288
bzr view --switch view-name
6290
To list all views defined::
6294
To delete all views::
6296
bzr view --delete --all
6300
takes_args = ['file*']
6303
help='Apply list or delete action to all views.',
6306
help='Delete the view.',
6309
help='Name of the view to define, list or delete.',
6313
help='Name of the view to switch to.',
6318
def run(self, file_list,
6324
tree, file_list = WorkingTree.open_containing_paths(file_list,
6326
current_view, view_dict = tree.views.get_view_info()
6331
raise errors.BzrCommandError(gettext(
6332
"Both --delete and a file list specified"))
6334
raise errors.BzrCommandError(gettext(
6335
"Both --delete and --switch specified"))
6337
tree.views.set_view_info(None, {})
6338
self.outf.write(gettext("Deleted all views.\n"))
6340
raise errors.BzrCommandError(gettext("No current view to delete"))
6342
tree.views.delete_view(name)
6343
self.outf.write(gettext("Deleted '%s' view.\n") % name)
6346
raise errors.BzrCommandError(gettext(
6347
"Both --switch and a file list specified"))
6349
raise errors.BzrCommandError(gettext(
6350
"Both --switch and --all specified"))
6351
elif switch == 'off':
6352
if current_view is None:
6353
raise errors.BzrCommandError(gettext("No current view to disable"))
6354
tree.views.set_view_info(None, view_dict)
6355
self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
6357
tree.views.set_view_info(switch, view_dict)
6358
view_str = views.view_display_str(tree.views.lookup_view())
6359
self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
6362
self.outf.write(gettext('Views defined:\n'))
6363
for view in sorted(view_dict):
6364
if view == current_view:
6368
view_str = views.view_display_str(view_dict[view])
6369
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6371
self.outf.write(gettext('No views defined.\n'))
6374
# No name given and no current view set
6377
raise errors.BzrCommandError(gettext(
6378
"Cannot change the 'off' pseudo view"))
6379
tree.views.set_view(name, sorted(file_list))
6380
view_str = views.view_display_str(tree.views.lookup_view())
6381
self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
6385
# No name given and no current view set
6386
self.outf.write(gettext('No current view.\n'))
6388
view_str = views.view_display_str(tree.views.lookup_view(name))
6389
self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
4529
6392
class cmd_hooks(Command):
4530
"""Show a branch's currently registered hooks.
4534
takes_args = ['path?']
4536
def run(self, path=None):
6393
__doc__ = """Show hooks."""
6398
for hook_key in sorted(hooks.known_hooks.keys()):
6399
some_hooks = hooks.known_hooks_key_to_object(hook_key)
6400
self.outf.write("%s:\n" % type(some_hooks).__name__)
6401
for hook_name, hook_point in sorted(some_hooks.items()):
6402
self.outf.write(" %s:\n" % (hook_name,))
6403
found_hooks = list(hook_point)
6405
for hook in found_hooks:
6406
self.outf.write(" %s\n" %
6407
(some_hooks.get_hook_name(hook),))
6409
self.outf.write(gettext(" <no hooks installed>\n"))
6412
class cmd_remove_branch(Command):
6413
__doc__ = """Remove a branch.
6415
This will remove the branch from the specified location but
6416
will keep any working tree or repository in place.
6420
Remove the branch at repo/trunk::
6422
bzr remove-branch repo/trunk
6426
takes_args = ["location?"]
6428
aliases = ["rmbranch"]
6430
def run(self, location=None):
6431
if location is None:
6433
branch = Branch.open_containing(location)[0]
6434
branch.bzrdir.destroy_branch()
6437
class cmd_shelve(Command):
6438
__doc__ = """Temporarily set aside some changes from the current tree.
6440
Shelve allows you to temporarily put changes you've made "on the shelf",
6441
ie. out of the way, until a later time when you can bring them back from
6442
the shelf with the 'unshelve' command. The changes are stored alongside
6443
your working tree, and so they aren't propagated along with your branch nor
6444
will they survive its deletion.
6446
If shelve --list is specified, previously-shelved changes are listed.
6448
Shelve is intended to help separate several sets of changes that have
6449
been inappropriately mingled. If you just want to get rid of all changes
6450
and you don't need to restore them later, use revert. If you want to
6451
shelve all text changes at once, use shelve --all.
6453
If filenames are specified, only the changes to those files will be
6454
shelved. Other files will be left untouched.
6456
If a revision is specified, changes since that revision will be shelved.
6458
You can put multiple items on the shelf, and by default, 'unshelve' will
6459
restore the most recently shelved changes.
6461
For complicated changes, it is possible to edit the changes in a separate
6462
editor program to decide what the file remaining in the working copy
6463
should look like. To do this, add the configuration option
6465
change_editor = PROGRAM @new_path @old_path
6467
where @new_path is replaced with the path of the new version of the
6468
file and @old_path is replaced with the path of the old version of
6469
the file. The PROGRAM should save the new file with the desired
6470
contents of the file in the working tree.
6474
takes_args = ['file*']
6479
Option('all', help='Shelve all changes.'),
6481
RegistryOption('writer', 'Method to use for writing diffs.',
6482
bzrlib.option.diff_writer_registry,
6483
value_switches=True, enum_switch=False),
6485
Option('list', help='List shelved changes.'),
6487
help='Destroy removed changes instead of shelving them.'),
6489
_see_also = ['unshelve', 'configuration']
6491
def run(self, revision=None, all=False, file_list=None, message=None,
6492
writer=None, list=False, destroy=False, directory=None):
6494
return self.run_for_list(directory=directory)
6495
from bzrlib.shelf_ui import Shelver
6497
writer = bzrlib.option.diff_writer_registry.get()
6499
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6500
file_list, message, destroy=destroy, directory=directory)
6505
except errors.UserAbort:
6508
def run_for_list(self, directory=None):
6509
if directory is None:
6511
tree = WorkingTree.open_containing(directory)[0]
6512
self.add_cleanup(tree.lock_read().unlock)
6513
manager = tree.get_shelf_manager()
6514
shelves = manager.active_shelves()
6515
if len(shelves) == 0:
6516
note(gettext('No shelved changes.'))
6518
for shelf_id in reversed(shelves):
6519
message = manager.get_metadata(shelf_id).get('message')
6521
message = '<no message>'
6522
self.outf.write('%3d: %s\n' % (shelf_id, message))
6526
class cmd_unshelve(Command):
6527
__doc__ = """Restore shelved changes.
6529
By default, the most recently shelved changes are restored. However if you
6530
specify a shelf by id those changes will be restored instead. This works
6531
best when the changes don't depend on each other.
6534
takes_args = ['shelf_id?']
6537
RegistryOption.from_kwargs(
6538
'action', help="The action to perform.",
6539
enum_switch=False, value_switches=True,
6540
apply="Apply changes and remove from the shelf.",
6541
dry_run="Show changes, but do not apply or remove them.",
6542
preview="Instead of unshelving the changes, show the diff that "
6543
"would result from unshelving.",
6544
delete_only="Delete changes without applying them.",
6545
keep="Apply changes but don't delete them.",
6548
_see_also = ['shelve']
6550
def run(self, shelf_id=None, action='apply', directory=u'.'):
6551
from bzrlib.shelf_ui import Unshelver
6552
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6556
unshelver.tree.unlock()
6559
class cmd_clean_tree(Command):
6560
__doc__ = """Remove unwanted files from working tree.
6562
By default, only unknown files, not ignored files, are deleted. Versioned
6563
files are never deleted.
6565
Another class is 'detritus', which includes files emitted by bzr during
6566
normal operations and selftests. (The value of these files decreases with
6569
If no options are specified, unknown files are deleted. Otherwise, option
6570
flags are respected, and may be combined.
6572
To check what clean-tree will do, use --dry-run.
6574
takes_options = ['directory',
6575
Option('ignored', help='Delete all ignored files.'),
6576
Option('detritus', help='Delete conflict files, merge and revert'
6577
' backups, and failed selftest dirs.'),
6579
help='Delete files unknown to bzr (default).'),
6580
Option('dry-run', help='Show files to delete instead of'
6582
Option('force', help='Do not prompt before deleting.')]
6583
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6584
force=False, directory=u'.'):
6585
from bzrlib.clean_tree import clean_tree
6586
if not (unknown or ignored or detritus):
6590
clean_tree(directory, unknown=unknown, ignored=ignored,
6591
detritus=detritus, dry_run=dry_run, no_prompt=force)
6594
class cmd_reference(Command):
6595
__doc__ = """list, view and set branch locations for nested trees.
6597
If no arguments are provided, lists the branch locations for nested trees.
6598
If one argument is provided, display the branch location for that tree.
6599
If two arguments are provided, set the branch location for that tree.
6604
takes_args = ['path?', 'location?']
6606
def run(self, path=None, location=None):
6608
if path is not None:
6610
tree, branch, relpath =(
6611
controldir.ControlDir.open_containing_tree_or_branch(branchdir))
6612
if path is not None:
6615
tree = branch.basis_tree()
4537
6616
if path is None:
4539
branch_hooks = Branch.open(path).hooks
4540
for hook_type in branch_hooks:
4541
hooks = branch_hooks[hook_type]
4542
self.outf.write("%s:\n" % (hook_type,))
4545
self.outf.write(" %s\n" %
4546
(branch_hooks.get_hook_name(hook),))
6617
info = branch._get_all_reference_info().iteritems()
6618
self._display_reference_info(tree, branch, info)
6620
file_id = tree.path2id(path)
6622
raise errors.NotVersionedError(path)
6623
if location is None:
6624
info = [(file_id, branch.get_reference_info(file_id))]
6625
self._display_reference_info(tree, branch, info)
4548
self.outf.write(" <no hooks installed>\n")
4551
def _create_prefix(cur_transport):
4552
needed = [cur_transport]
4553
# Recurse upwards until we can create a directory successfully
4555
new_transport = cur_transport.clone('..')
4556
if new_transport.base == cur_transport.base:
4557
raise errors.BzrCommandError(
4558
"Failed to create path prefix for %s."
4559
% cur_transport.base)
4561
new_transport.mkdir('.')
4562
except errors.NoSuchFile:
4563
needed.append(new_transport)
4564
cur_transport = new_transport
4567
# Now we only need to create child directories
4569
cur_transport = needed.pop()
4570
cur_transport.ensure_base()
4573
# these get imported and then picked up by the scan for cmd_*
4574
# TODO: Some more consistent way to split command definitions across files;
4575
# we do need to load at least some information about them to know of
4576
# aliases. ideally we would avoid loading the implementation until the
4577
# details were needed.
4578
from bzrlib.cmd_version_info import cmd_version_info
4579
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4580
from bzrlib.bundle.commands import (
4583
from bzrlib.sign_my_commits import cmd_sign_my_commits
4584
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4585
cmd_weave_plan_merge, cmd_weave_merge_text
6627
branch.set_reference_info(file_id, path, location)
6629
def _display_reference_info(self, tree, branch, info):
6631
for file_id, (path, location) in info:
6633
path = tree.id2path(file_id)
6634
except errors.NoSuchId:
6636
ref_list.append((path, location))
6637
for path, location in sorted(ref_list):
6638
self.outf.write('%s %s\n' % (path, location))
6641
class cmd_export_pot(Command):
6642
__doc__ = """Export command helps and error messages in po format."""
6645
takes_options = [Option('plugin',
6646
help='Export help text from named command '\
6647
'(defaults to all built in commands).',
6649
Option('include-duplicates',
6650
help='Output multiple copies of the same msgid '
6651
'string if it appears more than once.'),
6654
def run(self, plugin=None, include_duplicates=False):
6655
from bzrlib.export_pot import export_pot
6656
export_pot(self.outf, plugin, include_duplicates)
6659
def _register_lazy_builtins():
6660
# register lazy builtins from other modules; called at startup and should
6661
# be only called once.
6662
for (name, aliases, module_name) in [
6663
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6664
('cmd_config', [], 'bzrlib.config'),
6665
('cmd_dpush', [], 'bzrlib.foreign'),
6666
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6667
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6668
('cmd_conflicts', [], 'bzrlib.conflicts'),
6669
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6670
('cmd_verify_signatures', [],
6671
'bzrlib.commit_signature_commands'),
6672
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6674
builtin_command_registry.register_lazy(name, aliases, module_name)