13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
17
"""builtin bzr commands"""
20
from StringIO import StringIO
21
22
from bzrlib.lazy_import import lazy_import
22
23
lazy_import(globals(), """
28
31
from bzrlib import (
35
config as _mod_config,
40
42
merge as _mod_merge,
45
47
revision as _mod_revision,
54
55
from bzrlib.branch import Branch
55
56
from bzrlib.conflicts import ConflictList
56
from bzrlib.transport import memory
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
57
from bzrlib.revisionspec import RevisionSpec
58
58
from bzrlib.smtp_connection import SMTPConnection
59
59
from bzrlib.workingtree import WorkingTree
60
from bzrlib.i18n import gettext, ngettext
63
from bzrlib.commands import (
65
builtin_command_registry,
68
from bzrlib.option import (
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
81
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
82
def tree_files(file_list, default_branch=u'.', canonicalize=True,
84
return internal_tree_files(file_list, default_branch, canonicalize,
88
def tree_files_for_add(file_list):
90
Return a tree and list of absolute paths from a file list.
92
Similar to tree_files, but add handles files a bit differently, so it a
93
custom implementation. In particular, MutableTreeTree.smart_add expects
94
absolute paths, which it immediately converts to relative paths.
96
# FIXME Would be nice to just return the relative paths like
97
# internal_tree_files does, but there are a large number of unit tests
98
# that assume the current interface to mutabletree.smart_add
100
tree, relpath = WorkingTree.open_containing(file_list[0])
101
if tree.supports_views():
102
view_files = tree.views.lookup_view()
104
for filename in file_list:
105
if not osutils.is_inside_any(view_files, filename):
106
raise errors.FileOutsideView(filename, view_files)
107
file_list = file_list[:]
108
file_list[0] = tree.abspath(relpath)
110
tree = WorkingTree.open_containing(u'.')[0]
111
if tree.supports_views():
112
view_files = tree.views.lookup_view()
114
file_list = view_files
115
view_str = views.view_display_str(view_files)
116
note(gettext("Ignoring files outside view. View is %s") % view_str)
117
return tree, file_list
120
def _get_one_revision(command_name, revisions):
121
if revisions is None:
123
if len(revisions) != 1:
124
raise errors.BzrCommandError(gettext(
125
'bzr %s --revision takes exactly one revision identifier') % (
130
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
131
"""Get a revision tree. Not suitable for commands that change the tree.
133
Specifically, the basis tree in dirstate trees is coupled to the dirstate
134
and doing a commit/uncommit/pull will at best fail due to changing the
137
If tree is passed in, it should be already locked, for lifetime management
138
of the trees internal cached state.
142
if revisions is None:
144
rev_tree = tree.basis_tree()
146
rev_tree = branch.basis_tree()
148
revision = _get_one_revision(command_name, revisions)
149
rev_tree = revision.as_tree(branch)
62
from bzrlib.commands import Command, display_command
63
from bzrlib.option import ListOption, Option, RegistryOption
64
from bzrlib.progress import DummyProgress, ProgressPhase
65
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
68
def tree_files(file_list, default_branch=u'.'):
70
return internal_tree_files(file_list, default_branch)
71
except errors.FileInWrongBranch, e:
72
raise errors.BzrCommandError("%s is not in the same branch as %s" %
73
(e.path, file_list[0]))
153
76
# XXX: Bad function name; should possibly also be a class method of
154
77
# WorkingTree rather than a function.
155
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
156
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
78
def internal_tree_files(file_list, default_branch=u'.'):
158
79
"""Convert command-line paths to a WorkingTree and relative paths.
160
Deprecated: use WorkingTree.open_containing_paths instead.
162
81
This is typically used for command-line processors that take one or
163
82
more filenames, and infer the workingtree that contains them.
165
84
The filenames given are not required to exist.
167
:param file_list: Filenames to convert.
86
:param file_list: Filenames to convert.
169
88
:param default_branch: Fallback tree path to use if file_list is empty or
172
:param apply_view: if True and a view is set, apply it or check that
173
specified files are within it
175
91
:return: workingtree, [relative_paths]
177
return WorkingTree.open_containing_paths(
178
file_list, default_directory='.',
183
def _get_view_info_for_change_reporter(tree):
184
"""Get the view information from a tree for change reporting."""
93
if file_list is None or len(file_list) == 0:
94
return WorkingTree.open_containing(default_branch)[0], file_list
95
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
97
for filename in file_list:
99
new_list.append(tree.relpath(osutils.dereference_path(filename)))
100
except errors.PathNotChild:
101
raise errors.FileInWrongBranch(tree.branch, filename)
102
return tree, new_list
105
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
106
def get_format_type(typestring):
107
"""Parse and return a format specifier."""
108
# Have to use BzrDirMetaFormat1 directly, so that
109
# RepositoryFormat.set_default_format works
110
if typestring == "default":
111
return bzrdir.BzrDirMetaFormat1()
187
current_view = tree.views.get_view_info()[0]
188
if current_view is not None:
189
view_info = (current_view, tree.views.lookup_view())
190
except errors.ViewsNotSupported:
195
def _open_directory_or_containing_tree_or_branch(filename, directory):
196
"""Open the tree or branch containing the specified file, unless
197
the --directory option is used to specify a different branch."""
198
if directory is not None:
199
return (None, Branch.open(directory), filename)
200
return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
113
return bzrdir.format_registry.make_bzrdir(typestring)
115
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
116
raise errors.BzrCommandError(msg)
203
119
# TODO: Make sure no commands unconditionally use the working directory as a
234
150
Not versioned and not matching an ignore pattern.
236
Additionally for directories, symlinks and files with a changed
237
executable bit, Bazaar indicates their type using a trailing
238
character: '/', '@' or '*' respectively. These decorations can be
239
disabled using the '--no-classify' option.
241
152
To see ignored files use 'bzr ignored'. For details on the
242
153
changes to file texts, use 'bzr diff'.
244
Note that --short or -S gives status flags for each item, similar
245
to Subversion's status command. To get output similar to svn -q,
155
--short gives a status flags for each item, similar to the SVN's status
248
158
If no arguments are specified, the status of the entire working
249
159
directory is shown. Otherwise, only the status of the specified
250
160
files or directories is reported. If a directory is given, status
251
161
is reported for everything inside that directory.
253
Before merges are committed, the pending merge tip revisions are
254
shown. To see all pending merge revisions, use the -v option.
255
To skip the display of pending merge information altogether, use
256
the no-pending option or specify a file/directory.
258
To compare the working directory to a specific revision, pass a
259
single revision to the revision argument.
261
To see which files have changed in a specific revision, or between
262
two revisions, pass a revision range to the revision argument.
263
This will produce the same results as calling 'bzr diff --summarize'.
163
If a revision argument is given, the status is calculated against
164
that revision, or between two revisions if two are provided.
266
167
# TODO: --no-recurse, --recurse options
268
169
takes_args = ['file*']
269
takes_options = ['show-ids', 'revision', 'change', 'verbose',
270
Option('short', help='Use short status indicators.',
272
Option('versioned', help='Only show versioned files.',
274
Option('no-pending', help='Don\'t show pending merges.',
276
Option('no-classify',
277
help='Do not mark object type using indicator.',
170
takes_options = ['show-ids', 'revision',
171
Option('short', help='Give short SVN-style status lines.'),
172
Option('versioned', help='Only show versioned files.')]
280
173
aliases = ['st', 'stat']
282
175
encoding_type = 'replace'
283
176
_see_also = ['diff', 'revert', 'status-flags']
286
179
def run(self, show_ids=False, file_list=None, revision=None, short=False,
287
versioned=False, no_pending=False, verbose=False,
289
181
from bzrlib.status import show_tree_status
291
if revision and len(revision) > 2:
292
raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
293
' one or two revision specifiers'))
295
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
296
# Avoid asking for specific files when that is not needed.
297
if relfile_list == ['']:
299
# Don't disable pending merges for full trees other than '.'.
300
if file_list == ['.']:
302
# A specific path within a tree was given.
303
elif relfile_list is not None:
183
tree, file_list = tree_files(file_list)
305
185
show_tree_status(tree, show_ids=show_ids,
306
specific_files=relfile_list, revision=revision,
307
to_file=self.outf, short=short, versioned=versioned,
308
show_pending=(not no_pending), verbose=verbose,
309
classify=not no_classify)
186
specific_files=file_list, revision=revision,
187
to_file=self.outf, short=short, versioned=versioned)
312
190
class cmd_cat_revision(Command):
313
__doc__ = """Write out metadata for a revision.
191
"""Write out metadata for a revision.
315
193
The revision to print can either be specified by a specific
316
194
revision identifier, or you can use --revision.
320
198
takes_args = ['revision_id?']
321
takes_options = ['directory', 'revision']
199
takes_options = ['revision']
322
200
# cat-revision is more for frontends so should be exact
323
201
encoding = 'strict'
325
def print_revision(self, revisions, revid):
326
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
327
record = stream.next()
328
if record.storage_kind == 'absent':
329
raise errors.NoSuchRevision(revisions, revid)
330
revtext = record.get_bytes_as('fulltext')
331
self.outf.write(revtext.decode('utf-8'))
334
def run(self, revision_id=None, revision=None, directory=u'.'):
204
def run(self, revision_id=None, revision=None):
206
revision_id = osutils.safe_revision_id(revision_id, warn=False)
335
207
if revision_id is not None and revision is not None:
336
raise errors.BzrCommandError(gettext('You can only supply one of'
337
' revision_id or --revision'))
208
raise errors.BzrCommandError('You can only supply one of'
209
' revision_id or --revision')
338
210
if revision_id is None and revision is None:
339
raise errors.BzrCommandError(gettext('You must supply either'
340
' --revision or a revision_id'))
342
b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
344
revisions = b.repository.revisions
345
if revisions is None:
346
raise errors.BzrCommandError(gettext('Repository %r does not support '
347
'access to raw revision texts'))
349
b.repository.lock_read()
351
# TODO: jam 20060112 should cat-revision always output utf-8?
352
if revision_id is not None:
353
revision_id = osutils.safe_revision_id(revision_id, warn=False)
355
self.print_revision(revisions, revision_id)
356
except errors.NoSuchRevision:
357
msg = gettext("The repository {0} contains no revision {1}.").format(
358
b.repository.base, revision_id)
359
raise errors.BzrCommandError(msg)
360
elif revision is not None:
363
raise errors.BzrCommandError(
364
gettext('You cannot specify a NULL revision.'))
365
rev_id = rev.as_revision_id(b)
366
self.print_revision(revisions, rev_id)
368
b.repository.unlock()
371
class cmd_dump_btree(Command):
372
__doc__ = """Dump the contents of a btree index file to stdout.
374
PATH is a btree index file, it can be any URL. This includes things like
375
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
377
By default, the tuples stored in the index file will be displayed. With
378
--raw, we will uncompress the pages, but otherwise display the raw bytes
382
# TODO: Do we want to dump the internal nodes as well?
383
# TODO: It would be nice to be able to dump the un-parsed information,
384
# rather than only going through iter_all_entries. However, this is
385
# good enough for a start
387
encoding_type = 'exact'
388
takes_args = ['path']
389
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
390
' rather than the parsed tuples.'),
393
def run(self, path, raw=False):
394
dirname, basename = osutils.split(path)
395
t = transport.get_transport(dirname)
397
self._dump_raw_bytes(t, basename)
399
self._dump_entries(t, basename)
401
def _get_index_and_bytes(self, trans, basename):
402
"""Create a BTreeGraphIndex and raw bytes."""
403
bt = btree_index.BTreeGraphIndex(trans, basename, None)
404
bytes = trans.get_bytes(basename)
405
bt._file = cStringIO.StringIO(bytes)
406
bt._size = len(bytes)
409
def _dump_raw_bytes(self, trans, basename):
412
# We need to parse at least the root node.
413
# This is because the first page of every row starts with an
414
# uncompressed header.
415
bt, bytes = self._get_index_and_bytes(trans, basename)
416
for page_idx, page_start in enumerate(xrange(0, len(bytes),
417
btree_index._PAGE_SIZE)):
418
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
419
page_bytes = bytes[page_start:page_end]
421
self.outf.write('Root node:\n')
422
header_end, data = bt._parse_header_from_bytes(page_bytes)
423
self.outf.write(page_bytes[:header_end])
425
self.outf.write('\nPage %d\n' % (page_idx,))
426
if len(page_bytes) == 0:
427
self.outf.write('(empty)\n');
429
decomp_bytes = zlib.decompress(page_bytes)
430
self.outf.write(decomp_bytes)
431
self.outf.write('\n')
433
def _dump_entries(self, trans, basename):
435
st = trans.stat(basename)
436
except errors.TransportNotPossible:
437
# We can't stat, so we'll fake it because we have to do the 'get()'
439
bt, _ = self._get_index_and_bytes(trans, basename)
441
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
442
for node in bt.iter_all_entries():
443
# Node is made up of:
444
# (index, key, value, [references])
448
refs_as_tuples = None
450
refs_as_tuples = static_tuple.as_tuples(refs)
451
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
452
self.outf.write('%s\n' % (as_tuple,))
211
raise errors.BzrCommandError('You must supply either'
212
' --revision or a revision_id')
213
b = WorkingTree.open_containing(u'.')[0].branch
215
# TODO: jam 20060112 should cat-revision always output utf-8?
216
if revision_id is not None:
217
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
218
elif revision is not None:
221
raise errors.BzrCommandError('You cannot specify a NULL'
223
revno, rev_id = rev.in_history(b)
224
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
455
227
class cmd_remove_tree(Command):
456
__doc__ = """Remove the working tree from a given branch/checkout.
228
"""Remove the working tree from a given branch/checkout.
458
230
Since a lightweight checkout is little more than a working tree
459
231
this will refuse to run against one.
461
233
To re-create the working tree, use "bzr checkout".
463
235
_see_also = ['checkout', 'working-trees']
464
takes_args = ['location*']
467
help='Remove the working tree even if it has '
468
'uncommitted or shelved changes.'),
471
def run(self, location_list, force=False):
472
if not location_list:
475
for location in location_list:
476
d = bzrdir.BzrDir.open(location)
479
working = d.open_workingtree()
480
except errors.NoWorkingTree:
481
raise errors.BzrCommandError(gettext("No working tree to remove"))
482
except errors.NotLocalUrl:
483
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
484
" of a remote path"))
486
if (working.has_changes()):
487
raise errors.UncommittedChanges(working)
488
if working.get_shelf_manager().last_shelf() is not None:
489
raise errors.ShelvedChanges(working)
491
if working.user_url != working.branch.user_url:
492
raise errors.BzrCommandError(gettext("You cannot remove the working tree"
493
" from a lightweight checkout"))
495
d.destroy_workingtree()
498
class cmd_repair_workingtree(Command):
499
__doc__ = """Reset the working tree state file.
501
This is not meant to be used normally, but more as a way to recover from
502
filesystem corruption, etc. This rebuilds the working inventory back to a
503
'known good' state. Any new modifications (adding a file, renaming, etc)
504
will be lost, though modified files will still be detected as such.
506
Most users will want something more like "bzr revert" or "bzr update"
507
unless the state file has become corrupted.
509
By default this attempts to recover the current state by looking at the
510
headers of the state file. If the state file is too corrupted to even do
511
that, you can supply --revision to force the state of the tree.
514
takes_options = ['revision', 'directory',
516
help='Reset the tree even if it doesn\'t appear to be'
521
def run(self, revision=None, directory='.', force=False):
522
tree, _ = WorkingTree.open_containing(directory)
523
self.add_cleanup(tree.lock_tree_write().unlock)
527
except errors.BzrError:
528
pass # There seems to be a real error here, so we'll reset
531
raise errors.BzrCommandError(gettext(
532
'The tree does not appear to be corrupt. You probably'
533
' want "bzr revert" instead. Use "--force" if you are'
534
' sure you want to reset the working tree.'))
538
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
237
takes_args = ['location?']
239
def run(self, location='.'):
240
d = bzrdir.BzrDir.open(location)
540
tree.reset_state(revision_ids)
541
except errors.BzrError, e:
542
if revision_ids is None:
543
extra = (gettext(', the header appears corrupt, try passing -r -1'
544
' to set the state to the last commit'))
547
raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
243
working = d.open_workingtree()
244
except errors.NoWorkingTree:
245
raise errors.BzrCommandError("No working tree to remove")
246
except errors.NotLocalUrl:
247
raise errors.BzrCommandError("You cannot remove the working tree of a "
250
working_path = working.bzrdir.root_transport.base
251
branch_path = working.branch.bzrdir.root_transport.base
252
if working_path != branch_path:
253
raise errors.BzrCommandError("You cannot remove the working tree from "
254
"a lightweight checkout")
256
d.destroy_workingtree()
550
259
class cmd_revno(Command):
551
__doc__ = """Show current revision number.
260
"""Show current revision number.
553
262
This is equal to the number of revisions on this branch.
556
265
_see_also = ['info']
557
266
takes_args = ['location?']
559
Option('tree', help='Show revno of working tree'),
563
def run(self, tree=False, location=u'.'):
566
wt = WorkingTree.open_containing(location)[0]
567
self.add_cleanup(wt.lock_read().unlock)
568
except (errors.NoWorkingTree, errors.NotLocalUrl):
569
raise errors.NoWorkingTree(location)
570
revid = wt.last_revision()
572
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
573
except errors.NoSuchRevision:
575
revno = ".".join(str(n) for n in revno_t)
577
b = Branch.open_containing(location)[0]
578
self.add_cleanup(b.lock_read().unlock)
581
self.outf.write(str(revno) + '\n')
269
def run(self, location=u'.'):
270
self.outf.write(str(Branch.open_containing(location)[0].revno()))
271
self.outf.write('\n')
584
274
class cmd_revision_info(Command):
585
__doc__ = """Show revision number and revision id for a given revision identifier.
275
"""Show revision number and revision id for a given revision identifier.
588
278
takes_args = ['revision_info*']
591
custom_help('directory',
592
help='Branch to examine, '
593
'rather than the one containing the working directory.'),
594
Option('tree', help='Show revno of working tree'),
279
takes_options = ['revision']
598
def run(self, revision=None, directory=u'.', tree=False,
599
revision_info_list=[]):
282
def run(self, revision=None, revision_info_list=[]):
602
wt = WorkingTree.open_containing(directory)[0]
604
self.add_cleanup(wt.lock_read().unlock)
605
except (errors.NoWorkingTree, errors.NotLocalUrl):
607
b = Branch.open_containing(directory)[0]
608
self.add_cleanup(b.lock_read().unlock)
610
285
if revision is not None:
611
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
286
revs.extend(revision)
612
287
if revision_info_list is not None:
613
for rev_str in revision_info_list:
614
rev_spec = RevisionSpec.from_string(rev_str)
615
revision_ids.append(rev_spec.as_revision_id(b))
616
# No arguments supplied, default to the last revision
617
if len(revision_ids) == 0:
620
raise errors.NoWorkingTree(directory)
621
revision_ids.append(wt.last_revision())
288
for rev in revision_info_list:
289
revs.append(RevisionSpec.from_string(rev))
291
b = Branch.open_containing(u'.')[0]
294
revs.append(RevisionSpec.from_string('-1'))
297
revinfo = rev.in_history(b)
298
if revinfo.revno is None:
299
dotted_map = b.get_revision_id_to_revno_map()
300
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
301
print '%s %s' % (revno, revinfo.rev_id)
623
revision_ids.append(b.last_revision())
627
for revision_id in revision_ids:
629
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
630
revno = '.'.join(str(i) for i in dotted_revno)
631
except errors.NoSuchRevision:
633
maxlen = max(maxlen, len(revno))
634
revinfos.append([revno, revision_id])
638
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
303
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
641
306
class cmd_add(Command):
642
__doc__ = """Add specified files or directories.
307
"""Add specified files or directories.
644
309
In non-recursive mode, all the named items are added, regardless
645
310
of whether they were previously ignored. A warning is given if
852
522
takes_args = ['names*']
853
523
takes_options = [Option("after", help="Move only the bzr identifier"
854
524
" of the file, because the file has already been moved."),
855
Option('auto', help='Automatically guess renames.'),
856
Option('dry-run', help='Avoid making changes when guessing renames.'),
858
526
aliases = ['move', 'rename']
859
527
encoding_type = 'replace'
861
def run(self, names_list, after=False, auto=False, dry_run=False):
863
return self.run_auto(names_list, after, dry_run)
865
raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
529
def run(self, names_list, after=False):
866
530
if names_list is None:
868
533
if len(names_list) < 2:
869
raise errors.BzrCommandError(gettext("missing file argument"))
870
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
871
self.add_cleanup(tree.lock_tree_write().unlock)
872
self._run(tree, names_list, rel_names, after)
874
def run_auto(self, names_list, after, dry_run):
875
if names_list is not None and len(names_list) > 1:
876
raise errors.BzrCommandError(gettext('Only one path may be specified to'
879
raise errors.BzrCommandError(gettext('--after cannot be specified with'
881
work_tree, file_list = WorkingTree.open_containing_paths(
882
names_list, default_directory='.')
883
self.add_cleanup(work_tree.lock_tree_write().unlock)
884
rename_map.RenameMap.guess_renames(work_tree, dry_run)
886
def _run(self, tree, names_list, rel_names, after):
887
into_existing = osutils.isdir(names_list[-1])
888
if into_existing and len(names_list) == 2:
890
# a. case-insensitive filesystem and change case of dir
891
# b. move directory after the fact (if the source used to be
892
# a directory, but now doesn't exist in the working tree
893
# and the target is an existing directory, just rename it)
894
if (not tree.case_sensitive
895
and rel_names[0].lower() == rel_names[1].lower()):
896
into_existing = False
899
# 'fix' the case of a potential 'from'
900
from_id = tree.path2id(
901
tree.get_canonical_inventory_path(rel_names[0]))
902
if (not osutils.lexists(names_list[0]) and
903
from_id and inv.get_file_kind(from_id) == "directory"):
904
into_existing = False
534
raise errors.BzrCommandError("missing file argument")
535
tree, rel_names = tree_files(names_list)
537
if os.path.isdir(names_list[-1]):
907
538
# move into existing directory
908
# All entries reference existing inventory items, so fix them up
909
# for cicp file-systems.
910
rel_names = tree.get_canonical_inventory_paths(rel_names)
911
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
913
self.outf.write("%s => %s\n" % (src, dest))
539
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
540
self.outf.write("%s => %s\n" % pair)
915
542
if len(names_list) != 2:
916
raise errors.BzrCommandError(gettext('to mv multiple files the'
543
raise errors.BzrCommandError('to mv multiple files the'
917
544
' destination must be a versioned'
920
# for cicp file-systems: the src references an existing inventory
922
src = tree.get_canonical_inventory_path(rel_names[0])
923
# Find the canonical version of the destination: In all cases, the
924
# parent of the target must be in the inventory, so we fetch the
925
# canonical version from there (we do not always *use* the
926
# canonicalized tail portion - we may be attempting to rename the
928
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
929
dest_parent = osutils.dirname(canon_dest)
930
spec_tail = osutils.basename(rel_names[1])
931
# For a CICP file-system, we need to avoid creating 2 inventory
932
# entries that differ only by case. So regardless of the case
933
# we *want* to use (ie, specified by the user or the file-system),
934
# we must always choose to use the case of any existing inventory
935
# items. The only exception to this is when we are attempting a
936
# case-only rename (ie, canonical versions of src and dest are
938
dest_id = tree.path2id(canon_dest)
939
if dest_id is None or tree.path2id(src) == dest_id:
940
# No existing item we care about, so work out what case we
941
# are actually going to use.
943
# If 'after' is specified, the tail must refer to a file on disk.
945
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
947
# pathjoin with an empty tail adds a slash, which breaks
949
dest_parent_fq = tree.basedir
951
dest_tail = osutils.canonical_relpath(
953
osutils.pathjoin(dest_parent_fq, spec_tail))
955
# not 'after', so case as specified is used
956
dest_tail = spec_tail
958
# Use the existing item so 'mv' fails with AlreadyVersioned.
959
dest_tail = os.path.basename(canon_dest)
960
dest = osutils.pathjoin(dest_parent, dest_tail)
961
mutter("attempting to move %s => %s", src, dest)
962
tree.rename_one(src, dest, after=after)
964
self.outf.write("%s => %s\n" % (src, dest))
546
tree.rename_one(rel_names[0], rel_names[1], after=after)
547
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
967
550
class cmd_pull(Command):
968
__doc__ = """Turn this branch into a mirror of another branch.
551
"""Turn this branch into a mirror of another branch.
970
By default, this command only works on branches that have not diverged.
971
Branches are considered diverged if the destination branch's most recent
972
commit is one that has not been merged (directly or indirectly) into the
553
This command only works on branches that have not diverged. Branches are
554
considered diverged if the destination branch's most recent commit is one
555
that has not been merged (directly or indirectly) into the parent.
975
557
If branches have diverged, you can use 'bzr merge' to integrate the changes
976
558
from one into the other. Once one branch has merged, the other should
977
559
be able to pull it again.
979
If you want to replace your local changes and just want your branch to
980
match the remote one, use pull --overwrite. This will work even if the two
981
branches have diverged.
983
If there is no default location set, the first pull will set it (use
984
--no-remember to avoid setting it). After that, you can omit the
985
location to use the default. To change the default, use --remember. The
986
value will only be saved if the remote location can be accessed.
988
Note: The location can be specified either in the form of a branch,
989
or in the form of a path to a file containing a merge directive generated
561
If you want to forget your local changes and just update your branch to
562
match the remote one, use pull --overwrite.
564
If there is no default location set, the first pull will set it. After
565
that, you can omit the location to use the default. To change the
566
default, use --remember. The value will only be saved if the remote
567
location can be accessed.
993
_see_also = ['push', 'update', 'status-flags', 'send']
994
takes_options = ['remember', 'overwrite', 'revision',
995
custom_help('verbose',
996
help='Show logs of pulled revisions.'),
997
custom_help('directory',
570
_see_also = ['push', 'update', 'status-flags']
571
takes_options = ['remember', 'overwrite', 'revision', 'verbose',
998
573
help='Branch to pull into, '
999
'rather than the one containing the working directory.'),
1001
help="Perform a local pull in a bound "
1002
"branch. Local pulls are not applied to "
1003
"the master branch."
574
'rather than the one containing the working directory.',
1006
help="Show base revision text in conflicts.")
1008
579
takes_args = ['location?']
1009
580
encoding_type = 'replace'
1011
def run(self, location=None, remember=None, overwrite=False,
582
def run(self, location=None, remember=False, overwrite=False,
1012
583
revision=None, verbose=False,
1013
directory=None, local=False,
1015
585
# FIXME: too much stuff is in the command class
1016
586
revision_id = None
1017
587
mergeable = None
1112
662
If branches have diverged, you can use 'bzr push --overwrite' to replace
1113
663
the other branch completely, discarding its unmerged changes.
1115
665
If you want to ensure you have the different changes in the other branch,
1116
666
do a merge (see bzr help merge) from the other branch, and commit that.
1117
667
After that you will be able to do a push without '--overwrite'.
1119
If there is no default push location set, the first push will set it (use
1120
--no-remember to avoid setting it). After that, you can omit the
1121
location to use the default. To change the default, use --remember. The
1122
value will only be saved if the remote location can be accessed.
669
If there is no default push location set, the first push will set it.
670
After that, you can omit the location to use the default. To change the
671
default, use --remember. The value will only be saved if the remote
672
location can be accessed.
1125
675
_see_also = ['pull', 'update', 'working-trees']
1126
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
676
takes_options = ['remember', 'overwrite', 'verbose',
1127
677
Option('create-prefix',
1128
678
help='Create the path leading up to the branch '
1129
679
'if it does not already exist.'),
1130
custom_help('directory',
1131
681
help='Branch to push from, '
1132
'rather than the one containing the working directory.'),
682
'rather than the one containing the working directory.',
1133
686
Option('use-existing-dir',
1134
687
help='By default push will fail if the target'
1135
688
' directory exists, but does not already'
1136
689
' have a control directory. This flag will'
1137
690
' allow push to proceed.'),
1139
help='Create a stacked branch that references the public location '
1140
'of the parent branch.'),
1141
Option('stacked-on',
1142
help='Create a stacked branch that refers to another branch '
1143
'for the commit history. Only the work not present in the '
1144
'referenced branch is included in the branch created.',
1147
help='Refuse to push if there are uncommitted changes in'
1148
' the working tree, --no-strict disables the check.'),
1150
help="Don't populate the working tree, even for protocols"
1151
" that support it."),
1153
692
takes_args = ['location?']
1154
693
encoding_type = 'replace'
1156
def run(self, location=None, remember=None, overwrite=False,
1157
create_prefix=False, verbose=False, revision=None,
1158
use_existing_dir=False, directory=None, stacked_on=None,
1159
stacked=False, strict=None, no_tree=False):
1160
from bzrlib.push import _show_push_branch
695
def run(self, location=None, remember=False, overwrite=False,
696
create_prefix=False, verbose=False,
697
use_existing_dir=False,
699
# FIXME: Way too big! Put this into a function called from the
1162
701
if directory is None:
1164
# Get the source branch
1166
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1167
# Get the tip's revision_id
1168
revision = _get_one_revision('push', revision)
1169
if revision is not None:
1170
revision_id = revision.in_history(br_from).rev_id
1173
if tree is not None and revision_id is None:
1174
tree.check_changed_or_out_of_date(
1175
strict, 'push_strict',
1176
more_error='Use --no-strict to force the push.',
1177
more_warning='Uncommitted changes will not be pushed.')
1178
# Get the stacked_on branch, if any
1179
if stacked_on is not None:
1180
stacked_on = urlutils.normalize_url(stacked_on)
1182
parent_url = br_from.get_parent()
1184
parent = Branch.open(parent_url)
1185
stacked_on = parent.get_public_branch()
1187
# I considered excluding non-http url's here, thus forcing
1188
# 'public' branches only, but that only works for some
1189
# users, so it's best to just depend on the user spotting an
1190
# error by the feedback given to them. RBC 20080227.
1191
stacked_on = parent_url
1193
raise errors.BzrCommandError(gettext(
1194
"Could not determine branch to refer to."))
1196
# Get the destination location
703
br_from = Branch.open_containing(directory)[0]
704
stored_loc = br_from.get_push_location()
1197
705
if location is None:
1198
stored_loc = br_from.get_push_location()
1199
706
if stored_loc is None:
1200
raise errors.BzrCommandError(gettext(
1201
"No push location known or specified."))
707
raise errors.BzrCommandError("No push location known or specified.")
1203
709
display_url = urlutils.unescape_for_display(stored_loc,
1204
710
self.outf.encoding)
1205
note(gettext("Using saved push location: %s") % display_url)
711
self.outf.write("Using saved location: %s\n" % display_url)
1206
712
location = stored_loc
1208
_show_push_branch(br_from, revision_id, location, self.outf,
1209
verbose=verbose, overwrite=overwrite, remember=remember,
1210
stacked_on=stacked_on, create_prefix=create_prefix,
1211
use_existing_dir=use_existing_dir, no_tree=no_tree)
714
to_transport = transport.get_transport(location)
716
br_to = repository_to = dir_to = None
718
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
719
except errors.NotBranchError:
720
pass # Didn't find anything
722
# If we can open a branch, use its direct repository, otherwise see
723
# if there is a repository without a branch.
725
br_to = dir_to.open_branch()
726
except errors.NotBranchError:
727
# Didn't find a branch, can we find a repository?
729
repository_to = dir_to.find_repository()
730
except errors.NoRepositoryPresent:
733
# Found a branch, so we must have found a repository
734
repository_to = br_to.repository
739
# The destination doesn't exist; create it.
740
# XXX: Refactor the create_prefix/no_create_prefix code into a
741
# common helper function
743
to_transport.mkdir('.')
744
except errors.FileExists:
745
if not use_existing_dir:
746
raise errors.BzrCommandError("Target directory %s"
747
" already exists, but does not have a valid .bzr"
748
" directory. Supply --use-existing-dir to push"
749
" there anyway." % location)
750
except errors.NoSuchFile:
751
if not create_prefix:
752
raise errors.BzrCommandError("Parent directory of %s"
754
"\nYou may supply --create-prefix to create all"
755
" leading parent directories."
757
_create_prefix(to_transport)
759
# Now the target directory exists, but doesn't have a .bzr
760
# directory. So we need to create it, along with any work to create
761
# all of the dependent branches, etc.
762
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
763
revision_id=br_from.last_revision())
764
br_to = dir_to.open_branch()
765
# TODO: Some more useful message about what was copied
766
note('Created new branch.')
767
# We successfully created the target, remember it
768
if br_from.get_push_location() is None or remember:
769
br_from.set_push_location(br_to.base)
770
elif repository_to is None:
771
# we have a bzrdir but no branch or repository
772
# XXX: Figure out what to do other than complain.
773
raise errors.BzrCommandError("At %s you have a valid .bzr control"
774
" directory, but not a branch or repository. This is an"
775
" unsupported configuration. Please move the target directory"
776
" out of the way and try again."
779
# We have a repository but no branch, copy the revisions, and then
781
last_revision_id = br_from.last_revision()
782
repository_to.fetch(br_from.repository,
783
revision_id=last_revision_id)
784
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
785
note('Created new branch.')
786
if br_from.get_push_location() is None or remember:
787
br_from.set_push_location(br_to.base)
788
else: # We have a valid to branch
789
# We were able to connect to the remote location, so remember it
790
# we don't need to successfully push because of possible divergence.
791
if br_from.get_push_location() is None or remember:
792
br_from.set_push_location(br_to.base)
794
old_rh = br_to.revision_history()
797
tree_to = dir_to.open_workingtree()
798
except errors.NotLocalUrl:
799
warning("This transport does not update the working "
800
"tree of: %s. See 'bzr help working-trees' for "
801
"more information." % br_to.base)
802
push_result = br_from.push(br_to, overwrite)
803
except errors.NoWorkingTree:
804
push_result = br_from.push(br_to, overwrite)
808
push_result = br_from.push(tree_to.branch, overwrite)
812
except errors.DivergedBranches:
813
raise errors.BzrCommandError('These branches have diverged.'
814
' Try using "merge" and then "push".')
815
if push_result is not None:
816
push_result.report(self.outf)
818
new_rh = br_to.revision_history()
821
from bzrlib.log import show_changed_revisions
822
show_changed_revisions(br_to, old_rh, new_rh,
825
# we probably did a clone rather than a push, so a message was
1214
830
class cmd_branch(Command):
1215
__doc__ = """Create a new branch that is a copy of an existing branch.
831
"""Create a new copy of a branch.
1217
833
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1218
834
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1224
840
To retrieve the branch as of a particular revision, supply the --revision
1225
841
parameter, as in "branch foo/bar -r 5".
1227
The synonyms 'clone' and 'get' for this command are deprecated.
1230
844
_see_also = ['checkout']
1231
845
takes_args = ['from_location', 'to_location?']
1232
takes_options = ['revision',
1233
Option('hardlink', help='Hard-link working tree files where possible.'),
1234
Option('files-from', type=str,
1235
help="Get file contents from this tree."),
1237
help="Create a branch without a working-tree."),
1239
help="Switch the checkout in the current directory "
1240
"to the new branch."),
1242
help='Create a stacked branch referring to the source branch. '
1243
'The new branch will depend on the availability of the source '
1244
'branch for all operations.'),
1245
Option('standalone',
1246
help='Do not use a shared repository, even if available.'),
1247
Option('use-existing-dir',
1248
help='By default branch will fail if the target'
1249
' directory exists, but does not already'
1250
' have a control directory. This flag will'
1251
' allow branch to proceed.'),
1253
help="Bind new branch to from location."),
846
takes_options = ['revision']
1255
847
aliases = ['get', 'clone']
1257
def run(self, from_location, to_location=None, revision=None,
1258
hardlink=False, stacked=False, standalone=False, no_tree=False,
1259
use_existing_dir=False, switch=False, bind=False,
1261
from bzrlib import switch as _mod_switch
849
def run(self, from_location, to_location=None, revision=None):
1262
850
from bzrlib.tag import _merge_tags_if_possible
1263
if self.invoked_as in ['get', 'clone']:
1264
ui.ui_factory.show_user_warning(
1265
'deprecated_command',
1266
deprecated_name=self.invoked_as,
1267
recommended_name='branch',
1268
deprecated_in_version='2.4')
1269
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1271
if not (hardlink or files_from):
1272
# accelerator_tree is usually slower because you have to read N
1273
# files (no readahead, lots of seeks, etc), but allow the user to
1274
# explicitly request it
1275
accelerator_tree = None
1276
if files_from is not None and files_from != from_location:
1277
accelerator_tree = WorkingTree.open(files_from)
1278
revision = _get_one_revision('branch', revision)
1279
self.add_cleanup(br_from.lock_read().unlock)
1280
if revision is not None:
1281
revision_id = revision.as_revision_id(br_from)
1283
# FIXME - wt.last_revision, fallback to branch, fall back to
1284
# None or perhaps NULL_REVISION to mean copy nothing
1286
revision_id = br_from.last_revision()
1287
if to_location is None:
1288
to_location = urlutils.derive_to_location(from_location)
1289
to_transport = transport.get_transport(to_location)
1291
to_transport.mkdir('.')
1292
except errors.FileExists:
1293
if not use_existing_dir:
1294
raise errors.BzrCommandError(gettext('Target directory "%s" '
1295
'already exists.') % to_location)
1298
bzrdir.BzrDir.open_from_transport(to_transport)
1299
except errors.NotBranchError:
1302
raise errors.AlreadyBranchError(to_location)
1303
except errors.NoSuchFile:
1304
raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
1307
# preserve whatever source format we have.
1308
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1309
possible_transports=[to_transport],
1310
accelerator_tree=accelerator_tree,
1311
hardlink=hardlink, stacked=stacked,
1312
force_new_repo=standalone,
1313
create_tree_if_local=not no_tree,
1314
source_branch=br_from)
1315
branch = dir.open_branch()
1316
except errors.NoSuchRevision:
1317
to_transport.delete_tree('.')
1318
msg = gettext("The branch {0} has no revision {1}.").format(
1319
from_location, revision)
1320
raise errors.BzrCommandError(msg)
1321
_merge_tags_if_possible(br_from, branch)
1322
# If the source branch is stacked, the new branch may
1323
# be stacked whether we asked for that explicitly or not.
1324
# We therefore need a try/except here and not just 'if stacked:'
1326
note(gettext('Created new stacked branch referring to %s.') %
1327
branch.get_stacked_on_url())
1328
except (errors.NotStacked, errors.UnstackableBranchFormat,
1329
errors.UnstackableRepositoryFormat), e:
1330
note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
1332
# Bind to the parent
1333
parent_branch = Branch.open(from_location)
1334
branch.bind(parent_branch)
1335
note(gettext('New branch bound to %s') % from_location)
1337
# Switch to the new branch
1338
wt, _ = WorkingTree.open_containing('.')
1339
_mod_switch.switch(wt.bzrdir, branch)
1340
note(gettext('Switched to branch: %s'),
1341
urlutils.unescape_for_display(branch.base, 'utf-8'))
1344
class cmd_branches(Command):
1345
__doc__ = """List the branches available at the current location.
1347
This command will print the names of all the branches at the current
1351
takes_args = ['location?']
1353
Option('recursive', short_name='R',
1354
help='Recursively scan for branches rather than '
1355
'just looking in the specified location.')]
1357
def run(self, location=".", recursive=False):
1359
t = transport.get_transport(location)
1360
if not t.listable():
1361
raise errors.BzrCommandError(
1362
"Can't scan this type of location.")
1363
for b in bzrdir.BzrDir.find_branches(t):
1364
self.outf.write("%s\n" % urlutils.unescape_for_display(
1365
urlutils.relative_url(t.base, b.base),
1366
self.outf.encoding).rstrip("/"))
1368
dir = bzrdir.BzrDir.open_containing(location)[0]
1369
for branch in dir.list_branches():
1370
if branch.name is None:
1371
self.outf.write(gettext(" (default)\n"))
1373
self.outf.write(" %s\n" % branch.name.encode(
1374
self.outf.encoding))
853
elif len(revision) > 1:
854
raise errors.BzrCommandError(
855
'bzr branch --revision takes exactly 1 revision value')
857
br_from = Branch.open(from_location)
860
if len(revision) == 1 and revision[0] is not None:
861
revision_id = revision[0].in_history(br_from)[1]
863
# FIXME - wt.last_revision, fallback to branch, fall back to
864
# None or perhaps NULL_REVISION to mean copy nothing
866
revision_id = br_from.last_revision()
867
if to_location is None:
868
to_location = urlutils.derive_to_location(from_location)
871
name = os.path.basename(to_location) + '\n'
873
to_transport = transport.get_transport(to_location)
875
to_transport.mkdir('.')
876
except errors.FileExists:
877
raise errors.BzrCommandError('Target directory "%s" already'
878
' exists.' % to_location)
879
except errors.NoSuchFile:
880
raise errors.BzrCommandError('Parent of "%s" does not exist.'
883
# preserve whatever source format we have.
884
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
885
possible_transports=[to_transport])
886
branch = dir.open_branch()
887
except errors.NoSuchRevision:
888
to_transport.delete_tree('.')
889
msg = "The branch %s has no revision %s." % (from_location, revision[0])
890
raise errors.BzrCommandError(msg)
892
branch.control_files.put_utf8('branch-name', name)
893
_merge_tags_if_possible(br_from, branch)
894
note('Branched %d revision(s).' % branch.revno())
1377
899
class cmd_checkout(Command):
1378
__doc__ = """Create a new checkout of an existing branch.
900
"""Create a new checkout of an existing branch.
1380
902
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1381
903
the branch found in '.'. This is useful if you have removed the working tree
1382
904
or if it was never created - i.e. if you pushed the branch to its current
1383
905
location using SFTP.
1385
907
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1386
908
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1387
909
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1460
984
@display_command
1461
985
def run(self, dir=u'.'):
1462
986
tree = WorkingTree.open_containing(dir)[0]
1463
self.add_cleanup(tree.lock_read().unlock)
1464
new_inv = tree.inventory
1465
old_tree = tree.basis_tree()
1466
self.add_cleanup(old_tree.lock_read().unlock)
1467
old_inv = old_tree.inventory
1469
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1470
for f, paths, c, v, p, n, k, e in iterator:
1471
if paths[0] == paths[1]:
1475
renames.append(paths)
1477
for old_name, new_name in renames:
1478
self.outf.write("%s => %s\n" % (old_name, new_name))
989
new_inv = tree.inventory
990
old_tree = tree.basis_tree()
993
old_inv = old_tree.inventory
994
renames = list(_mod_tree.find_renames(old_inv, new_inv))
996
for old_name, new_name in renames:
997
self.outf.write("%s => %s\n" % (old_name, new_name))
1481
1004
class cmd_update(Command):
1482
__doc__ = """Update a tree to have the latest code committed to its branch.
1005
"""Update a tree to have the latest code committed to its branch.
1484
1007
This will perform a merge into the working tree, and may generate
1485
conflicts. If you have any local changes, you will still
1008
conflicts. If you have any local changes, you will still
1486
1009
need to commit them after the update for the update to be complete.
1488
If you want to discard your local changes, you can just do a
1011
If you want to discard your local changes, you can just do a
1489
1012
'bzr revert' instead of 'bzr commit' after the update.
1491
If you want to restore a file that has been removed locally, use
1492
'bzr revert' instead of 'bzr update'.
1494
If the tree's branch is bound to a master branch, it will also update
1495
the branch from the master.
1498
1015
_see_also = ['pull', 'working-trees', 'status-flags']
1499
1016
takes_args = ['dir?']
1500
takes_options = ['revision',
1502
help="Show base revision text in conflicts."),
1504
1017
aliases = ['up']
1506
def run(self, dir='.', revision=None, show_base=None):
1507
if revision is not None and len(revision) != 1:
1508
raise errors.BzrCommandError(gettext(
1509
"bzr update --revision takes exactly one revision"))
1019
def run(self, dir='.'):
1510
1020
tree = WorkingTree.open_containing(dir)[0]
1511
branch = tree.branch
1512
possible_transports = []
1513
master = branch.get_master_branch(
1514
possible_transports=possible_transports)
1021
master = tree.branch.get_master_branch()
1515
1022
if master is not None:
1516
branch_location = master.base
1517
1023
tree.lock_write()
1519
branch_location = tree.branch.base
1520
1025
tree.lock_tree_write()
1521
self.add_cleanup(tree.unlock)
1522
# get rid of the final '/' and be ready for display
1523
branch_location = urlutils.unescape_for_display(
1524
branch_location.rstrip('/'),
1526
existing_pending_merges = tree.get_parent_ids()[1:]
1530
# may need to fetch data into a heavyweight checkout
1531
# XXX: this may take some time, maybe we should display a
1533
old_tip = branch.update(possible_transports)
1534
if revision is not None:
1535
revision_id = revision[0].as_revision_id(branch)
1537
revision_id = branch.last_revision()
1538
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1539
revno = branch.revision_id_to_dotted_revno(revision_id)
1540
note(gettext("Tree is up to date at revision {0} of branch {1}"
1541
).format('.'.join(map(str, revno)), branch_location))
1543
view_info = _get_view_info_for_change_reporter(tree)
1544
change_reporter = delta._ChangeReporter(
1545
unversioned_filter=tree.is_ignored,
1546
view_info=view_info)
1548
conflicts = tree.update(
1550
possible_transports=possible_transports,
1551
revision=revision_id,
1553
show_base=show_base)
1554
except errors.NoSuchRevision, e:
1555
raise errors.BzrCommandError(gettext(
1556
"branch has no revision %s\n"
1557
"bzr update --revision only works"
1558
" for a revision in the branch history")
1560
revno = tree.branch.revision_id_to_dotted_revno(
1561
_mod_revision.ensure_null(tree.last_revision()))
1562
note(gettext('Updated to revision {0} of branch {1}').format(
1563
'.'.join(map(str, revno)), branch_location))
1564
parent_ids = tree.get_parent_ids()
1565
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1566
note(gettext('Your local commits will now show as pending merges with '
1567
"'bzr status', and can be committed with 'bzr commit'."))
1027
existing_pending_merges = tree.get_parent_ids()[1:]
1028
last_rev = _mod_revision.ensure_null(tree.last_revision())
1029
if last_rev == _mod_revision.ensure_null(
1030
tree.branch.last_revision()):
1031
# may be up to date, check master too.
1032
if master is None or last_rev == _mod_revision.ensure_null(
1033
master.last_revision()):
1034
revno = tree.branch.revision_id_to_revno(last_rev)
1035
note("Tree is up to date at revision %d." % (revno,))
1037
conflicts = tree.update(delta._ChangeReporter(
1038
unversioned_filter=tree.is_ignored))
1039
revno = tree.branch.revision_id_to_revno(
1040
_mod_revision.ensure_null(tree.last_revision()))
1041
note('Updated to revision %d.' % (revno,))
1042
if tree.get_parent_ids()[1:] != existing_pending_merges:
1043
note('Your local commits will now show as pending merges with '
1044
"'bzr status', and can be committed with 'bzr commit'.")
1574
1053
class cmd_info(Command):
1575
__doc__ = """Show information about a working tree, branch or repository.
1054
"""Show information about a working tree, branch or repository.
1577
1056
This command will show all known locations and formats associated to the
1578
tree, branch or repository.
1580
In verbose mode, statistical information is included with each report.
1581
To see extended statistic information, use a verbosity level of 2 or
1582
higher by specifying the verbose option multiple times, e.g. -vv.
1057
tree, branch or repository. Statistical information is included with
1584
1060
Branches and working trees will also report any missing revisions.
1588
Display information on the format and related locations:
1592
Display the above together with extended format information and
1593
basic statistics (like the number of files in the working tree and
1594
number of revisions in the branch and repository):
1598
Display the above together with number of committers to the branch:
1602
1062
_see_also = ['revno', 'working-trees', 'repositories']
1603
1063
takes_args = ['location?']
1604
1064
takes_options = ['verbose']
1605
encoding_type = 'replace'
1607
1066
@display_command
1608
def run(self, location=None, verbose=False):
1610
noise_level = get_verbosity_level()
1067
def run(self, location=None, verbose=0):
1613
1068
from bzrlib.info import show_bzrdir_info
1614
1069
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1615
verbose=noise_level, outfile=self.outf)
1618
1073
class cmd_remove(Command):
1619
__doc__ = """Remove files or directories.
1621
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1622
delete them if they can easily be recovered using revert otherwise they
1623
will be backed up (adding an extention of the form .~#~). If no options or
1624
parameters are given Bazaar will scan for files that are being tracked by
1625
Bazaar but missing in your tree and stop tracking them for you.
1074
"""Remove files or directories.
1076
This makes bzr stop tracking changes to the specified files and
1077
delete them if they can easily be recovered using revert.
1079
You can specify one or more files, and/or --new. If you specify --new,
1080
only 'added' files will be removed. If you specify both, then new files
1081
in the specified directories will be removed. If the directories are
1082
also new, they will also be removed.
1627
1084
takes_args = ['file*']
1628
1085
takes_options = ['verbose',
1629
Option('new', help='Only remove files that have never been committed.'),
1086
Option('new', help='Remove newly-added files.'),
1630
1087
RegistryOption.from_kwargs('file-deletion-strategy',
1631
1088
'The file deletion mode to be used.',
1632
1089
title='Deletion Strategy', value_switches=True, enum_switch=False,
1633
safe='Backup changed files (default).',
1634
keep='Delete from bzr but leave the working copy.',
1635
no_backup='Don\'t backup changed files.',
1090
safe='Only delete files if they can be'
1091
' safely recovered (default).',
1092
keep="Don't delete any files.",
1636
1093
force='Delete all the specified files, even if they can not be '
1637
'recovered and even if they are non-empty directories. '
1638
'(deprecated, use no-backup)')]
1639
aliases = ['rm', 'del']
1094
'recovered and even if they are non-empty directories.')]
1640
1096
encoding_type = 'replace'
1642
1098
def run(self, file_list, verbose=False, new=False,
1643
1099
file_deletion_strategy='safe'):
1644
if file_deletion_strategy == 'force':
1645
note(gettext("(The --force option is deprecated, rather use --no-backup "
1647
file_deletion_strategy = 'no-backup'
1649
tree, file_list = WorkingTree.open_containing_paths(file_list)
1100
tree, file_list = tree_files(file_list)
1651
1102
if file_list is not None:
1652
file_list = [f for f in file_list]
1103
file_list = [f for f in file_list if f != '']
1105
raise errors.BzrCommandError('Specify one or more files to'
1106
' remove, or use --new.')
1654
self.add_cleanup(tree.lock_write().unlock)
1655
# Heuristics should probably all move into tree.remove_smart or
1658
1109
added = tree.changes_from(tree.basis_tree(),
1659
1110
specific_files=file_list).added
1660
1111
file_list = sorted([f[0] for f in added], reverse=True)
1661
1112
if len(file_list) == 0:
1662
raise errors.BzrCommandError(gettext('No matching files.'))
1663
elif file_list is None:
1664
# missing files show up in iter_changes(basis) as
1665
# versioned-with-no-kind.
1667
for change in tree.iter_changes(tree.basis_tree()):
1668
# Find paths in the working tree that have no kind:
1669
if change[1][1] is not None and change[6][1] is None:
1670
missing.append(change[1][1])
1671
file_list = sorted(missing, reverse=True)
1672
file_deletion_strategy = 'keep'
1113
raise errors.BzrCommandError('No matching files.')
1673
1114
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1674
1115
keep_files=file_deletion_strategy=='keep',
1675
force=(file_deletion_strategy=='no-backup'))
1116
force=file_deletion_strategy=='force')
1678
1119
class cmd_file_id(Command):
1679
__doc__ = """Print file_id of a particular file or directory.
1120
"""Print file_id of a particular file or directory.
1681
1122
The file_id is assigned when the file is first added and remains the
1682
1123
same through all revisions where the file exists, even when it is
2236
1596
return int(limitstring)
2237
1597
except ValueError:
2238
msg = gettext("The limit argument must be an integer.")
2239
raise errors.BzrCommandError(msg)
2242
def _parse_levels(s):
2246
msg = gettext("The levels argument must be an integer.")
1598
msg = "The limit argument must be an integer."
2247
1599
raise errors.BzrCommandError(msg)
2250
1602
class cmd_log(Command):
2251
__doc__ = """Show historical log for a branch or subset of a branch.
2253
log is bzr's default tool for exploring the history of a branch.
2254
The branch to use is taken from the first parameter. If no parameters
2255
are given, the branch containing the working directory is logged.
2256
Here are some simple examples::
2258
bzr log log the current branch
2259
bzr log foo.py log a file in its branch
2260
bzr log http://server/branch log a branch on a server
2262
The filtering, ordering and information shown for each revision can
2263
be controlled as explained below. By default, all revisions are
2264
shown sorted (topologically) so that newer revisions appear before
2265
older ones and descendants always appear before ancestors. If displayed,
2266
merged revisions are shown indented under the revision in which they
2271
The log format controls how information about each revision is
2272
displayed. The standard log formats are called ``long``, ``short``
2273
and ``line``. The default is long. See ``bzr help log-formats``
2274
for more details on log formats.
2276
The following options can be used to control what information is
2279
-l N display a maximum of N revisions
2280
-n N display N levels of revisions (0 for all, 1 for collapsed)
2281
-v display a status summary (delta) for each revision
2282
-p display a diff (patch) for each revision
2283
--show-ids display revision-ids (and file-ids), not just revnos
2285
Note that the default number of levels to display is a function of the
2286
log format. If the -n option is not used, the standard log formats show
2287
just the top level (mainline).
2289
Status summaries are shown using status flags like A, M, etc. To see
2290
the changes explained using words like ``added`` and ``modified``
2291
instead, use the -vv option.
2295
To display revisions from oldest to newest, use the --forward option.
2296
In most cases, using this option will have little impact on the total
2297
time taken to produce a log, though --forward does not incrementally
2298
display revisions like --reverse does when it can.
2300
:Revision filtering:
2302
The -r option can be used to specify what revision or range of revisions
2303
to filter against. The various forms are shown below::
2305
-rX display revision X
2306
-rX.. display revision X and later
2307
-r..Y display up to and including revision Y
2308
-rX..Y display from X to Y inclusive
2310
See ``bzr help revisionspec`` for details on how to specify X and Y.
2311
Some common examples are given below::
2313
-r-1 show just the tip
2314
-r-10.. show the last 10 mainline revisions
2315
-rsubmit:.. show what's new on this branch
2316
-rancestor:path.. show changes since the common ancestor of this
2317
branch and the one at location path
2318
-rdate:yesterday.. show changes since yesterday
2320
When logging a range of revisions using -rX..Y, log starts at
2321
revision Y and searches back in history through the primary
2322
("left-hand") parents until it finds X. When logging just the
2323
top level (using -n1), an error is reported if X is not found
2324
along the way. If multi-level logging is used (-n0), X may be
2325
a nested merge revision and the log will be truncated accordingly.
2329
If parameters are given and the first one is not a branch, the log
2330
will be filtered to show only those revisions that changed the
2331
nominated files or directories.
2333
Filenames are interpreted within their historical context. To log a
2334
deleted file, specify a revision range so that the file existed at
2335
the end or start of the range.
2337
Historical context is also important when interpreting pathnames of
2338
renamed files/directories. Consider the following example:
2340
* revision 1: add tutorial.txt
2341
* revision 2: modify tutorial.txt
2342
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2346
* ``bzr log guide.txt`` will log the file added in revision 1
2348
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2350
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2351
the original file in revision 2.
2353
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2354
was no file called guide.txt in revision 2.
2356
Renames are always followed by log. By design, there is no need to
2357
explicitly ask for this (and no way to stop logging a file back
2358
until it was last renamed).
2362
The --match option can be used for finding revisions that match a
2363
regular expression in a commit message, committer, author or bug.
2364
Specifying the option several times will match any of the supplied
2365
expressions. --match-author, --match-bugs, --match-committer and
2366
--match-message can be used to only match a specific field.
2370
GUI tools and IDEs are often better at exploring history than command
2371
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2372
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2373
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2374
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2376
You may find it useful to add the aliases below to ``bazaar.conf``::
2380
top = log -l10 --line
2383
``bzr tip`` will then show the latest revision while ``bzr top``
2384
will show the last 10 mainline revisions. To see the details of a
2385
particular revision X, ``bzr show -rX``.
2387
If you are interested in looking deeper into a particular merge X,
2388
use ``bzr log -n0 -rX``.
2390
``bzr log -v`` on a branch with lots of history is currently
2391
very slow. A fix for this issue is currently under development.
2392
With or without that fix, it is recommended that a revision range
2393
be given when using the -v option.
2395
bzr has a generic full-text matching plugin, bzr-search, that can be
2396
used to find revisions matching user names, commit messages, etc.
2397
Among other features, this plugin can find all revisions containing
2398
a list of words but not others.
2400
When exploring non-mainline history on large projects with deep
2401
history, the performance of log can be greatly improved by installing
2402
the historycache plugin. This plugin buffers historical information
2403
trading disk space for faster speed.
1603
"""Show log of a branch, file, or directory.
1605
By default show the log of the branch containing the working directory.
1607
To request a range of logs, you can use the command -r begin..end
1608
-r revision requests a specific revision, -r ..end or -r begin.. are
1612
Log the current branch::
1620
Log the last 10 revisions of a branch::
1622
bzr log -r -10.. http://server/branch
2405
takes_args = ['file*']
2406
_see_also = ['log-formats', 'revisionspec']
1625
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1627
takes_args = ['location?']
2407
1628
takes_options = [
2408
1629
Option('forward',
2409
1630
help='Show from oldest to newest.'),
2411
custom_help('verbose',
1633
help='Display timezone as local, original, or utc.'),
2412
1636
help='Show files changed in each revision.'),
2416
type=bzrlib.option._parse_revision_str,
2418
help='Show just the specified revision.'
2419
' See also "help revisionspec".'),
2421
RegistryOption('authors',
2422
'What names to list as authors - first, all or committer.',
2424
lazy_registry=('bzrlib.log', 'author_list_registry'),
2428
help='Number of levels to display - 0 for all, 1 for flat.',
2430
type=_parse_levels),
2431
1640
Option('message',
2432
1642
help='Show revisions whose message matches this '
2433
1643
'regular expression.',
2436
1645
Option('limit',
2438
1646
help='Limit the output to the first N revisions.',
2440
1648
type=_parse_limit),
2443
help='Show changes made in each revision as a patch.'),
2444
Option('include-merged',
2445
help='Show merged revisions like --levels 0 does.'),
2446
Option('include-merges', hidden=True,
2447
help='Historical alias for --include-merged.'),
2448
Option('omit-merges',
2449
help='Do not report commits with more than one parent.'),
2450
Option('exclude-common-ancestry',
2451
help='Display only the revisions that are not part'
2452
' of both ancestries (require -rX..Y)'
2454
Option('signatures',
2455
help='Show digital signature validity'),
2458
help='Show revisions whose properties match this '
2461
ListOption('match-message',
2462
help='Show revisions whose message matches this '
2465
ListOption('match-committer',
2466
help='Show revisions whose committer matches this '
2469
ListOption('match-author',
2470
help='Show revisions whose authors match this '
2473
ListOption('match-bugs',
2474
help='Show revisions whose bugs match this '
2478
1650
encoding_type = 'replace'
2480
1652
@display_command
2481
def run(self, file_list=None, timezone='original',
1653
def run(self, location=None, timezone='original',
2483
1655
show_ids=False,
2487
1658
log_format=None,
2492
include_merged=None,
2494
exclude_common_ancestry=False,
2498
match_committer=None,
2502
include_merges=symbol_versioning.DEPRECATED_PARAMETER,
2504
from bzrlib.log import (
2506
make_log_request_dict,
2507
_get_info_for_log_files,
1661
from bzrlib.log import show_log
1662
assert message is None or isinstance(message, basestring), \
1663
"invalid message argument %r" % message
2509
1664
direction = (forward and 'forward') or 'reverse'
2510
if symbol_versioning.deprecated_passed(include_merges):
2511
ui.ui_factory.show_user_warning(
2512
'deprecated_command_option',
2513
deprecated_name='--include-merges',
2514
recommended_name='--include-merged',
2515
deprecated_in_version='2.5',
2516
command=self.invoked_as)
2517
if include_merged is None:
2518
include_merged = include_merges
2520
raise errors.BzrCommandError(gettext(
2521
'{0} and {1} are mutually exclusive').format(
2522
'--include-merges', '--include-merged'))
2523
if include_merged is None:
2524
include_merged = False
2525
if (exclude_common_ancestry
2526
and (revision is None or len(revision) != 2)):
2527
raise errors.BzrCommandError(gettext(
2528
'--exclude-common-ancestry requires -r with two revisions'))
2533
raise errors.BzrCommandError(gettext(
2534
'{0} and {1} are mutually exclusive').format(
2535
'--levels', '--include-merged'))
2537
if change is not None:
2539
raise errors.RangeInChangeOption()
2540
if revision is not None:
2541
raise errors.BzrCommandError(gettext(
2542
'{0} and {1} are mutually exclusive').format(
2543
'--revision', '--change'))
2548
filter_by_dir = False
2550
# find the file ids to log and check for directory filtering
2551
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2552
revision, file_list, self.add_cleanup)
2553
for relpath, file_id, kind in file_info_list:
1669
# find the file id to log:
1671
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1675
tree = b.basis_tree()
1676
file_id = tree.path2id(fp)
2554
1677
if file_id is None:
2555
raise errors.BzrCommandError(gettext(
2556
"Path unknown at end or start of revision range: %s") %
2558
# If the relpath is the top of the tree, we log everything
2563
file_ids.append(file_id)
2564
filter_by_dir = filter_by_dir or (
2565
kind in ['directory', 'tree-reference'])
1678
raise errors.BzrCommandError(
1679
"Path does not have any revision history: %s" %
2568
# FIXME ? log the current subdir only RBC 20060203
1683
# FIXME ? log the current subdir only RBC 20060203
2569
1684
if revision is not None \
2570
1685
and len(revision) > 0 and revision[0].get_branch():
2571
1686
location = revision[0].get_branch()
2722
1752
@display_command
2723
1753
def run(self, filename):
2724
1754
tree, relpath = WorkingTree.open_containing(filename)
2725
1756
file_id = tree.path2id(relpath)
2727
self.add_cleanup(b.lock_read().unlock)
2728
touching_revs = log.find_touching_revisions(b, file_id)
2729
for revno, revision_id, what in touching_revs:
1757
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2730
1758
self.outf.write("%6d %s\n" % (revno, what))
2733
1761
class cmd_ls(Command):
2734
__doc__ = """List files in a tree.
1762
"""List files in a tree.
2737
1765
_see_also = ['status', 'cat']
2738
1766
takes_args = ['path?']
1767
# TODO: Take a revision or remote path and list that tree instead.
2739
1768
takes_options = [
2742
Option('recursive', short_name='R',
2743
help='Recurse into subdirectories.'),
1771
Option('non-recursive',
1772
help='Don\'t recurse into subdirectories.'),
2744
1773
Option('from-root',
2745
1774
help='Print paths relative to the root of the branch.'),
2746
Option('unknown', short_name='u',
2747
help='Print unknown files.'),
2748
Option('versioned', help='Print versioned files.',
2750
Option('ignored', short_name='i',
2751
help='Print ignored files.'),
2752
Option('kind', short_name='k',
1775
Option('unknown', help='Print unknown files.'),
1776
Option('versioned', help='Print versioned files.'),
1777
Option('ignored', help='Print ignored files.'),
1779
help='Write an ascii NUL (\\0) separator '
1780
'between files rather than a newline.'),
2753
1782
help='List entries of a particular kind: file, directory, symlink.',
2759
1786
@display_command
2760
1787
def run(self, revision=None, verbose=False,
2761
recursive=False, from_root=False,
1788
non_recursive=False, from_root=False,
2762
1789
unknown=False, versioned=False, ignored=False,
2763
null=False, kind=None, show_ids=False, path=None, directory=None):
1790
null=False, kind=None, show_ids=False, path=None):
2765
1792
if kind and kind not in ('file', 'directory', 'symlink'):
2766
raise errors.BzrCommandError(gettext('invalid kind specified'))
1793
raise errors.BzrCommandError('invalid kind specified')
2768
1795
if verbose and null:
2769
raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
1796
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2770
1797
all = not (unknown or versioned or ignored)
2772
1799
selection = {'I':ignored, '?':unknown, 'V':versioned}
2774
1801
if path is None:
2778
raise errors.BzrCommandError(gettext('cannot specify both --from-root'
1806
raise errors.BzrCommandError('cannot specify both --from-root'
2781
tree, branch, relpath = \
2782
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2784
# Calculate the prefix to use
1810
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2788
prefix = relpath + '/'
2789
elif fs_path != '.' and not fs_path.endswith('/'):
2790
prefix = fs_path + '/'
2792
if revision is not None or tree is None:
2793
tree = _get_one_revision_tree('ls', revision, branch=branch)
2796
if isinstance(tree, WorkingTree) and tree.supports_views():
2797
view_files = tree.views.lookup_view()
2800
view_str = views.view_display_str(view_files)
2801
note(gettext("Ignoring files outside view. View is %s") % view_str)
2803
self.add_cleanup(tree.lock_read().unlock)
2804
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2805
from_dir=relpath, recursive=recursive):
2806
# Apply additional masking
2807
if not all and not selection[fc]:
2809
if kind is not None and fkind != kind:
2814
fullpath = osutils.pathjoin(relpath, fp)
2817
views.check_path_in_view(tree, fullpath)
2818
except errors.FileOutsideView:
2823
fp = osutils.pathjoin(prefix, fp)
2824
kindch = entry.kind_character()
2825
outstring = fp + kindch
2826
ui.ui_factory.clear_term()
2828
outstring = '%-8s %s' % (fc, outstring)
2829
if show_ids and fid is not None:
2830
outstring = "%-50s %s" % (outstring, fid)
2831
self.outf.write(outstring + '\n')
2833
self.outf.write(fp + '\0')
2836
self.outf.write(fid)
2837
self.outf.write('\0')
2845
self.outf.write('%-50s %s\n' % (outstring, my_id))
2847
self.outf.write(outstring + '\n')
1816
if revision is not None:
1817
tree = branch.repository.revision_tree(
1818
revision[0].in_history(branch).rev_id)
1820
tree = branch.basis_tree()
1824
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1825
if fp.startswith(relpath):
1826
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1827
if non_recursive and '/' in fp:
1829
if not all and not selection[fc]:
1831
if kind is not None and fkind != kind:
1834
kindch = entry.kind_character()
1835
outstring = '%-8s %s%s' % (fc, fp, kindch)
1836
if show_ids and fid is not None:
1837
outstring = "%-50s %s" % (outstring, fid)
1838
self.outf.write(outstring + '\n')
1840
self.outf.write(fp + '\0')
1843
self.outf.write(fid)
1844
self.outf.write('\0')
1852
self.outf.write('%-50s %s\n' % (fp, my_id))
1854
self.outf.write(fp + '\n')
2850
1859
class cmd_unknowns(Command):
2851
__doc__ = """List unknown files.
1860
"""List unknown files.
2855
1864
_see_also = ['ls']
2856
takes_options = ['directory']
2858
1866
@display_command
2859
def run(self, directory=u'.'):
2860
for f in WorkingTree.open_containing(directory)[0].unknowns():
1868
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2861
1869
self.outf.write(osutils.quotefn(f) + '\n')
2864
1872
class cmd_ignore(Command):
2865
__doc__ = """Ignore specified files or patterns.
2867
See ``bzr help patterns`` for details on the syntax of patterns.
2869
If a .bzrignore file does not exist, the ignore command
2870
will create one and add the specified files or patterns to the newly
2871
created file. The ignore command will also automatically add the
2872
.bzrignore file to be versioned. Creating a .bzrignore file without
2873
the use of the ignore command will require an explicit add command.
1873
"""Ignore specified files or patterns.
2875
1875
To remove patterns from the ignore list, edit the .bzrignore file.
2876
After adding, editing or deleting that file either indirectly by
2877
using this command or directly by using an editor, be sure to commit
2880
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2881
the global ignore file can be found in the application data directory as
2882
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2883
Global ignores are not touched by this command. The global ignore file
2884
can be edited directly using an editor.
2886
Patterns prefixed with '!' are exceptions to ignore patterns and take
2887
precedence over regular ignores. Such exceptions are used to specify
2888
files that should be versioned which would otherwise be ignored.
2890
Patterns prefixed with '!!' act as regular ignore patterns, but have
2891
precedence over the '!' exception patterns.
2895
* Ignore patterns containing shell wildcards must be quoted from
2898
* Ignore patterns starting with "#" act as comments in the ignore file.
2899
To ignore patterns that begin with that character, use the "RE:" prefix.
1877
Trailing slashes on patterns are ignored.
1878
If the pattern contains a slash or is a regular expression, it is compared
1879
to the whole path from the branch root. Otherwise, it is compared to only
1880
the last component of the path. To match a file only in the root
1881
directory, prepend './'.
1883
Ignore patterns specifying absolute paths are not allowed.
1885
Ignore patterns may include globbing wildcards such as::
1887
? - Matches any single character except '/'
1888
* - Matches 0 or more characters except '/'
1889
/**/ - Matches 0 or more directories in a path
1890
[a-z] - Matches a single character from within a group of characters
1892
Ignore patterns may also be Python regular expressions.
1893
Regular expression ignore patterns are identified by a 'RE:' prefix
1894
followed by the regular expression. Regular expression ignore patterns
1895
may not include named or numbered groups.
1897
Note: ignore patterns containing shell wildcards must be quoted from
2902
1901
Ignore the top level Makefile::
2904
1903
bzr ignore ./Makefile
2906
Ignore .class files in all directories...::
2908
bzr ignore "*.class"
2910
...but do not ignore "special.class"::
2912
bzr ignore "!special.class"
2914
Ignore files whose name begins with the "#" character::
2918
Ignore .o files under the lib directory::
2920
bzr ignore "lib/**/*.o"
2922
Ignore .o files under the lib directory::
2924
bzr ignore "RE:lib/.*\.o"
2926
Ignore everything but the "debian" toplevel directory::
2928
bzr ignore "RE:(?!debian/).*"
2930
Ignore everything except the "local" toplevel directory,
2931
but always ignore autosave files ending in ~, even under local/::
2934
bzr ignore "!./local"
1905
Ignore class files in all directories::
1907
bzr ignore '*.class'
1909
Ignore .o files under the lib directory::
1911
bzr ignore 'lib/**/*.o'
1913
Ignore .o files under the lib directory::
1915
bzr ignore 'RE:lib/.*\.o'
2938
_see_also = ['status', 'ignored', 'patterns']
1918
_see_also = ['status', 'ignored']
2939
1919
takes_args = ['name_pattern*']
2940
takes_options = ['directory',
2941
Option('default-rules',
2942
help='Display the default ignore rules that bzr uses.')
1921
Option('old-default-rules',
1922
help='Write out the ignore rules bzr < 0.9 always used.')
2945
def run(self, name_pattern_list=None, default_rules=None,
2947
from bzrlib import ignores
2948
if default_rules is not None:
2949
# dump the default rules and exit
2950
for pattern in ignores.USER_DEFAULTS:
2951
self.outf.write("%s\n" % pattern)
1925
def run(self, name_pattern_list=None, old_default_rules=None):
1926
from bzrlib.atomicfile import AtomicFile
1927
if old_default_rules is not None:
1928
# dump the rules and exit
1929
for pattern in ignores.OLD_DEFAULTS:
2953
1932
if not name_pattern_list:
2954
raise errors.BzrCommandError(gettext("ignore requires at least one "
2955
"NAME_PATTERN or --default-rules."))
2956
name_pattern_list = [globbing.normalize_pattern(p)
1933
raise errors.BzrCommandError("ignore requires at least one "
1934
"NAME_PATTERN or --old-default-rules")
1935
name_pattern_list = [globbing.normalize_pattern(p)
2957
1936
for p in name_pattern_list]
2959
bad_patterns_count = 0
2960
for p in name_pattern_list:
2961
if not globbing.Globster.is_pattern_valid(p):
2962
bad_patterns_count += 1
2963
bad_patterns += ('\n %s' % p)
2965
msg = (ngettext('Invalid ignore pattern found. %s',
2966
'Invalid ignore patterns found. %s',
2967
bad_patterns_count) % bad_patterns)
2968
ui.ui_factory.show_error(msg)
2969
raise errors.InvalidPattern('')
2970
1937
for name_pattern in name_pattern_list:
2971
if (name_pattern[0] == '/' or
1938
if (name_pattern[0] == '/' or
2972
1939
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2973
raise errors.BzrCommandError(gettext(
2974
"NAME_PATTERN should not be an absolute path"))
2975
tree, relpath = WorkingTree.open_containing(directory)
2976
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2977
ignored = globbing.Globster(name_pattern_list)
2979
self.add_cleanup(tree.lock_read().unlock)
2980
for entry in tree.list_files():
2984
if ignored.match(filename):
2985
matches.append(filename)
2986
if len(matches) > 0:
2987
self.outf.write(gettext("Warning: the following files are version "
2988
"controlled and match your ignore pattern:\n%s"
2989
"\nThese files will continue to be version controlled"
2990
" unless you 'bzr remove' them.\n") % ("\n".join(matches),))
1940
raise errors.BzrCommandError(
1941
"NAME_PATTERN should not be an absolute path")
1942
tree, relpath = WorkingTree.open_containing(u'.')
1943
ifn = tree.abspath('.bzrignore')
1944
if os.path.exists(ifn):
1947
igns = f.read().decode('utf-8')
1953
# TODO: If the file already uses crlf-style termination, maybe
1954
# we should use that for the newly added lines?
1956
if igns and igns[-1] != '\n':
1958
for name_pattern in name_pattern_list:
1959
igns += name_pattern + '\n'
1961
f = AtomicFile(ifn, 'wb')
1963
f.write(igns.encode('utf-8'))
1968
if not tree.path2id('.bzrignore'):
1969
tree.add(['.bzrignore'])
2993
1972
class cmd_ignored(Command):
2994
__doc__ = """List ignored files and the patterns that matched them.
2996
List all the ignored files and the ignore pattern that caused the file to
2999
Alternatively, to list just the files::
1973
"""List ignored files and the patterns that matched them.
3004
encoding_type = 'replace'
3005
_see_also = ['ignore', 'ls']
3006
takes_options = ['directory']
1976
_see_also = ['ignore']
3008
1977
@display_command
3009
def run(self, directory=u'.'):
3010
tree = WorkingTree.open_containing(directory)[0]
3011
self.add_cleanup(tree.lock_read().unlock)
3012
for path, file_class, kind, file_id, entry in tree.list_files():
3013
if file_class != 'I':
3015
## XXX: Slightly inefficient since this was already calculated
3016
pat = tree.is_ignored(path)
3017
self.outf.write('%-50s %s\n' % (path, pat))
1979
tree = WorkingTree.open_containing(u'.')[0]
1982
for path, file_class, kind, file_id, entry in tree.list_files():
1983
if file_class != 'I':
1985
## XXX: Slightly inefficient since this was already calculated
1986
pat = tree.is_ignored(path)
1987
print '%-50s %s' % (path, pat)
3020
1992
class cmd_lookup_revision(Command):
3021
__doc__ = """Lookup the revision-id from a revision-number
1993
"""Lookup the revision-id from a revision-number
3024
1996
bzr lookup-revision 33
3027
1999
takes_args = ['revno']
3028
takes_options = ['directory']
3030
2001
@display_command
3031
def run(self, revno, directory=u'.'):
2002
def run(self, revno):
3033
2004
revno = int(revno)
3034
2005
except ValueError:
3035
raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
3037
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
3038
self.outf.write("%s\n" % revid)
2006
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2008
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3041
2011
class cmd_export(Command):
3042
__doc__ = """Export current or past revision to a destination directory or archive.
2012
"""Export current or past revision to a destination directory or archive.
3044
2014
If no revision is specified this exports the last committed revision.
3067
2037
================= =========================
3070
takes_args = ['dest', 'branch_or_subdir?']
3071
takes_options = ['directory',
2039
takes_args = ['dest', 'branch?']
3072
2041
Option('format',
3073
2042
help="Type of file to export to.",
3076
Option('filters', help='Apply content filters to export the '
3077
'convenient form.'),
3080
2047
help="Name of the root directory inside the exported file."),
3081
Option('per-file-timestamps',
3082
help='Set modification time of files to that of the last '
3083
'revision in which it was changed.'),
3085
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
3086
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2049
def run(self, dest, branch=None, revision=None, format=None, root=None):
3087
2050
from bzrlib.export import export
3089
if branch_or_subdir is None:
3090
tree = WorkingTree.open_containing(directory)[0]
2053
tree = WorkingTree.open_containing(u'.')[0]
3091
2054
b = tree.branch
3094
b, subdir = Branch.open_containing(branch_or_subdir)
3097
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2056
b = Branch.open(branch)
2058
if revision is None:
2059
# should be tree.last_revision FIXME
2060
rev_id = b.last_revision()
2062
if len(revision) != 1:
2063
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2064
rev_id = revision[0].in_history(b).rev_id
2065
t = b.repository.revision_tree(rev_id)
3099
export(rev_tree, dest, format, root, subdir, filtered=filters,
3100
per_file_timestamps=per_file_timestamps)
2067
export(t, dest, format, root)
3101
2068
except errors.NoSuchExportFormat, e:
3102
raise errors.BzrCommandError(gettext('Unsupported export format: %s') % e.format)
2069
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3105
2072
class cmd_cat(Command):
3106
__doc__ = """Write the contents of a file as of a given revision to standard output.
2073
"""Write the contents of a file as of a given revision to standard output.
3108
2075
If no revision is nominated, the last revision is used.
3110
2077
Note: Take care to redirect standard output when using this command on a
3114
2081
_see_also = ['ls']
3115
takes_options = ['directory',
3116
2083
Option('name-from-revision', help='The path name in the old tree.'),
3117
Option('filters', help='Apply content filters to display the '
3118
'convenience form.'),
3121
2086
takes_args = ['filename']
3122
2087
encoding_type = 'exact'
3124
2089
@display_command
3125
def run(self, filename, revision=None, name_from_revision=False,
3126
filters=False, directory=None):
2090
def run(self, filename, revision=None, name_from_revision=False):
3127
2091
if revision is not None and len(revision) != 1:
3128
raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3129
" one revision specifier"))
3130
tree, branch, relpath = \
3131
_open_directory_or_containing_tree_or_branch(filename, directory)
3132
self.add_cleanup(branch.lock_read().unlock)
3133
return self._run(tree, branch, relpath, filename, revision,
3134
name_from_revision, filters)
3136
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2092
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2097
tree, b, relpath = \
2098
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2099
except errors.NotBranchError:
2102
if revision is not None and revision[0].get_branch() is not None:
2103
b = Branch.open(revision[0].get_branch())
3138
2104
if tree is None:
3139
2105
tree = b.basis_tree()
3140
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3141
self.add_cleanup(rev_tree.lock_read().unlock)
2106
if revision is None:
2107
revision_id = b.last_revision()
2109
revision_id = revision[0].in_history(b).rev_id
2111
cur_file_id = tree.path2id(relpath)
2112
rev_tree = b.repository.revision_tree(revision_id)
3143
2113
old_file_id = rev_tree.path2id(relpath)
3145
# TODO: Split out this code to something that generically finds the
3146
# best id for a path across one or more trees; it's like
3147
# find_ids_across_trees but restricted to find just one. -- mbp
3149
2115
if name_from_revision:
3150
# Try in revision if requested
3151
2116
if old_file_id is None:
3152
raise errors.BzrCommandError(gettext(
3153
"{0!r} is not present in revision {1}").format(
3154
filename, rev_tree.get_revision_id()))
3156
actual_file_id = old_file_id
3158
cur_file_id = tree.path2id(relpath)
3159
if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3160
actual_file_id = cur_file_id
3161
elif old_file_id is not None:
3162
actual_file_id = old_file_id
3164
raise errors.BzrCommandError(gettext(
3165
"{0!r} is not present in revision {1}").format(
3166
filename, rev_tree.get_revision_id()))
3168
from bzrlib.filter_tree import ContentFilterTree
3169
filter_tree = ContentFilterTree(rev_tree,
3170
rev_tree._content_filter_stack)
3171
content = filter_tree.get_file_text(actual_file_id)
3173
content = rev_tree.get_file_text(actual_file_id)
3175
self.outf.write(content)
2117
raise errors.BzrCommandError("%r is not present in revision %s"
2118
% (filename, revision_id))
2120
rev_tree.print_file(old_file_id)
2121
elif cur_file_id is not None:
2122
rev_tree.print_file(cur_file_id)
2123
elif old_file_id is not None:
2124
rev_tree.print_file(old_file_id)
2126
raise errors.BzrCommandError("%r is not present in revision %s" %
2127
(filename, revision_id))
3178
2130
class cmd_local_time_offset(Command):
3179
__doc__ = """Show the offset in seconds from GMT to local time."""
2131
"""Show the offset in seconds from GMT to local time."""
3181
2133
@display_command
3183
self.outf.write("%s\n" % osutils.local_time_offset())
2135
print osutils.local_time_offset()
3187
2139
class cmd_commit(Command):
3188
__doc__ = """Commit changes into a new revision.
3190
An explanatory message needs to be given for each commit. This is
3191
often done by using the --message option (getting the message from the
3192
command line) or by using the --file option (getting the message from
3193
a file). If neither of these options is given, an editor is opened for
3194
the user to enter the message. To see the changed files in the
3195
boilerplate text loaded into the editor, use the --show-diff option.
3197
By default, the entire tree is committed and the person doing the
3198
commit is assumed to be the author. These defaults can be overridden
3203
If selected files are specified, only changes to those files are
3204
committed. If a directory is specified then the directory and
3205
everything within it is committed.
3207
When excludes are given, they take precedence over selected files.
3208
For example, to commit only changes within foo, but not changes
3211
bzr commit foo -x foo/bar
3213
A selective commit after a merge is not yet supported.
3217
If the author of the change is not the same person as the committer,
3218
you can specify the author's name using the --author option. The
3219
name should be in the same format as a committer-id, e.g.
3220
"John Doe <jdoe@example.com>". If there is more than one author of
3221
the change you can specify the option multiple times, once for each
3226
A common mistake is to forget to add a new file or directory before
3227
running the commit command. The --strict option checks for unknown
3228
files and aborts the commit if any are found. More advanced pre-commit
3229
checks can be implemented by defining hooks. See ``bzr help hooks``
3234
If you accidentially commit the wrong changes or make a spelling
3235
mistake in the commit message say, you can use the uncommit command
3236
to undo it. See ``bzr help uncommit`` for details.
3238
Hooks can also be configured to run after a commit. This allows you
3239
to trigger updates to external systems like bug trackers. The --fixes
3240
option can be used to record the association between a revision and
3241
one or more bugs. See ``bzr help bugs`` for details.
2140
"""Commit changes into a new revision.
2142
If no arguments are given, the entire tree is committed.
2144
If selected files are specified, only changes to those files are
2145
committed. If a directory is specified then the directory and everything
2146
within it is committed.
2148
A selected-file commit may fail in some cases where the committed
2149
tree would be invalid. Consider::
2154
bzr commit foo -m "committing foo"
2155
bzr mv foo/bar foo/baz
2158
bzr commit foo/bar -m "committing bar but not baz"
2160
In the example above, the last commit will fail by design. This gives
2161
the user the opportunity to decide whether they want to commit the
2162
rename at the same time, separately first, or not at all. (As a general
2163
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2165
Note: A selected-file commit after a merge is not yet supported.
3244
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
2167
# TODO: Run hooks on tree to-be-committed, and after commit.
2169
# TODO: Strict commit that fails if there are deleted files.
2170
# (what does "deleted files" mean ??)
2172
# TODO: Give better message for -s, --summary, used by tla people
2174
# XXX: verbose currently does nothing
2176
_see_also = ['bugs', 'uncommit']
3245
2177
takes_args = ['selected*']
3246
2178
takes_options = [
3247
ListOption('exclude', type=str, short_name='x',
3248
help="Do not consider changes made to a given path."),
3249
2179
Option('message', type=unicode,
3250
2180
short_name='m',
3251
2181
help="Description of the new revision."),
3259
2189
Option('strict',
3260
2190
help="Refuse to commit if there are unknown "
3261
2191
"files in the working tree."),
3262
Option('commit-time', type=str,
3263
help="Manually set a commit time using commit date "
3264
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3265
2192
ListOption('fixes', type=str,
3266
help="Mark a bug as being fixed by this revision "
3267
"(see \"bzr help bugs\")."),
3268
ListOption('author', type=unicode,
3269
help="Set the author's name, if it's different "
3270
"from the committer."),
2193
help="Mark a bug as being fixed by this revision."),
3271
2194
Option('local',
3272
2195
help="Perform a local commit in a bound "
3273
2196
"branch. Local commits are not pushed to "
3274
2197
"the master branch until a normal commit "
3275
2198
"is performed."
3277
Option('show-diff', short_name='p',
3278
help='When no message is supplied, show the diff along'
3279
' with the status summary in the message editor.'),
3281
help='When committing to a foreign version control '
3282
'system do not push data that can not be natively '
3285
2201
aliases = ['ci', 'checkin']
3287
def _iter_bug_fix_urls(self, fixes, branch):
3288
default_bugtracker = None
2203
def _get_bug_fix_properties(self, fixes, branch):
3289
2205
# Configure the properties for bug fixing attributes.
3290
2206
for fixed_bug in fixes:
3291
2207
tokens = fixed_bug.split(':')
3292
if len(tokens) == 1:
3293
if default_bugtracker is None:
3294
branch_config = branch.get_config()
3295
default_bugtracker = branch_config.get_user_option(
3297
if default_bugtracker is None:
3298
raise errors.BzrCommandError(gettext(
3299
"No tracker specified for bug %s. Use the form "
3300
"'tracker:id' or specify a default bug tracker "
3301
"using the `bugtracker` option.\nSee "
3302
"\"bzr help bugs\" for more information on this "
3303
"feature. Commit refused.") % fixed_bug)
3304
tag = default_bugtracker
3306
elif len(tokens) != 2:
3307
raise errors.BzrCommandError(gettext(
3308
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3309
"See \"bzr help bugs\" for more information on this "
3310
"feature.\nCommit refused.") % fixed_bug)
3312
tag, bug_id = tokens
2208
if len(tokens) != 2:
2209
raise errors.BzrCommandError(
2210
"Invalid bug %s. Must be in the form of 'tag:id'. "
2211
"Commit refused." % fixed_bug)
2212
tag, bug_id = tokens
3314
yield bugtracker.get_bug_url(tag, branch, bug_id)
2214
bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
3315
2215
except errors.UnknownBugTrackerAbbreviation:
3316
raise errors.BzrCommandError(gettext(
3317
'Unrecognized bug %s. Commit refused.') % fixed_bug)
3318
except errors.MalformedBugIdentifier, e:
3319
raise errors.BzrCommandError(gettext(
3320
"%s\nCommit refused.") % (str(e),))
3322
def run(self, message=None, file=None, verbose=False, selected_list=None,
3323
unchanged=False, strict=False, local=False, fixes=None,
3324
author=None, show_diff=False, exclude=None, commit_time=None,
3326
from bzrlib.errors import (
3331
from bzrlib.msgeditor import (
3332
edit_commit_message_encoded,
3333
generate_commit_message_template,
3334
make_commit_message_template_encoded,
3338
commit_stamp = offset = None
3339
if commit_time is not None:
3341
commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3342
except ValueError, e:
3343
raise errors.BzrCommandError(gettext(
3344
"Could not parse --commit-time: " + str(e)))
2216
raise errors.BzrCommandError(
2217
'Unrecognized bug %s. Commit refused.' % fixed_bug)
2218
except errors.MalformedBugIdentifier:
2219
raise errors.BzrCommandError(
2220
"Invalid bug identifier for %s. Commit refused."
2222
properties.append('%s fixed' % bug_url)
2223
return '\n'.join(properties)
2225
def run(self, message=None, file=None, verbose=True, selected_list=None,
2226
unchanged=False, strict=False, local=False, fixes=None):
2227
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2228
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2230
from bzrlib.msgeditor import edit_commit_message, \
2231
make_commit_message_template
2233
# TODO: Need a blackbox test for invoking the external editor; may be
2234
# slightly problematic to run this cross-platform.
2236
# TODO: do more checks that the commit will succeed before
2237
# spending the user's valuable time typing a commit message.
3346
2239
properties = {}
3348
tree, selected_list = WorkingTree.open_containing_paths(selected_list)
2241
tree, selected_list = tree_files(selected_list)
3349
2242
if selected_list == ['']:
3350
2243
# workaround - commit of root of tree should be exactly the same
3351
2244
# as just default commit in that tree, and succeed even though
3352
2245
# selected-file merge commit is not done yet
3353
2246
selected_list = []
3357
bug_property = bugtracker.encode_fixes_bug_urls(
3358
self._iter_bug_fix_urls(fixes, tree.branch))
2248
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
3359
2249
if bug_property:
3360
2250
properties['bugs'] = bug_property
3362
2252
if local and not tree.branch.get_bound_location():
3363
2253
raise errors.LocalRequiresBoundBranch()
3365
if message is not None:
3367
file_exists = osutils.lexists(message)
3368
except UnicodeError:
3369
# The commit message contains unicode characters that can't be
3370
# represented in the filesystem encoding, so that can't be a
3375
'The commit message is a file name: "%(f)s".\n'
3376
'(use --file "%(f)s" to take commit message from that file)'
3378
ui.ui_factory.show_warning(warning_msg)
3380
message = message.replace('\r\n', '\n')
3381
message = message.replace('\r', '\n')
3383
raise errors.BzrCommandError(gettext(
3384
"please specify either --message or --file"))
3386
2255
def get_message(commit_obj):
3387
2256
"""Callback to get commit message"""
2257
my_message = message
2258
if my_message is None and not file:
2259
template = make_commit_message_template(tree, selected_list)
2260
my_message = edit_commit_message(template)
2261
if my_message is None:
2262
raise errors.BzrCommandError("please specify a commit"
2263
" message with either --message or --file")
2264
elif my_message and file:
2265
raise errors.BzrCommandError(
2266
"please specify either --message or --file")
3391
my_message = f.read().decode(osutils.get_user_encoding())
3394
elif message is not None:
3395
my_message = message
3397
# No message supplied: make one up.
3398
# text is the status of the tree
3399
text = make_commit_message_template_encoded(tree,
3400
selected_list, diff=show_diff,
3401
output_encoding=osutils.get_user_encoding())
3402
# start_message is the template generated from hooks
3403
# XXX: Warning - looks like hooks return unicode,
3404
# make_commit_message_template_encoded returns user encoding.
3405
# We probably want to be using edit_commit_message instead to
3407
my_message = set_commit_message(commit_obj)
3408
if my_message is None:
3409
start_message = generate_commit_message_template(commit_obj)
3410
my_message = edit_commit_message_encoded(text,
3411
start_message=start_message)
3412
if my_message is None:
3413
raise errors.BzrCommandError(gettext("please specify a commit"
3414
" message with either --message or --file"))
3415
if my_message == "":
3416
raise errors.BzrCommandError(gettext("Empty commit message specified."
3417
" Please specify a commit message with either"
3418
" --message or --file or leave a blank message"
3419
" with --message \"\"."))
2268
my_message = codecs.open(file, 'rt',
2269
bzrlib.user_encoding).read()
2270
if my_message == "":
2271
raise errors.BzrCommandError("empty commit message specified")
3420
2272
return my_message
3422
# The API permits a commit with a filter of [] to mean 'select nothing'
3423
# but the command line should not do that.
3424
if not selected_list:
3425
selected_list = None
2275
reporter = ReportCommitToLog()
2277
reporter = NullCommitReporter()
3427
2280
tree.commit(message_callback=get_message,
3428
2281
specific_files=selected_list,
3429
2282
allow_pointless=unchanged, strict=strict, local=local,
3430
reporter=None, verbose=verbose, revprops=properties,
3431
authors=author, timestamp=commit_stamp,
3433
exclude=tree.safe_relpath_files(exclude),
2283
reporter=reporter, revprops=properties)
3435
2284
except PointlessCommit:
3436
raise errors.BzrCommandError(gettext("No changes to commit."
3437
" Please 'bzr add' the files you want to commit, or use"
3438
" --unchanged to force an empty commit."))
2285
# FIXME: This should really happen before the file is read in;
2286
# perhaps prepare the commit; get the message; then actually commit
2287
raise errors.BzrCommandError("no changes to commit."
2288
" use --unchanged to commit anyhow")
3439
2289
except ConflictsInTree:
3440
raise errors.BzrCommandError(gettext('Conflicts detected in working '
2290
raise errors.BzrCommandError('Conflicts detected in working '
3441
2291
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
3443
2293
except StrictCommitFailed:
3444
raise errors.BzrCommandError(gettext("Commit refused because there are"
3445
" unknown files in the working tree."))
2294
raise errors.BzrCommandError("Commit refused because there are"
2295
" unknown files in the working tree.")
3446
2296
except errors.BoundBranchOutOfDate, e:
3447
e.extra_help = (gettext("\n"
3448
'To commit to master branch, run update and then commit.\n'
3449
'You can also pass --local to commit to continue working '
2297
raise errors.BzrCommandError(str(e) + "\n"
2298
'To commit to master branch, run update and then commit.\n'
2299
'You can also pass --local to commit to continue working '
3454
2303
class cmd_check(Command):
3455
__doc__ = """Validate working tree structure, branch consistency and repository history.
3457
This command checks various invariants about branch and repository storage
3458
to detect data corruption or bzr bugs.
3460
The working tree and branch checks will only give output if a problem is
3461
detected. The output fields of the repository check are:
3464
This is just the number of revisions checked. It doesn't
3468
This is just the number of versionedfiles checked. It
3469
doesn't indicate a problem.
3471
unreferenced ancestors
3472
Texts that are ancestors of other texts, but
3473
are not properly referenced by the revision ancestry. This is a
3474
subtle problem that Bazaar can work around.
3477
This is the total number of unique file contents
3478
seen in the checked revisions. It does not indicate a problem.
3481
This is the total number of repeated texts seen
3482
in the checked revisions. Texts can be repeated when their file
3483
entries are modified, but the file contents are not. It does not
3486
If no restrictions are specified, all Bazaar data that is found at the given
3487
location will be checked.
3491
Check the tree and branch at 'foo'::
3493
bzr check --tree --branch foo
3495
Check only the repository at 'bar'::
3497
bzr check --repo bar
3499
Check everything at 'baz'::
2304
"""Validate consistency of branch history.
2306
This command checks various invariants about the branch storage to
2307
detect data corruption or bzr bugs.
3504
2310
_see_also = ['reconcile']
3505
takes_args = ['path?']
3506
takes_options = ['verbose',
3507
Option('branch', help="Check the branch related to the"
3508
" current directory."),
3509
Option('repo', help="Check the repository related to the"
3510
" current directory."),
3511
Option('tree', help="Check the working tree related to"
3512
" the current directory.")]
2311
takes_args = ['branch?']
2312
takes_options = ['verbose']
3514
def run(self, path=None, verbose=False, branch=False, repo=False,
3516
from bzrlib.check import check_dwim
3519
if not branch and not repo and not tree:
3520
branch = repo = tree = True
3521
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2314
def run(self, branch=None, verbose=False):
2315
from bzrlib.check import check
2317
tree = WorkingTree.open_containing()[0]
2318
branch = tree.branch
2320
branch = Branch.open(branch)
2321
check(branch, verbose)
3524
2324
class cmd_upgrade(Command):
3525
__doc__ = """Upgrade a repository, branch or working tree to a newer format.
3527
When the default format has changed after a major new release of
3528
Bazaar, you may be informed during certain operations that you
3529
should upgrade. Upgrading to a newer format may improve performance
3530
or make new features available. It may however limit interoperability
3531
with older repositories or with older versions of Bazaar.
3533
If you wish to upgrade to a particular format rather than the
3534
current default, that can be specified using the --format option.
3535
As a consequence, you can use the upgrade command this way to
3536
"downgrade" to an earlier format, though some conversions are
3537
a one way process (e.g. changing from the 1.x default to the
3538
2.x default) so downgrading is not always possible.
3540
A backup.bzr.~#~ directory is created at the start of the conversion
3541
process (where # is a number). By default, this is left there on
3542
completion. If the conversion fails, delete the new .bzr directory
3543
and rename this one back in its place. Use the --clean option to ask
3544
for the backup.bzr directory to be removed on successful conversion.
3545
Alternatively, you can delete it by hand if everything looks good
3548
If the location given is a shared repository, dependent branches
3549
are also converted provided the repository converts successfully.
3550
If the conversion of a branch fails, remaining branches are still
3553
For more information on upgrades, see the Bazaar Upgrade Guide,
3554
http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
2325
"""Upgrade branch storage to current format.
2327
The check command or bzr developers may sometimes advise you to run
2328
this command. When the default format has changed you may also be warned
2329
during other operations to upgrade.
3557
_see_also = ['check', 'reconcile', 'formats']
2332
_see_also = ['check']
3558
2333
takes_args = ['url?']
3559
2334
takes_options = [
3560
RegistryOption('format',
3561
help='Upgrade to a specific format. See "bzr help'
3562
' formats" for details.',
3563
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3564
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3565
value_switches=True, title='Branch format'),
3567
help='Remove the backup.bzr directory if successful.'),
3569
help="Show what would be done, but don't actually do anything."),
2335
RegistryOption('format',
2336
help='Upgrade to a specific format. See "bzr help'
2337
' formats" for details.',
2338
registry=bzrdir.format_registry,
2339
converter=bzrdir.format_registry.make_bzrdir,
2340
value_switches=True, title='Branch format'),
3572
def run(self, url='.', format=None, clean=False, dry_run=False):
2343
def run(self, url='.', format=None):
3573
2344
from bzrlib.upgrade import upgrade
3574
exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
3576
if len(exceptions) == 1:
3577
# Compatibility with historical behavior
2346
format = bzrdir.format_registry.make_bzrdir('default')
2347
upgrade(url, format)
3583
2350
class cmd_whoami(Command):
3584
__doc__ = """Show or set bzr user id.
2351
"""Show or set bzr user id.
3587
2354
Show the email of the current user::
3814
2490
'throughout the test suite.',
3815
2491
type=get_transport_type),
3816
2492
Option('benchmark',
3817
help='Run the benchmarks rather than selftests.',
2493
help='Run the benchmarks rather than selftests.'),
3819
2494
Option('lsprof-timed',
3820
2495
help='Generate lsprof output for benchmarked'
3821
2496
' sections of code.'),
3822
Option('lsprof-tests',
3823
help='Generate lsprof output for each test.'),
2497
Option('cache-dir', type=str,
2498
help='Cache intermediate benchmark output in this '
3824
2500
Option('first',
3825
2501
help='Run all tests, but run specified tests first.',
3826
2502
short_name='f',
3828
2504
Option('list-only',
3829
2505
help='List the tests instead of running them.'),
3830
RegistryOption('parallel',
3831
help="Run the test suite in parallel.",
3832
lazy_registry=('bzrlib.tests', 'parallel_registry'),
3833
value_switches=False,
3835
2506
Option('randomize', type=str, argname="SEED",
3836
2507
help='Randomize the order of tests using the given'
3837
2508
' seed or "now" for the current time.'),
3838
ListOption('exclude', type=str, argname="PATTERN",
3840
help='Exclude tests that match this regular'
3843
help='Output test progress via subunit.'),
2509
Option('exclude', type=str, argname="PATTERN",
2511
help='Exclude tests that match this regular'
3844
2513
Option('strict', help='Fail on missing dependencies or '
3845
2514
'known failures.'),
3846
Option('load-list', type=str, argname='TESTLISTFILE',
3847
help='Load a test id list from a text file.'),
3848
ListOption('debugflag', type=str, short_name='E',
3849
help='Turn on a selftest debug flag.'),
3850
ListOption('starting-with', type=str, argname='TESTID',
3851
param_name='starting_with', short_name='s',
3853
'Load only the tests starting with TESTID.'),
3855
help="By default we disable fsync and fdatasync"
3856
" while running the test suite.")
3858
2516
encoding_type = 'replace'
3861
Command.__init__(self)
3862
self.additional_selftest_args = {}
3864
def run(self, testspecs_list=None, verbose=False, one=False,
2518
def run(self, testspecs_list=None, verbose=None, one=False,
3865
2519
transport=None, benchmark=None,
2520
lsprof_timed=None, cache_dir=None,
3867
2521
first=False, list_only=False,
3868
randomize=None, exclude=None, strict=False,
3869
load_list=None, debugflag=None, starting_with=None, subunit=False,
3870
parallel=None, lsprof_tests=False,
3872
from bzrlib import tests
2522
randomize=None, exclude=None, strict=False):
2524
from bzrlib.tests import selftest
2525
import bzrlib.benchmarks as benchmarks
2526
from bzrlib.benchmarks import tree_creator
2527
from bzrlib.version import show_version
2529
if cache_dir is not None:
2530
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2532
show_version(show_config=False, show_copyright=False)
3874
2534
if testspecs_list is not None:
3875
2535
pattern = '|'.join(testspecs_list)
3880
from bzrlib.tests import SubUnitBzrRunner
3882
raise errors.BzrCommandError(gettext("subunit not available. subunit "
3883
"needs to be installed to use --subunit."))
3884
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3885
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3886
# stdout, which would corrupt the subunit stream.
3887
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3888
# following code can be deleted when it's sufficiently deployed
3889
# -- vila/mgz 20100514
3890
if (sys.platform == "win32"
3891
and getattr(sys.stdout, 'fileno', None) is not None):
3893
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3895
self.additional_selftest_args.setdefault(
3896
'suite_decorators', []).append(parallel)
3898
raise errors.BzrCommandError(gettext(
3899
"--benchmark is no longer supported from bzr 2.2; "
3900
"use bzr-usertest instead"))
3901
test_suite_factory = None
3903
exclude_pattern = None
2539
test_suite_factory = benchmarks.test_suite
2542
# TODO: should possibly lock the history file...
2543
benchfile = open(".perf_history", "at", buffering=1)
3905
exclude_pattern = '(' + '|'.join(exclude) + ')'
3907
self._disable_fsync()
3908
selftest_kwargs = {"verbose": verbose,
3910
"stop_on_failure": one,
3911
"transport": transport,
3912
"test_suite_factory": test_suite_factory,
3913
"lsprof_timed": lsprof_timed,
3914
"lsprof_tests": lsprof_tests,
3915
"matching_tests_first": first,
3916
"list_only": list_only,
3917
"random_seed": randomize,
3918
"exclude_pattern": exclude_pattern,
3920
"load_list": load_list,
3921
"debug_flags": debugflag,
3922
"starting_with": starting_with
3924
selftest_kwargs.update(self.additional_selftest_args)
3926
# Make deprecation warnings visible, unless -Werror is set
3927
cleanup = symbol_versioning.activate_deprecation_warnings(
2545
test_suite_factory = None
3930
result = tests.selftest(**selftest_kwargs)
2550
result = selftest(verbose=verbose,
2552
stop_on_failure=one,
2553
transport=transport,
2554
test_suite_factory=test_suite_factory,
2555
lsprof_timed=lsprof_timed,
2556
bench_history=benchfile,
2557
matching_tests_first=first,
2558
list_only=list_only,
2559
random_seed=randomize,
2560
exclude_pattern=exclude,
2564
if benchfile is not None:
2567
info('tests passed')
2569
info('tests failed')
3933
2570
return int(not result)
3935
def _disable_fsync(self):
3936
"""Change the 'os' functionality to not synchronize."""
3937
self._orig_fsync = getattr(os, 'fsync', None)
3938
if self._orig_fsync is not None:
3939
os.fsync = lambda filedes: None
3940
self._orig_fdatasync = getattr(os, 'fdatasync', None)
3941
if self._orig_fdatasync is not None:
3942
os.fdatasync = lambda filedes: None
3945
2573
class cmd_version(Command):
3946
__doc__ = """Show version of bzr."""
3948
encoding_type = 'replace'
3950
Option("short", help="Print just the version number."),
2574
"""Show version of bzr."""
3953
2576
@display_command
3954
def run(self, short=False):
3955
2578
from bzrlib.version import show_version
3957
self.outf.write(bzrlib.version_string + '\n')
3959
show_version(to_file=self.outf)
3962
2582
class cmd_rocks(Command):
3963
__doc__ = """Statement of optimism."""
2583
"""Statement of optimism."""
3967
2587
@display_command
3969
self.outf.write(gettext("It sure does!\n"))
2589
print "It sure does!"
3972
2592
class cmd_find_merge_base(Command):
3973
__doc__ = """Find and print a base revision for merging two branches."""
2593
"""Find and print a base revision for merging two branches."""
3974
2594
# TODO: Options to specify revisions on either side, as if
3975
2595
# merging only part of the history.
3976
2596
takes_args = ['branch', 'other']
3979
2599
@display_command
3980
2600
def run(self, branch, other):
3981
from bzrlib.revision import ensure_null
2601
from bzrlib.revision import ensure_null, MultipleRevisionSources
3983
2603
branch1 = Branch.open_containing(branch)[0]
3984
2604
branch2 = Branch.open_containing(other)[0]
3985
self.add_cleanup(branch1.lock_read().unlock)
3986
self.add_cleanup(branch2.lock_read().unlock)
3987
2606
last1 = ensure_null(branch1.last_revision())
3988
2607
last2 = ensure_null(branch2.last_revision())
3990
2609
graph = branch1.repository.get_graph(branch2.repository)
3991
2610
base_rev_id = graph.find_unique_lca(last1, last2)
3993
self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
2612
print 'merge base is revision %s' % base_rev_id
3996
2615
class cmd_merge(Command):
3997
__doc__ = """Perform a three-way merge.
3999
The source of the merge can be specified either in the form of a branch,
4000
or in the form of a path to a file containing a merge directive generated
4001
with bzr send. If neither is specified, the default is the upstream branch
4002
or the branch most recently merged using --remember. The source of the
4003
merge may also be specified in the form of a path to a file in another
4004
branch: in this case, only the modifications to that file are merged into
4005
the current working tree.
4007
When merging from a branch, by default bzr will try to merge in all new
4008
work from the other branch, automatically determining an appropriate base
4009
revision. If this fails, you may need to give an explicit base.
4011
To pick a different ending revision, pass "--revision OTHER". bzr will
4012
try to merge in all new work up to and including revision OTHER.
4014
If you specify two values, "--revision BASE..OTHER", only revisions BASE
4015
through OTHER, excluding BASE but including OTHER, will be merged. If this
4016
causes some revisions to be skipped, i.e. if the destination branch does
4017
not already contain revision BASE, such a merge is commonly referred to as
4018
a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4019
cherrypicks. The changes look like a normal commit, and the history of the
4020
changes from the other branch is not stored in the commit.
4022
Revision numbers are always relative to the source branch.
2616
"""Perform a three-way merge.
2618
The branch is the branch you will merge from. By default, it will merge
2619
the latest revision. If you specify a revision, that revision will be
2620
merged. If you specify two revisions, the first will be used as a BASE,
2621
and the second one as OTHER. Revision numbers are always relative to the
2624
By default, bzr will try to merge in all new work from the other
2625
branch, automatically determining an appropriate base. If this
2626
fails, you may need to give an explicit base.
4024
2628
Merge will do its best to combine the changes in two branches, but there
4025
2629
are some kinds of problems only a human can fix. When it encounters those,
4026
2630
it will mark a conflict. A conflict means that you need to fix something,
4119
2702
allow_pending = True
4120
2703
verified = 'inapplicable'
4122
2704
tree = WorkingTree.open_containing(directory)[0]
4123
if tree.branch.revno() == 0:
4124
raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4125
'https://bugs.launchpad.net/bzr/+bug/308562'))
4128
basis_tree = tree.revision_tree(tree.last_revision())
4129
except errors.NoSuchRevision:
4130
basis_tree = tree.basis_tree()
4132
# die as quickly as possible if there are uncommitted changes
4134
if tree.has_changes():
4135
raise errors.UncommittedChanges(tree)
4137
view_info = _get_view_info_for_change_reporter(tree)
4138
2705
change_reporter = delta._ChangeReporter(
4139
unversioned_filter=tree.is_ignored, view_info=view_info)
4140
pb = ui.ui_factory.nested_progress_bar()
4141
self.add_cleanup(pb.finished)
4142
self.add_cleanup(tree.lock_write().unlock)
4143
if location is not None:
4145
mergeable = bundle.read_mergeable_from_url(location,
4146
possible_transports=possible_transports)
4147
except errors.NotABundle:
2706
unversioned_filter=tree.is_ignored)
2709
pb = ui.ui_factory.nested_progress_bar()
2710
cleanups.append(pb.finished)
2712
cleanups.append(tree.unlock)
2713
if location is not None:
2714
mergeable, other_transport = _get_mergeable_helper(location)
2717
raise errors.BzrCommandError('Cannot use --uncommitted'
2718
' with bundles or merge directives.')
2720
if revision is not None:
2721
raise errors.BzrCommandError(
2722
'Cannot use -r with merge directives or bundles')
2723
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2725
possible_transports.append(other_transport)
2727
if merger is None and uncommitted:
2728
if revision is not None and len(revision) > 0:
2729
raise errors.BzrCommandError('Cannot use --uncommitted and'
2730
' --revision at the same time.')
2731
location = self._select_branch_location(tree, location)[0]
2732
other_tree, other_path = WorkingTree.open_containing(location)
2733
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2735
allow_pending = False
2738
merger, allow_pending = self._get_merger_from_branch(tree,
2739
location, revision, remember, possible_transports, pb)
2741
merger.merge_type = merge_type
2742
merger.reprocess = reprocess
2743
merger.show_base = show_base
2744
merger.change_reporter = change_reporter
2745
self.sanity_check_merger(merger)
2746
if (merger.base_rev_id == merger.other_rev_id and
2747
merger.other_rev_id != None):
2748
note('Nothing to do.')
2751
if merger.interesting_files is not None:
2752
raise BzrCommandError('Cannot pull individual files')
2753
if (merger.base_rev_id == tree.last_revision()):
2754
result = tree.pull(merger.other_branch, False,
2755
merger.other_rev_id)
2756
result.report(self.outf)
2758
merger.check_basis(not force)
2759
conflict_count = merger.do_merge()
2761
merger.set_pending()
2762
if verified == 'failed':
2763
warning('Preview patch does not match changes')
2764
if conflict_count != 0:
4151
raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4152
' with bundles or merge directives.'))
4154
if revision is not None:
4155
raise errors.BzrCommandError(gettext(
4156
'Cannot use -r with merge directives or bundles'))
4157
merger, verified = _mod_merge.Merger.from_mergeable(tree,
4160
if merger is None and uncommitted:
4161
if revision is not None and len(revision) > 0:
4162
raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4163
' --revision at the same time.'))
4164
merger = self.get_merger_from_uncommitted(tree, location, None)
4165
allow_pending = False
4168
merger, allow_pending = self._get_merger_from_branch(tree,
4169
location, revision, remember, possible_transports, None)
4171
merger.merge_type = merge_type
4172
merger.reprocess = reprocess
4173
merger.show_base = show_base
4174
self.sanity_check_merger(merger)
4175
if (merger.base_rev_id == merger.other_rev_id and
4176
merger.other_rev_id is not None):
4177
# check if location is a nonexistent file (and not a branch) to
4178
# disambiguate the 'Nothing to do'
4179
if merger.interesting_files:
4180
if not merger.other_tree.has_filename(
4181
merger.interesting_files[0]):
4182
note(gettext("merger: ") + str(merger))
4183
raise errors.PathsDoNotExist([location])
4184
note(gettext('Nothing to do.'))
4186
if pull and not preview:
4187
if merger.interesting_files is not None:
4188
raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4189
if (merger.base_rev_id == tree.last_revision()):
4190
result = tree.pull(merger.other_branch, False,
4191
merger.other_rev_id)
4192
result.report(self.outf)
4194
if merger.this_basis is None:
4195
raise errors.BzrCommandError(gettext(
4196
"This branch has no commits."
4197
" (perhaps you would prefer 'bzr pull')"))
4199
return self._do_preview(merger)
4201
return self._do_interactive(merger)
4203
return self._do_merge(merger, change_reporter, allow_pending,
4206
def _get_preview(self, merger):
4207
tree_merger = merger.make_merger()
4208
tt = tree_merger.make_preview_transform()
4209
self.add_cleanup(tt.finalize)
4210
result_tree = tt.get_preview_tree()
4213
def _do_preview(self, merger):
4214
from bzrlib.diff import show_diff_trees
4215
result_tree = self._get_preview(merger)
4216
path_encoding = osutils.get_diff_header_encoding()
4217
show_diff_trees(merger.this_tree, result_tree, self.outf,
4218
old_label='', new_label='',
4219
path_encoding=path_encoding)
4221
def _do_merge(self, merger, change_reporter, allow_pending, verified):
4222
merger.change_reporter = change_reporter
4223
conflict_count = merger.do_merge()
4225
merger.set_pending()
4226
if verified == 'failed':
4227
warning('Preview patch does not match changes')
4228
if conflict_count != 0:
4233
def _do_interactive(self, merger):
4234
"""Perform an interactive merge.
4236
This works by generating a preview tree of the merge, then using
4237
Shelver to selectively remove the differences between the working tree
4238
and the preview tree.
4240
from bzrlib import shelf_ui
4241
result_tree = self._get_preview(merger)
4242
writer = bzrlib.option.diff_writer_registry.get()
4243
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4244
reporter=shelf_ui.ApplyReporter(),
4245
diff_writer=writer(sys.stdout))
2769
for cleanup in reversed(cleanups):
4251
2772
def sanity_check_merger(self, merger):
4252
2773
if (merger.show_base and
4253
2774
not merger.merge_type is _mod_merge.Merge3Merger):
4254
raise errors.BzrCommandError(gettext("Show-base is not supported for this"
4255
" merge type. %s") % merger.merge_type)
4256
if merger.reprocess is None:
4257
if merger.show_base:
4258
merger.reprocess = False
4260
# Use reprocess if the merger supports it
4261
merger.reprocess = merger.merge_type.supports_reprocess
2775
raise errors.BzrCommandError("Show-base is not supported for this"
2776
" merge type. %s" % merger.merge_type)
4262
2777
if merger.reprocess and not merger.merge_type.supports_reprocess:
4263
raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
4264
" for merge type %s.") %
2778
raise errors.BzrCommandError("Conflict reduction is not supported"
2779
" for merge type %s." %
4265
2780
merger.merge_type)
4266
2781
if merger.reprocess and merger.show_base:
4267
raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
2782
raise errors.BzrCommandError("Cannot do conflict reduction and"
4270
2785
def _get_merger_from_branch(self, tree, location, revision, remember,
4271
2786
possible_transports, pb):
4272
2787
"""Produce a merger from a location, assuming it refers to a branch."""
4273
2788
from bzrlib.tag import _merge_tags_if_possible
2789
assert revision is None or len(revision) < 3
4274
2790
# find the branch locations
4275
other_loc, user_location = self._select_branch_location(tree, location,
2791
other_loc, location = self._select_branch_location(tree, location,
4277
2793
if revision is not None and len(revision) == 2:
4278
base_loc, _unused = self._select_branch_location(tree,
4279
location, revision, 0)
2794
base_loc, location = self._select_branch_location(tree, location,
4281
2797
base_loc = other_loc
4282
2798
# Open the branches
4580
3065
class cmd_shell_complete(Command):
4581
__doc__ = """Show appropriate completions for context.
3066
"""Show appropriate completions for context.
4583
3068
For a list of all available commands, say 'bzr shell-complete'.
4585
3070
takes_args = ['context?']
4586
3071
aliases = ['s-c']
4589
3074
@display_command
4590
3075
def run(self, context=None):
4591
3076
import shellcomplete
4592
3077
shellcomplete.shellcomplete(context)
3080
class cmd_fetch(Command):
3081
"""Copy in history from another branch but don't merge it.
3083
This is an internal method used for pull and merge.
3086
takes_args = ['from_branch', 'to_branch']
3087
def run(self, from_branch, to_branch):
3088
from bzrlib.fetch import Fetcher
3089
from_b = Branch.open(from_branch)
3090
to_b = Branch.open(to_branch)
3091
Fetcher(to_b, from_b)
4595
3094
class cmd_missing(Command):
4596
__doc__ = """Show unmerged/unpulled revisions between two branches.
3095
"""Show unmerged/unpulled revisions between two branches.
4598
3097
OTHER_BRANCH may be local or remote.
4600
To filter on a range of revisions, you can use the command -r begin..end
4601
-r revision requests a specific revision, -r ..end or -r begin.. are
4605
1 - some missing revisions
4606
0 - no missing revisions
4610
Determine the missing revisions between this and the branch at the
4611
remembered pull location::
4615
Determine the missing revisions between this and another branch::
4617
bzr missing http://server/branch
4619
Determine the missing revisions up to a specific revision on the other
4622
bzr missing -r ..-10
4624
Determine the missing revisions up to a specific revision on this
4627
bzr missing --my-revision ..-10
4630
3100
_see_also = ['merge', 'pull']
4631
3101
takes_args = ['other_branch?']
4632
3102
takes_options = [
4634
Option('reverse', 'Reverse the order of revisions.'),
4636
'Display changes in the local branch only.'),
4637
Option('this' , 'Same as --mine-only.'),
4638
Option('theirs-only',
4639
'Display changes in the remote branch only.'),
4640
Option('other', 'Same as --theirs-only.'),
4644
custom_help('revision',
4645
help='Filter on other branch revisions (inclusive). '
4646
'See "help revisionspec" for details.'),
4647
Option('my-revision',
4648
type=_parse_revision_str,
4649
help='Filter on local branch revisions (inclusive). '
4650
'See "help revisionspec" for details.'),
4651
Option('include-merged',
4652
'Show all revisions in addition to the mainline ones.'),
4653
Option('include-merges', hidden=True,
4654
help='Historical alias for --include-merged.'),
3103
Option('reverse', 'Reverse the order of revisions.'),
3105
'Display changes in the local branch only.'),
3106
Option('this' , 'Same as --mine-only.'),
3107
Option('theirs-only',
3108
'Display changes in the remote branch only.'),
3109
Option('other', 'Same as --theirs-only.'),
4656
3114
encoding_type = 'replace'
4658
3116
@display_command
4659
3117
def run(self, other_branch=None, reverse=False, mine_only=False,
4661
log_format=None, long=False, short=False, line=False,
4662
show_ids=False, verbose=False, this=False, other=False,
4663
include_merged=None, revision=None, my_revision=None,
4665
include_merges=symbol_versioning.DEPRECATED_PARAMETER):
3118
theirs_only=False, log_format=None, long=False, short=False, line=False,
3119
show_ids=False, verbose=False, this=False, other=False):
4666
3120
from bzrlib.missing import find_unmerged, iter_log_revisions
3121
from bzrlib.log import log_formatter
4671
if symbol_versioning.deprecated_passed(include_merges):
4672
ui.ui_factory.show_user_warning(
4673
'deprecated_command_option',
4674
deprecated_name='--include-merges',
4675
recommended_name='--include-merged',
4676
deprecated_in_version='2.5',
4677
command=self.invoked_as)
4678
if include_merged is None:
4679
include_merged = include_merges
4681
raise errors.BzrCommandError(gettext(
4682
'{0} and {1} are mutually exclusive').format(
4683
'--include-merges', '--include-merged'))
4684
if include_merged is None:
4685
include_merged = False
4690
# TODO: We should probably check that we don't have mine-only and
4691
# theirs-only set, but it gets complicated because we also have
4692
# this and other which could be used.
4699
local_branch = Branch.open_containing(directory)[0]
4700
self.add_cleanup(local_branch.lock_read().unlock)
3128
local_branch = Branch.open_containing(u".")[0]
4702
3129
parent = local_branch.get_parent()
4703
3130
if other_branch is None:
4704
3131
other_branch = parent
4705
3132
if other_branch is None:
4706
raise errors.BzrCommandError(gettext("No peer location known"
3133
raise errors.BzrCommandError("No peer location known"
4708
3135
display_url = urlutils.unescape_for_display(parent,
4709
3136
self.outf.encoding)
4710
message(gettext("Using saved parent location: {0}\n").format(
3137
self.outf.write("Using last location: " + display_url + "\n")
4713
3139
remote_branch = Branch.open(other_branch)
4714
3140
if remote_branch.base == local_branch.base:
4715
3141
remote_branch = local_branch
4717
self.add_cleanup(remote_branch.lock_read().unlock)
4719
local_revid_range = _revision_range_to_revid_range(
4720
_get_revision_range(my_revision, local_branch,
4723
remote_revid_range = _revision_range_to_revid_range(
4724
_get_revision_range(revision,
4725
remote_branch, self.name()))
4727
local_extra, remote_extra = find_unmerged(
4728
local_branch, remote_branch, restrict,
4729
backward=not reverse,
4730
include_merged=include_merged,
4731
local_revid_range=local_revid_range,
4732
remote_revid_range=remote_revid_range)
4734
if log_format is None:
4735
registry = log.log_formatter_registry
4736
log_format = registry.get_default(local_branch)
4737
lf = log_format(to_file=self.outf,
4739
show_timezone='original')
4742
if local_extra and not theirs_only:
4743
message(ngettext("You have %d extra revision:\n",
4744
"You have %d extra revisions:\n",
4747
for revision in iter_log_revisions(local_extra,
4748
local_branch.repository,
4750
lf.log_revision(revision)
4751
printed_local = True
4754
printed_local = False
4756
if remote_extra and not mine_only:
4757
if printed_local is True:
4759
message(ngettext("You are missing %d revision:\n",
4760
"You are missing %d revisions:\n",
4761
len(remote_extra)) %
4763
for revision in iter_log_revisions(remote_extra,
4764
remote_branch.repository,
4766
lf.log_revision(revision)
4769
if mine_only and not local_extra:
4770
# We checked local, and found nothing extra
4771
message(gettext('This branch has no new revisions.\n'))
4772
elif theirs_only and not remote_extra:
4773
# We checked remote, and found nothing extra
4774
message(gettext('Other branch has no new revisions.\n'))
4775
elif not (mine_only or theirs_only or local_extra or
4777
# We checked both branches, and neither one had extra
4779
message(gettext("Branches are up to date.\n"))
3142
local_branch.lock_read()
3144
remote_branch.lock_read()
3146
local_extra, remote_extra = find_unmerged(local_branch,
3148
if log_format is None:
3149
registry = log.log_formatter_registry
3150
log_format = registry.get_default(local_branch)
3151
lf = log_format(to_file=self.outf,
3153
show_timezone='original')
3154
if reverse is False:
3155
local_extra.reverse()
3156
remote_extra.reverse()
3157
if local_extra and not theirs_only:
3158
self.outf.write("You have %d extra revision(s):\n" %
3160
for revision in iter_log_revisions(local_extra,
3161
local_branch.repository,
3163
lf.log_revision(revision)
3164
printed_local = True
3166
printed_local = False
3167
if remote_extra and not mine_only:
3168
if printed_local is True:
3169
self.outf.write("\n\n\n")
3170
self.outf.write("You are missing %d revision(s):\n" %
3172
for revision in iter_log_revisions(remote_extra,
3173
remote_branch.repository,
3175
lf.log_revision(revision)
3176
if not remote_extra and not local_extra:
3178
self.outf.write("Branches are up to date.\n")
3182
remote_branch.unlock()
3184
local_branch.unlock()
4781
3185
if not status_code and parent is None and other_branch is not None:
4782
self.add_cleanup(local_branch.lock_write().unlock)
4783
# handle race conditions - a parent might be set while we run.
4784
if local_branch.get_parent() is None:
4785
local_branch.set_parent(remote_branch.base)
3186
local_branch.lock_write()
3188
# handle race conditions - a parent might be set while we run.
3189
if local_branch.get_parent() is None:
3190
local_branch.set_parent(remote_branch.base)
3192
local_branch.unlock()
4786
3193
return status_code
4789
3196
class cmd_pack(Command):
4790
__doc__ = """Compress the data within a repository.
4792
This operation compresses the data within a bazaar repository. As
4793
bazaar supports automatic packing of repository, this operation is
4794
normally not required to be done manually.
4796
During the pack operation, bazaar takes a backup of existing repository
4797
data, i.e. pack files. This backup is eventually removed by bazaar
4798
automatically when it is safe to do so. To save disk space by removing
4799
the backed up pack files, the --clean-obsolete-packs option may be
4802
Warning: If you use --clean-obsolete-packs and your machine crashes
4803
during or immediately after repacking, you may be left with a state
4804
where the deletion has been written to disk but the new packs have not
4805
been. In this case the repository may be unusable.
3197
"""Compress the data within a repository."""
4808
3199
_see_also = ['repositories']
4809
3200
takes_args = ['branch_or_repo?']
4811
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4814
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3202
def run(self, branch_or_repo='.'):
4815
3203
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4817
3205
branch = dir.open_branch()
4818
3206
repository = branch.repository
4819
3207
except errors.NotBranchError:
4820
3208
repository = dir.open_repository()
4821
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4824
3212
class cmd_plugins(Command):
4825
__doc__ = """List the installed plugins.
4827
This command displays the list of installed plugins including
4828
version of plugin and a short description of each.
4830
--verbose shows the path where each plugin is located.
3213
"""List the installed plugins.
3215
This command displays the list of installed plugins including the
3216
path where each one is located and a short description of each.
4832
3218
A plugin is an external component for Bazaar that extends the
4833
3219
revision control system, by adding or replacing code in Bazaar.
5670
3988
Tags are stored in the branch. Tags are copied from one branch to another
5671
3989
along when you branch, push, pull or merge.
5673
It is an error to give a tag name that already exists unless you pass
3991
It is an error to give a tag name that already exists unless you pass
5674
3992
--force, in which case the tag is moved to point to the new revision.
5676
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5677
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5679
If no tag name is specified it will be determined through the
5680
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5681
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5685
3995
_see_also = ['commit', 'tags']
5686
takes_args = ['tag_name?']
3996
takes_args = ['tag_name']
5687
3997
takes_options = [
5688
3998
Option('delete',
5689
3999
help='Delete this tag rather than placing it.',
5691
custom_help('directory',
5692
help='Branch in which to place the tag.'),
4002
help='Branch in which to place the tag.',
5693
4006
Option('force',
5694
4007
help='Replace existing tags.',
5699
def run(self, tag_name=None,
4012
def run(self, tag_name,
5705
4018
branch, relpath = Branch.open_containing(directory)
5706
self.add_cleanup(branch.lock_write().unlock)
5708
if tag_name is None:
5709
raise errors.BzrCommandError(gettext("No tag specified to delete."))
5710
branch.tags.delete_tag(tag_name)
5711
note(gettext('Deleted tag %s.') % tag_name)
5714
if len(revision) != 1:
5715
raise errors.BzrCommandError(gettext(
5716
"Tags can only be placed on a single revision, "
5718
revision_id = revision[0].as_revision_id(branch)
5720
revision_id = branch.last_revision()
5721
if tag_name is None:
5722
tag_name = branch.automatic_tag_name(revision_id)
5723
if tag_name is None:
5724
raise errors.BzrCommandError(gettext(
5725
"Please specify a tag name."))
5727
existing_target = branch.tags.lookup_tag(tag_name)
5728
except errors.NoSuchTag:
5729
existing_target = None
5730
if not force and existing_target not in (None, revision_id):
5731
raise errors.TagAlreadyExists(tag_name)
5732
if existing_target == revision_id:
5733
note(gettext('Tag %s already exists for that revision.') % tag_name)
4022
branch.tags.delete_tag(tag_name)
4023
self.outf.write('Deleted tag %s.\n' % tag_name)
4026
if len(revision) != 1:
4027
raise errors.BzrCommandError(
4028
"Tags can only be placed on a single revision, "
4030
revision_id = revision[0].in_history(branch).rev_id
4032
revision_id = branch.last_revision()
4033
if (not force) and branch.tags.has_tag(tag_name):
4034
raise errors.TagAlreadyExists(tag_name)
5735
4035
branch.tags.set_tag(tag_name, revision_id)
5736
if existing_target is None:
5737
note(gettext('Created tag %s.') % tag_name)
5739
note(gettext('Updated tag %s.') % tag_name)
4036
self.outf.write('Created tag %s.\n' % tag_name)
5742
4041
class cmd_tags(Command):
5743
__doc__ = """List tags.
5745
This command shows a table of tag names and the revisions they reference.
4044
This tag shows a table of tag names and the revisions they reference.
5748
4047
_see_also = ['tag']
5749
4048
takes_options = [
5750
custom_help('directory',
5751
help='Branch whose tags should be displayed.'),
5752
RegistryOption('sort',
5753
'Sort tags by different criteria.', title='Sorting',
5754
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
4050
help='Branch whose tags should be displayed.',
5760
4056
@display_command
5761
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5762
from bzrlib.tag import tag_sort_methods
5763
4060
branch, relpath = Branch.open_containing(directory)
5765
tags = branch.tags.get_tag_dict().items()
5769
self.add_cleanup(branch.lock_read().unlock)
5771
# Restrict to the specified range
5772
tags = self._tags_for_range(branch, revision)
5774
sort = tag_sort_methods.get()
5777
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5778
for index, (tag, revid) in enumerate(tags):
5780
revno = branch.revision_id_to_dotted_revno(revid)
5781
if isinstance(revno, tuple):
5782
revno = '.'.join(map(str, revno))
5783
except (errors.NoSuchRevision,
5784
errors.GhostRevisionsHaveNoRevno):
5785
# Bad tag data/merges can lead to tagged revisions
5786
# which are not in this branch. Fail gracefully ...
5788
tags[index] = (tag, revno)
5790
for tag, revspec in tags:
5791
self.outf.write('%-20s %s\n' % (tag, revspec))
5793
def _tags_for_range(self, branch, revision):
5795
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5796
revid1, revid2 = rev1.rev_id, rev2.rev_id
5797
# _get_revision_range will always set revid2 if it's not specified.
5798
# If revid1 is None, it means we want to start from the branch
5799
# origin which is always a valid ancestor. If revid1 == revid2, the
5800
# ancestry check is useless.
5801
if revid1 and revid1 != revid2:
5802
# FIXME: We really want to use the same graph than
5803
# branch.iter_merge_sorted_revisions below, but this is not
5804
# easily available -- vila 2011-09-23
5805
if branch.repository.get_graph().is_ancestor(revid2, revid1):
5806
# We don't want to output anything in this case...
5808
# only show revisions between revid1 and revid2 (inclusive)
5809
tagged_revids = branch.tags.get_reverse_tag_dict()
5811
for r in branch.iter_merge_sorted_revisions(
5812
start_revision_id=revid2, stop_revision_id=revid1,
5813
stop_rule='include'):
5814
revid_tags = tagged_revids.get(r[0], None)
5816
found.extend([(tag, r[0]) for tag in revid_tags])
5820
class cmd_reconfigure(Command):
5821
__doc__ = """Reconfigure the type of a bzr directory.
5823
A target configuration must be specified.
5825
For checkouts, the bind-to location will be auto-detected if not specified.
5826
The order of preference is
5827
1. For a lightweight checkout, the current bound location.
5828
2. For branches that used to be checkouts, the previously-bound location.
5829
3. The push location.
5830
4. The parent location.
5831
If none of these is available, --bind-to must be specified.
5834
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5835
takes_args = ['location?']
5837
RegistryOption.from_kwargs(
5840
help='The relation between branch and tree.',
5841
value_switches=True, enum_switch=False,
5842
branch='Reconfigure to be an unbound branch with no working tree.',
5843
tree='Reconfigure to be an unbound branch with a working tree.',
5844
checkout='Reconfigure to be a bound branch with a working tree.',
5845
lightweight_checkout='Reconfigure to be a lightweight'
5846
' checkout (with no local history).',
5848
RegistryOption.from_kwargs(
5850
title='Repository type',
5851
help='Location fo the repository.',
5852
value_switches=True, enum_switch=False,
5853
standalone='Reconfigure to be a standalone branch '
5854
'(i.e. stop using shared repository).',
5855
use_shared='Reconfigure to use a shared repository.',
5857
RegistryOption.from_kwargs(
5859
title='Trees in Repository',
5860
help='Whether new branches in the repository have trees.',
5861
value_switches=True, enum_switch=False,
5862
with_trees='Reconfigure repository to create '
5863
'working trees on branches by default.',
5864
with_no_trees='Reconfigure repository to not create '
5865
'working trees on branches by default.'
5867
Option('bind-to', help='Branch to bind checkout to.', type=str),
5869
help='Perform reconfiguration even if local changes'
5871
Option('stacked-on',
5872
help='Reconfigure a branch to be stacked on another branch.',
5876
help='Reconfigure a branch to be unstacked. This '
5877
'may require copying substantial data into it.',
5881
def run(self, location=None, bind_to=None, force=False,
5882
tree_type=None, repository_type=None, repository_trees=None,
5883
stacked_on=None, unstacked=None):
5884
directory = bzrdir.BzrDir.open(location)
5885
if stacked_on and unstacked:
5886
raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
5887
elif stacked_on is not None:
5888
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5890
reconfigure.ReconfigureUnstacked().apply(directory)
5891
# At the moment you can use --stacked-on and a different
5892
# reconfiguration shape at the same time; there seems no good reason
5894
if (tree_type is None and
5895
repository_type is None and
5896
repository_trees is None):
5897
if stacked_on or unstacked:
5900
raise errors.BzrCommandError(gettext('No target configuration '
5902
reconfiguration = None
5903
if tree_type == 'branch':
5904
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5905
elif tree_type == 'tree':
5906
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5907
elif tree_type == 'checkout':
5908
reconfiguration = reconfigure.Reconfigure.to_checkout(
5910
elif tree_type == 'lightweight-checkout':
5911
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5914
reconfiguration.apply(force)
5915
reconfiguration = None
5916
if repository_type == 'use-shared':
5917
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5918
elif repository_type == 'standalone':
5919
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5921
reconfiguration.apply(force)
5922
reconfiguration = None
5923
if repository_trees == 'with-trees':
5924
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5926
elif repository_trees == 'with-no-trees':
5927
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5930
reconfiguration.apply(force)
5931
reconfiguration = None
5934
class cmd_switch(Command):
5935
__doc__ = """Set the branch of a checkout and update.
5937
For lightweight checkouts, this changes the branch being referenced.
5938
For heavyweight checkouts, this checks that there are no local commits
5939
versus the current bound branch, then it makes the local branch a mirror
5940
of the new location and binds to it.
5942
In both cases, the working tree is updated and uncommitted changes
5943
are merged. The user can commit or revert these as they desire.
5945
Pending merges need to be committed or reverted before using switch.
5947
The path to the branch to switch to can be specified relative to the parent
5948
directory of the current branch. For example, if you are currently in a
5949
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5952
Bound branches use the nickname of its master branch unless it is set
5953
locally, in which case switching will update the local nickname to be
5957
takes_args = ['to_location?']
5958
takes_options = ['directory',
5960
help='Switch even if local commits will be lost.'),
5962
Option('create-branch', short_name='b',
5963
help='Create the target branch from this one before'
5964
' switching to it.'),
5967
def run(self, to_location=None, force=False, create_branch=False,
5968
revision=None, directory=u'.'):
5969
from bzrlib import switch
5970
tree_location = directory
5971
revision = _get_one_revision('switch', revision)
5972
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5973
if to_location is None:
5974
if revision is None:
5975
raise errors.BzrCommandError(gettext('You must supply either a'
5976
' revision or a location'))
5977
to_location = tree_location
5979
branch = control_dir.open_branch()
5980
had_explicit_nick = branch.get_config().has_explicit_nickname()
5981
except errors.NotBranchError:
5983
had_explicit_nick = False
5986
raise errors.BzrCommandError(gettext('cannot create branch without'
5988
to_location = directory_service.directories.dereference(
5990
if '/' not in to_location and '\\' not in to_location:
5991
# This path is meant to be relative to the existing branch
5992
this_url = self._get_branch_location(control_dir)
5993
to_location = urlutils.join(this_url, '..', to_location)
5994
to_branch = branch.bzrdir.sprout(to_location,
5995
possible_transports=[branch.bzrdir.root_transport],
5996
source_branch=branch).open_branch()
5999
to_branch = Branch.open(to_location)
6000
except errors.NotBranchError:
6001
this_url = self._get_branch_location(control_dir)
6002
to_branch = Branch.open(
6003
urlutils.join(this_url, '..', to_location))
6004
if revision is not None:
6005
revision = revision.as_revision_id(to_branch)
6006
switch.switch(control_dir, to_branch, force, revision_id=revision)
6007
if had_explicit_nick:
6008
branch = control_dir.open_branch() #get the new branch!
6009
branch.nick = to_branch.nick
6010
note(gettext('Switched to branch: %s'),
6011
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6013
def _get_branch_location(self, control_dir):
6014
"""Return location of branch for this control dir."""
6016
this_branch = control_dir.open_branch()
6017
# This may be a heavy checkout, where we want the master branch
6018
master_location = this_branch.get_bound_location()
6019
if master_location is not None:
6020
return master_location
6021
# If not, use a local sibling
6022
return this_branch.base
6023
except errors.NotBranchError:
6024
format = control_dir.find_branch_format()
6025
if getattr(format, 'get_reference', None) is not None:
6026
return format.get_reference(control_dir)
6028
return control_dir.root_transport.base
6031
class cmd_view(Command):
6032
__doc__ = """Manage filtered views.
6034
Views provide a mask over the tree so that users can focus on
6035
a subset of a tree when doing their work. After creating a view,
6036
commands that support a list of files - status, diff, commit, etc -
6037
effectively have that list of files implicitly given each time.
6038
An explicit list of files can still be given but those files
6039
must be within the current view.
6041
In most cases, a view has a short life-span: it is created to make
6042
a selected change and is deleted once that change is committed.
6043
At other times, you may wish to create one or more named views
6044
and switch between them.
6046
To disable the current view without deleting it, you can switch to
6047
the pseudo view called ``off``. This can be useful when you need
6048
to see the whole tree for an operation or two (e.g. merge) but
6049
want to switch back to your view after that.
6052
To define the current view::
6054
bzr view file1 dir1 ...
6056
To list the current view::
6060
To delete the current view::
6064
To disable the current view without deleting it::
6066
bzr view --switch off
6068
To define a named view and switch to it::
6070
bzr view --name view-name file1 dir1 ...
6072
To list a named view::
6074
bzr view --name view-name
6076
To delete a named view::
6078
bzr view --name view-name --delete
6080
To switch to a named view::
6082
bzr view --switch view-name
6084
To list all views defined::
6088
To delete all views::
6090
bzr view --delete --all
6094
takes_args = ['file*']
6097
help='Apply list or delete action to all views.',
6100
help='Delete the view.',
6103
help='Name of the view to define, list or delete.',
6107
help='Name of the view to switch to.',
6112
def run(self, file_list,
6118
tree, file_list = WorkingTree.open_containing_paths(file_list,
6120
current_view, view_dict = tree.views.get_view_info()
6125
raise errors.BzrCommandError(gettext(
6126
"Both --delete and a file list specified"))
6128
raise errors.BzrCommandError(gettext(
6129
"Both --delete and --switch specified"))
6131
tree.views.set_view_info(None, {})
6132
self.outf.write(gettext("Deleted all views.\n"))
6134
raise errors.BzrCommandError(gettext("No current view to delete"))
6136
tree.views.delete_view(name)
6137
self.outf.write(gettext("Deleted '%s' view.\n") % name)
6140
raise errors.BzrCommandError(gettext(
6141
"Both --switch and a file list specified"))
6143
raise errors.BzrCommandError(gettext(
6144
"Both --switch and --all specified"))
6145
elif switch == 'off':
6146
if current_view is None:
6147
raise errors.BzrCommandError(gettext("No current view to disable"))
6148
tree.views.set_view_info(None, view_dict)
6149
self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
6151
tree.views.set_view_info(switch, view_dict)
6152
view_str = views.view_display_str(tree.views.lookup_view())
6153
self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
6156
self.outf.write(gettext('Views defined:\n'))
6157
for view in sorted(view_dict):
6158
if view == current_view:
6162
view_str = views.view_display_str(view_dict[view])
6163
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6165
self.outf.write(gettext('No views defined.\n'))
6168
# No name given and no current view set
6171
raise errors.BzrCommandError(gettext(
6172
"Cannot change the 'off' pseudo view"))
6173
tree.views.set_view(name, sorted(file_list))
6174
view_str = views.view_display_str(tree.views.lookup_view())
6175
self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
6179
# No name given and no current view set
6180
self.outf.write(gettext('No current view.\n'))
6182
view_str = views.view_display_str(tree.views.lookup_view(name))
6183
self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
6186
class cmd_hooks(Command):
6187
__doc__ = """Show hooks."""
6192
for hook_key in sorted(hooks.known_hooks.keys()):
6193
some_hooks = hooks.known_hooks_key_to_object(hook_key)
6194
self.outf.write("%s:\n" % type(some_hooks).__name__)
6195
for hook_name, hook_point in sorted(some_hooks.items()):
6196
self.outf.write(" %s:\n" % (hook_name,))
6197
found_hooks = list(hook_point)
6199
for hook in found_hooks:
6200
self.outf.write(" %s\n" %
6201
(some_hooks.get_hook_name(hook),))
6203
self.outf.write(gettext(" <no hooks installed>\n"))
6206
class cmd_remove_branch(Command):
6207
__doc__ = """Remove a branch.
6209
This will remove the branch from the specified location but
6210
will keep any working tree or repository in place.
6214
Remove the branch at repo/trunk::
6216
bzr remove-branch repo/trunk
6220
takes_args = ["location?"]
6222
aliases = ["rmbranch"]
6224
def run(self, location=None):
6225
if location is None:
6227
branch = Branch.open_containing(location)[0]
6228
branch.bzrdir.destroy_branch()
6231
class cmd_shelve(Command):
6232
__doc__ = """Temporarily set aside some changes from the current tree.
6234
Shelve allows you to temporarily put changes you've made "on the shelf",
6235
ie. out of the way, until a later time when you can bring them back from
6236
the shelf with the 'unshelve' command. The changes are stored alongside
6237
your working tree, and so they aren't propagated along with your branch nor
6238
will they survive its deletion.
6240
If shelve --list is specified, previously-shelved changes are listed.
6242
Shelve is intended to help separate several sets of changes that have
6243
been inappropriately mingled. If you just want to get rid of all changes
6244
and you don't need to restore them later, use revert. If you want to
6245
shelve all text changes at once, use shelve --all.
6247
If filenames are specified, only the changes to those files will be
6248
shelved. Other files will be left untouched.
6250
If a revision is specified, changes since that revision will be shelved.
6252
You can put multiple items on the shelf, and by default, 'unshelve' will
6253
restore the most recently shelved changes.
6255
For complicated changes, it is possible to edit the changes in a separate
6256
editor program to decide what the file remaining in the working copy
6257
should look like. To do this, add the configuration option
6259
change_editor = PROGRAM @new_path @old_path
6261
where @new_path is replaced with the path of the new version of the
6262
file and @old_path is replaced with the path of the old version of
6263
the file. The PROGRAM should save the new file with the desired
6264
contents of the file in the working tree.
6268
takes_args = ['file*']
6273
Option('all', help='Shelve all changes.'),
6275
RegistryOption('writer', 'Method to use for writing diffs.',
6276
bzrlib.option.diff_writer_registry,
6277
value_switches=True, enum_switch=False),
6279
Option('list', help='List shelved changes.'),
6281
help='Destroy removed changes instead of shelving them.'),
6283
_see_also = ['unshelve', 'configuration']
6285
def run(self, revision=None, all=False, file_list=None, message=None,
6286
writer=None, list=False, destroy=False, directory=None):
6288
return self.run_for_list(directory=directory)
6289
from bzrlib.shelf_ui import Shelver
6291
writer = bzrlib.option.diff_writer_registry.get()
6293
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6294
file_list, message, destroy=destroy, directory=directory)
6299
except errors.UserAbort:
6302
def run_for_list(self, directory=None):
6303
if directory is None:
6305
tree = WorkingTree.open_containing(directory)[0]
6306
self.add_cleanup(tree.lock_read().unlock)
6307
manager = tree.get_shelf_manager()
6308
shelves = manager.active_shelves()
6309
if len(shelves) == 0:
6310
note(gettext('No shelved changes.'))
6312
for shelf_id in reversed(shelves):
6313
message = manager.get_metadata(shelf_id).get('message')
6315
message = '<no message>'
6316
self.outf.write('%3d: %s\n' % (shelf_id, message))
6320
class cmd_unshelve(Command):
6321
__doc__ = """Restore shelved changes.
6323
By default, the most recently shelved changes are restored. However if you
6324
specify a shelf by id those changes will be restored instead. This works
6325
best when the changes don't depend on each other.
6328
takes_args = ['shelf_id?']
6331
RegistryOption.from_kwargs(
6332
'action', help="The action to perform.",
6333
enum_switch=False, value_switches=True,
6334
apply="Apply changes and remove from the shelf.",
6335
dry_run="Show changes, but do not apply or remove them.",
6336
preview="Instead of unshelving the changes, show the diff that "
6337
"would result from unshelving.",
6338
delete_only="Delete changes without applying them.",
6339
keep="Apply changes but don't delete them.",
6342
_see_also = ['shelve']
6344
def run(self, shelf_id=None, action='apply', directory=u'.'):
6345
from bzrlib.shelf_ui import Unshelver
6346
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6350
unshelver.tree.unlock()
6353
class cmd_clean_tree(Command):
6354
__doc__ = """Remove unwanted files from working tree.
6356
By default, only unknown files, not ignored files, are deleted. Versioned
6357
files are never deleted.
6359
Another class is 'detritus', which includes files emitted by bzr during
6360
normal operations and selftests. (The value of these files decreases with
6363
If no options are specified, unknown files are deleted. Otherwise, option
6364
flags are respected, and may be combined.
6366
To check what clean-tree will do, use --dry-run.
6368
takes_options = ['directory',
6369
Option('ignored', help='Delete all ignored files.'),
6370
Option('detritus', help='Delete conflict files, merge and revert'
6371
' backups, and failed selftest dirs.'),
6373
help='Delete files unknown to bzr (default).'),
6374
Option('dry-run', help='Show files to delete instead of'
6376
Option('force', help='Do not prompt before deleting.')]
6377
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6378
force=False, directory=u'.'):
6379
from bzrlib.clean_tree import clean_tree
6380
if not (unknown or ignored or detritus):
6384
clean_tree(directory, unknown=unknown, ignored=ignored,
6385
detritus=detritus, dry_run=dry_run, no_prompt=force)
6388
class cmd_reference(Command):
6389
__doc__ = """list, view and set branch locations for nested trees.
6391
If no arguments are provided, lists the branch locations for nested trees.
6392
If one argument is provided, display the branch location for that tree.
6393
If two arguments are provided, set the branch location for that tree.
6398
takes_args = ['path?', 'location?']
6400
def run(self, path=None, location=None):
6402
if path is not None:
6404
tree, branch, relpath =(
6405
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6406
if path is not None:
6409
tree = branch.basis_tree()
6411
info = branch._get_all_reference_info().iteritems()
6412
self._display_reference_info(tree, branch, info)
6414
file_id = tree.path2id(path)
6416
raise errors.NotVersionedError(path)
6417
if location is None:
6418
info = [(file_id, branch.get_reference_info(file_id))]
6419
self._display_reference_info(tree, branch, info)
6421
branch.set_reference_info(file_id, path, location)
6423
def _display_reference_info(self, tree, branch, info):
6425
for file_id, (path, location) in info:
6427
path = tree.id2path(file_id)
6428
except errors.NoSuchId:
6430
ref_list.append((path, location))
6431
for path, location in sorted(ref_list):
6432
self.outf.write('%s %s\n' % (path, location))
6435
class cmd_export_pot(Command):
6436
__doc__ = """Export command helps and error messages in po format."""
6441
from bzrlib.export_pot import export_pot
6442
export_pot(self.outf)
6445
def _register_lazy_builtins():
6446
# register lazy builtins from other modules; called at startup and should
6447
# be only called once.
6448
for (name, aliases, module_name) in [
6449
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6450
('cmd_config', [], 'bzrlib.config'),
6451
('cmd_dpush', [], 'bzrlib.foreign'),
6452
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6453
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6454
('cmd_conflicts', [], 'bzrlib.conflicts'),
6455
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6456
('cmd_verify_signatures', [],
6457
'bzrlib.commit_signature_commands'),
6458
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6460
builtin_command_registry.register_lazy(name, aliases, module_name)
4061
for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4062
self.outf.write('%-20s %s\n' % (tag_name, target))
4065
def _create_prefix(cur_transport):
4066
needed = [cur_transport]
4067
# Recurse upwards until we can create a directory successfully
4069
new_transport = cur_transport.clone('..')
4070
if new_transport.base == cur_transport.base:
4071
raise errors.BzrCommandError(
4072
"Failed to create path prefix for %s."
4073
% cur_transport.base)
4075
new_transport.mkdir('.')
4076
except errors.NoSuchFile:
4077
needed.append(new_transport)
4078
cur_transport = new_transport
4081
# Now we only need to create child directories
4083
cur_transport = needed.pop()
4084
cur_transport.ensure_base()
4087
def _get_mergeable_helper(location):
4088
"""Get a merge directive or bundle if 'location' points to one.
4090
Try try to identify a bundle and returns its mergeable form. If it's not,
4091
we return the tried transport anyway so that it can reused to access the
4094
:param location: can point to a bundle or a branch.
4096
:return: mergeable, transport
4099
url = urlutils.normalize_url(location)
4100
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4101
location_transport = transport.get_transport(url)
4104
# There may be redirections but we ignore the intermediate
4105
# and final transports used
4106
read = bundle.read_mergeable_from_transport
4107
mergeable, t = read(location_transport, filename)
4108
except errors.NotABundle:
4109
# Continue on considering this url a Branch but adjust the
4110
# location_transport
4111
location_transport = location_transport.clone(filename)
4112
return mergeable, location_transport
4115
# these get imported and then picked up by the scan for cmd_*
4116
# TODO: Some more consistent way to split command definitions across files;
4117
# we do need to load at least some information about them to know of
4118
# aliases. ideally we would avoid loading the implementation until the
4119
# details were needed.
4120
from bzrlib.cmd_version_info import cmd_version_info
4121
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4122
from bzrlib.bundle.commands import (
4125
from bzrlib.sign_my_commits import cmd_sign_my_commits
4126
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4127
cmd_weave_plan_merge, cmd_weave_merge_text