28
29
from bzrlib import (
35
config as _mod_config,
40
39
merge as _mod_merge,
45
43
revision as _mod_revision,
54
50
from bzrlib.branch import Branch
55
51
from bzrlib.conflicts import ConflictList
56
from bzrlib.transport import memory
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
52
from bzrlib.revisionspec import RevisionSpec
58
53
from bzrlib.smtp_connection import SMTPConnection
59
54
from bzrlib.workingtree import WorkingTree
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)
57
from bzrlib.commands import Command, display_command
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
59
from bzrlib.trace import mutter, note, warning, is_quiet, info
62
def tree_files(file_list, default_branch=u'.'):
64
return internal_tree_files(file_list, default_branch)
65
except errors.FileInWrongBranch, e:
66
raise errors.BzrCommandError("%s is not in the same branch as %s" %
67
(e.path, file_list[0]))
153
70
# XXX: Bad function name; should possibly also be a class method of
154
71
# 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,
72
def internal_tree_files(file_list, default_branch=u'.'):
158
73
"""Convert command-line paths to a WorkingTree and relative paths.
160
Deprecated: use WorkingTree.open_containing_paths instead.
162
75
This is typically used for command-line processors that take one or
163
76
more filenames, and infer the workingtree that contains them.
165
78
The filenames given are not required to exist.
167
:param file_list: Filenames to convert.
80
:param file_list: Filenames to convert.
169
82
: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
85
: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."""
87
if file_list is None or len(file_list) == 0:
88
return WorkingTree.open_containing(default_branch)[0], file_list
89
tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
91
for filename in file_list:
93
new_list.append(tree.relpath(osutils.dereference_path(filename)))
94
except errors.PathNotChild:
95
raise errors.FileInWrongBranch(tree.branch, filename)
99
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
100
def get_format_type(typestring):
101
"""Parse and return a format specifier."""
102
# Have to use BzrDirMetaFormat1 directly, so that
103
# RepositoryFormat.set_default_format works
104
if typestring == "default":
105
return bzrdir.BzrDirMetaFormat1()
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)
107
return bzrdir.format_registry.make_bzrdir(typestring)
109
msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
110
raise errors.BzrCommandError(msg)
203
113
# TODO: Make sure no commands unconditionally use the working directory as a
234
144
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
146
To see ignored files use 'bzr ignored'. For details on the
242
147
changes to file texts, use 'bzr diff'.
244
149
Note that --short or -S gives status flags for each item, similar
245
150
to Subversion's status command. To get output similar to svn -q,
248
153
If no arguments are specified, the status of the entire working
249
154
directory is shown. Otherwise, only the status of the specified
250
155
files or directories is reported. If a directory is given, status
251
156
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'.
158
If a revision argument is given, the status is calculated against
159
that revision, or between two revisions if two are provided.
266
162
# TODO: --no-recurse, --recurse options
268
164
takes_args = ['file*']
269
takes_options = ['show-ids', 'revision', 'change', 'verbose',
165
takes_options = ['show-ids', 'revision', 'change',
270
166
Option('short', help='Use short status indicators.',
272
168
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.',
280
171
aliases = ['st', 'stat']
282
173
encoding_type = 'replace'
283
174
_see_also = ['diff', 'revert', 'status-flags']
286
177
def run(self, show_ids=False, file_list=None, revision=None, short=False,
287
versioned=False, no_pending=False, verbose=False,
289
179
from bzrlib.status import show_tree_status
291
181
if revision and len(revision) > 2:
292
raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
293
' one or two revision specifiers'))
182
raise errors.BzrCommandError('bzr status --revision takes exactly'
183
' 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:
185
tree, file_list = tree_files(file_list)
305
187
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)
188
specific_files=file_list, revision=revision,
189
to_file=self.outf, short=short, versioned=versioned)
312
192
class cmd_cat_revision(Command):
313
__doc__ = """Write out metadata for a revision.
193
"""Write out metadata for a revision.
315
195
The revision to print can either be specified by a specific
316
196
revision identifier, or you can use --revision.
320
200
takes_args = ['revision_id?']
321
takes_options = ['directory', 'revision']
201
takes_options = ['revision']
322
202
# cat-revision is more for frontends so should be exact
323
203
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'.'):
206
def run(self, revision_id=None, revision=None):
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
revision_id = osutils.safe_revision_id(revision_id, warn=False)
218
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
219
elif revision is not None:
222
raise errors.BzrCommandError('You cannot specify a NULL'
224
revno, rev_id = rev.in_history(b)
225
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
455
228
class cmd_remove_tree(Command):
456
__doc__ = """Remove the working tree from a given branch/checkout.
229
"""Remove the working tree from a given branch/checkout.
458
231
Since a lightweight checkout is little more than a working tree
459
232
this will refuse to run against one.
461
234
To re-create the working tree, use "bzr checkout".
463
236
_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]
238
takes_args = ['location?']
240
def run(self, location='.'):
241
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))
244
working = d.open_workingtree()
245
except errors.NoWorkingTree:
246
raise errors.BzrCommandError("No working tree to remove")
247
except errors.NotLocalUrl:
248
raise errors.BzrCommandError("You cannot remove the working tree of a "
251
working_path = working.bzrdir.root_transport.base
252
branch_path = working.branch.bzrdir.root_transport.base
253
if working_path != branch_path:
254
raise errors.BzrCommandError("You cannot remove the working tree from "
255
"a lightweight checkout")
257
d.destroy_workingtree()
550
260
class cmd_revno(Command):
551
__doc__ = """Show current revision number.
261
"""Show current revision number.
553
263
This is equal to the number of revisions on this branch.
556
266
_see_also = ['info']
557
267
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')
270
def run(self, location=u'.'):
271
self.outf.write(str(Branch.open_containing(location)[0].revno()))
272
self.outf.write('\n')
584
275
class cmd_revision_info(Command):
585
__doc__ = """Show revision number and revision id for a given revision identifier.
276
"""Show revision number and revision id for a given revision identifier.
588
279
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'),
280
takes_options = ['revision']
598
def run(self, revision=None, directory=u'.', tree=False,
599
revision_info_list=[]):
283
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
286
if revision is not None:
611
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
287
revs.extend(revision)
612
288
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())
289
for rev in revision_info_list:
290
revs.append(RevisionSpec.from_string(rev))
292
b = Branch.open_containing(u'.')[0]
295
revs.append(RevisionSpec.from_string('-1'))
298
revinfo = rev.in_history(b)
299
if revinfo.revno is None:
300
dotted_map = b.get_revision_id_to_revno_map()
301
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
302
print '%s %s' % (revno, revinfo.rev_id)
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]))
304
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
641
307
class cmd_add(Command):
642
__doc__ = """Add specified files or directories.
308
"""Add specified files or directories.
644
310
In non-recursive mode, all the named items are added, regardless
645
311
of whether they were previously ignored. A warning is given if
852
523
takes_args = ['names*']
853
524
takes_options = [Option("after", help="Move only the bzr identifier"
854
525
" 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
527
aliases = ['move', 'rename']
859
528
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.'))
530
def run(self, names_list, after=False):
866
531
if names_list is None:
868
534
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
535
raise errors.BzrCommandError("missing file argument")
536
tree, rel_names = tree_files(names_list)
538
dest = names_list[-1]
539
isdir = os.path.isdir(dest)
540
if (isdir and not tree.case_sensitive and len(rel_names) == 2
541
and rel_names[0].lower() == rel_names[1].lower()):
907
544
# 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))
545
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
546
self.outf.write("%s => %s\n" % pair)
915
548
if len(names_list) != 2:
916
raise errors.BzrCommandError(gettext('to mv multiple files the'
549
raise errors.BzrCommandError('to mv multiple files the'
917
550
' 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))
552
tree.rename_one(rel_names[0], rel_names[1], after=after)
553
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
967
556
class cmd_pull(Command):
968
__doc__ = """Turn this branch into a mirror of another branch.
557
"""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
559
This command only works on branches that have not diverged. Branches are
560
considered diverged if the destination branch's most recent commit is one
561
that has not been merged (directly or indirectly) into the parent.
975
563
If branches have diverged, you can use 'bzr merge' to integrate the changes
976
564
from one into the other. Once one branch has merged, the other should
977
565
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
567
If you want to forget your local changes and just update your branch to
568
match the remote one, use pull --overwrite.
570
If there is no default location set, the first pull will set it. After
571
that, you can omit the location to use the default. To change the
572
default, use --remember. The value will only be saved if the remote
573
location can be accessed.
993
_see_also = ['push', 'update', 'status-flags', 'send']
576
_see_also = ['push', 'update', 'status-flags']
994
577
takes_options = ['remember', 'overwrite', 'revision',
995
578
custom_help('verbose',
996
579
help='Show logs of pulled revisions.'),
997
custom_help('directory',
998
581
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."
582
'rather than the one containing the working directory.',
1006
help="Show base revision text in conflicts.")
1008
587
takes_args = ['location?']
1009
588
encoding_type = 'replace'
1011
def run(self, location=None, remember=None, overwrite=False,
590
def run(self, location=None, remember=False, overwrite=False,
1012
591
revision=None, verbose=False,
1013
directory=None, local=False,
1015
593
# FIXME: too much stuff is in the command class
1016
594
revision_id = None
1017
595
mergeable = None
1127
691
Option('create-prefix',
1128
692
help='Create the path leading up to the branch '
1129
693
'if it does not already exist.'),
1130
custom_help('directory',
1131
695
help='Branch to push from, '
1132
'rather than the one containing the working directory.'),
696
'rather than the one containing the working directory.',
1133
700
Option('use-existing-dir',
1134
701
help='By default push will fail if the target'
1135
702
' directory exists, but does not already'
1136
703
' have a control directory. This flag will'
1137
704
' 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
706
takes_args = ['location?']
1154
707
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
709
def run(self, location=None, remember=False, overwrite=False,
710
create_prefix=False, verbose=False, revision=None,
711
use_existing_dir=False,
713
# FIXME: Way too big! Put this into a function called from the
1162
715
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
717
br_from = Branch.open_containing(directory)[0]
718
stored_loc = br_from.get_push_location()
1197
719
if location is None:
1198
stored_loc = br_from.get_push_location()
1199
720
if stored_loc is None:
1200
raise errors.BzrCommandError(gettext(
1201
"No push location known or specified."))
721
raise errors.BzrCommandError("No push location known or specified.")
1203
723
display_url = urlutils.unescape_for_display(stored_loc,
1204
724
self.outf.encoding)
1205
note(gettext("Using saved push location: %s") % display_url)
725
self.outf.write("Using saved location: %s\n" % display_url)
1206
726
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)
728
to_transport = transport.get_transport(location)
730
br_to = repository_to = dir_to = None
732
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
733
except errors.NotBranchError:
734
pass # Didn't find anything
736
# If we can open a branch, use its direct repository, otherwise see
737
# if there is a repository without a branch.
739
br_to = dir_to.open_branch()
740
except errors.NotBranchError:
741
# Didn't find a branch, can we find a repository?
743
repository_to = dir_to.find_repository()
744
except errors.NoRepositoryPresent:
747
# Found a branch, so we must have found a repository
748
repository_to = br_to.repository
750
if revision is not None:
751
if len(revision) == 1:
752
revision_id = revision[0].in_history(br_from).rev_id
754
raise errors.BzrCommandError(
755
'bzr push --revision takes one value.')
757
revision_id = br_from.last_revision()
763
# The destination doesn't exist; create it.
764
# XXX: Refactor the create_prefix/no_create_prefix code into a
765
# common helper function
767
def make_directory(transport):
771
def redirected(redirected_transport, e, redirection_notice):
772
return transport.get_transport(e.get_target_url())
775
to_transport = transport.do_catching_redirections(
776
make_directory, to_transport, redirected)
777
except errors.FileExists:
778
if not use_existing_dir:
779
raise errors.BzrCommandError("Target directory %s"
780
" already exists, but does not have a valid .bzr"
781
" directory. Supply --use-existing-dir to push"
782
" there anyway." % location)
783
except errors.NoSuchFile:
784
if not create_prefix:
785
raise errors.BzrCommandError("Parent directory of %s"
787
"\nYou may supply --create-prefix to create all"
788
" leading parent directories."
790
_create_prefix(to_transport)
791
except errors.TooManyRedirections:
792
raise errors.BzrCommandError("Too many redirections trying "
793
"to make %s." % location)
795
# Now the target directory exists, but doesn't have a .bzr
796
# directory. So we need to create it, along with any work to create
797
# all of the dependent branches, etc.
798
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
799
revision_id=revision_id)
800
br_to = dir_to.open_branch()
801
# TODO: Some more useful message about what was copied
802
note('Created new branch.')
803
# We successfully created the target, remember it
804
if br_from.get_push_location() is None or remember:
805
br_from.set_push_location(br_to.base)
806
elif repository_to is None:
807
# we have a bzrdir but no branch or repository
808
# XXX: Figure out what to do other than complain.
809
raise errors.BzrCommandError("At %s you have a valid .bzr control"
810
" directory, but not a branch or repository. This is an"
811
" unsupported configuration. Please move the target directory"
812
" out of the way and try again."
815
# We have a repository but no branch, copy the revisions, and then
817
repository_to.fetch(br_from.repository, revision_id=revision_id)
818
br_to = br_from.clone(dir_to, revision_id=revision_id)
819
note('Created new branch.')
820
if br_from.get_push_location() is None or remember:
821
br_from.set_push_location(br_to.base)
822
else: # We have a valid to branch
823
# We were able to connect to the remote location, so remember it
824
# we don't need to successfully push because of possible divergence.
825
if br_from.get_push_location() is None or remember:
826
br_from.set_push_location(br_to.base)
828
old_rh = br_to.revision_history()
831
tree_to = dir_to.open_workingtree()
832
except errors.NotLocalUrl:
833
warning("This transport does not update the working "
834
"tree of: %s. See 'bzr help working-trees' for "
835
"more information." % br_to.base)
836
push_result = br_from.push(br_to, overwrite,
837
stop_revision=revision_id)
838
except errors.NoWorkingTree:
839
push_result = br_from.push(br_to, overwrite,
840
stop_revision=revision_id)
844
push_result = br_from.push(tree_to.branch, overwrite,
845
stop_revision=revision_id)
849
except errors.DivergedBranches:
850
raise errors.BzrCommandError('These branches have diverged.'
851
' Try using "merge" and then "push".')
852
if push_result is not None:
853
push_result.report(self.outf)
855
new_rh = br_to.revision_history()
858
from bzrlib.log import show_changed_revisions
859
show_changed_revisions(br_to, old_rh, new_rh,
862
# we probably did a clone rather than a push, so a message was
1214
867
class cmd_branch(Command):
1215
__doc__ = """Create a new branch that is a copy of an existing branch.
868
"""Create a new copy of a branch.
1217
870
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1218
871
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1224
877
To retrieve the branch as of a particular revision, supply the --revision
1225
878
parameter, as in "branch foo/bar -r 5".
1227
The synonyms 'clone' and 'get' for this command are deprecated.
1230
881
_see_also = ['checkout']
1231
882
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."),
883
takes_options = ['revision', Option('hardlink',
884
help='Hard-link working tree files where possible.')]
1255
885
aliases = ['get', 'clone']
1257
887
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
1262
889
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')
892
elif len(revision) > 1:
893
raise errors.BzrCommandError(
894
'bzr branch --revision takes exactly 1 revision value')
1269
896
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))
900
if len(revision) == 1 and revision[0] is not None:
901
revision_id = revision[0].in_history(br_from)[1]
903
# FIXME - wt.last_revision, fallback to branch, fall back to
904
# None or perhaps NULL_REVISION to mean copy nothing
906
revision_id = br_from.last_revision()
907
if to_location is None:
908
to_location = urlutils.derive_to_location(from_location)
911
name = os.path.basename(to_location) + '\n'
913
to_transport = transport.get_transport(to_location)
915
to_transport.mkdir('.')
916
except errors.FileExists:
917
raise errors.BzrCommandError('Target directory "%s" already'
918
' exists.' % to_location)
919
except errors.NoSuchFile:
920
raise errors.BzrCommandError('Parent of "%s" does not exist.'
923
# preserve whatever source format we have.
924
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
925
possible_transports=[to_transport],
926
accelerator_tree=accelerator_tree,
928
branch = dir.open_branch()
929
except errors.NoSuchRevision:
930
to_transport.delete_tree('.')
931
msg = "The branch %s has no revision %s." % (from_location, revision[0])
932
raise errors.BzrCommandError(msg)
934
branch.control_files.put_utf8('branch-name', name)
935
_merge_tags_if_possible(br_from, branch)
936
note('Branched %d revision(s).' % branch.revno())
1377
941
class cmd_checkout(Command):
1378
__doc__ = """Create a new checkout of an existing branch.
942
"""Create a new checkout of an existing branch.
1380
944
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1381
945
the branch found in '.'. This is useful if you have removed the working tree
1382
946
or if it was never created - i.e. if you pushed the branch to its current
1383
947
location using SFTP.
1385
949
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1386
950
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1387
951
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1460
1024
@display_command
1461
1025
def run(self, dir=u'.'):
1462
1026
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))
1029
new_inv = tree.inventory
1030
old_tree = tree.basis_tree()
1031
old_tree.lock_read()
1033
old_inv = old_tree.inventory
1034
renames = list(_mod_tree.find_renames(old_inv, new_inv))
1036
for old_name, new_name in renames:
1037
self.outf.write("%s => %s\n" % (old_name, new_name))
1481
1044
class cmd_update(Command):
1482
__doc__ = """Update a tree to have the latest code committed to its branch.
1045
"""Update a tree to have the latest code committed to its branch.
1484
1047
This will perform a merge into the working tree, and may generate
1485
conflicts. If you have any local changes, you will still
1048
conflicts. If you have any local changes, you will still
1486
1049
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
1051
If you want to discard your local changes, you can just do a
1489
1052
'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
1055
_see_also = ['pull', 'working-trees', 'status-flags']
1499
1056
takes_args = ['dir?']
1500
takes_options = ['revision',
1502
help="Show base revision text in conflicts."),
1504
1057
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"))
1059
def run(self, dir='.'):
1510
1060
tree = WorkingTree.open_containing(dir)[0]
1511
branch = tree.branch
1512
1061
possible_transports = []
1513
master = branch.get_master_branch(
1062
master = tree.branch.get_master_branch(
1514
1063
possible_transports=possible_transports)
1515
1064
if master is not None:
1516
branch_location = master.base
1517
1065
tree.lock_write()
1519
branch_location = tree.branch.base
1520
1067
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)
1069
existing_pending_merges = tree.get_parent_ids()[1:]
1070
last_rev = _mod_revision.ensure_null(tree.last_revision())
1071
if last_rev == _mod_revision.ensure_null(
1072
tree.branch.last_revision()):
1073
# may be up to date, check master too.
1074
if master is None or last_rev == _mod_revision.ensure_null(
1075
master.last_revision()):
1076
revno = tree.branch.revision_id_to_revno(last_rev)
1077
note("Tree is up to date at revision %d." % (revno,))
1548
1079
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'."))
1080
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1081
possible_transports=possible_transports)
1082
revno = tree.branch.revision_id_to_revno(
1083
_mod_revision.ensure_null(tree.last_revision()))
1084
note('Updated to revision %d.' % (revno,))
1085
if tree.get_parent_ids()[1:] != existing_pending_merges:
1086
note('Your local commits will now show as pending merges with '
1087
"'bzr status', and can be committed with 'bzr commit'.")
1574
1096
class cmd_info(Command):
1575
__doc__ = """Show information about a working tree, branch or repository.
1097
"""Show information about a working tree, branch or repository.
1577
1099
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.
1100
tree, branch or repository. Statistical information is included with
1584
1103
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
1105
_see_also = ['revno', 'working-trees', 'repositories']
1603
1106
takes_args = ['location?']
2236
1634
return int(limitstring)
2237
1635
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.")
1636
msg = "The limit argument must be an integer."
2247
1637
raise errors.BzrCommandError(msg)
2250
1640
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.
1641
"""Show log of a branch, file, or directory.
1643
By default show the log of the branch containing the working directory.
1645
To request a range of logs, you can use the command -r begin..end
1646
-r revision requests a specific revision, -r ..end or -r begin.. are
1650
Log the current branch::
1658
Log the last 10 revisions of a branch::
1660
bzr log -r -10.. http://server/branch
2405
takes_args = ['file*']
2406
_see_also = ['log-formats', 'revisionspec']
1663
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1665
takes_args = ['location?']
2407
1666
takes_options = [
2408
1667
Option('forward',
2409
1668
help='Show from oldest to newest.'),
1671
help='Display timezone as local, original, or utc.'),
2411
1672
custom_help('verbose',
2412
1673
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
1677
Option('message',
2432
1679
help='Show revisions whose message matches this '
2433
1680
'regular expression.',
2436
1682
Option('limit',
2437
1683
short_name='l',
2438
1684
help='Limit the output to the first N revisions.',
2440
1686
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
1688
encoding_type = 'replace'
2480
1690
@display_command
2481
def run(self, file_list=None, timezone='original',
1691
def run(self, location=None, timezone='original',
2483
1693
show_ids=False,
2487
1696
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,
1699
from bzrlib.log import show_log
1700
assert message is None or isinstance(message, basestring), \
1701
"invalid message argument %r" % message
2509
1702
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:
1707
# find the file id to log:
1709
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1713
tree = b.basis_tree()
1714
file_id = tree.path2id(fp)
2554
1715
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'])
1716
raise errors.BzrCommandError(
1717
"Path does not have any revision history: %s" %
2568
# FIXME ? log the current subdir only RBC 20060203
1721
# FIXME ? log the current subdir only RBC 20060203
2569
1722
if revision is not None \
2570
1723
and len(revision) > 0 and revision[0].get_branch():
2571
1724
location = revision[0].get_branch()
2574
1727
dir, relpath = bzrdir.BzrDir.open_containing(location)
2575
1728
b = dir.open_branch()
2576
self.add_cleanup(b.lock_read().unlock)
2577
rev1, rev2 = _get_revision_range(revision, b, self.name())
2579
if b.get_config().validate_signatures_in_log():
2583
if not gpg.GPGStrategy.verify_signatures_available():
2584
raise errors.GpgmeNotInstalled(None)
2586
# Decide on the type of delta & diff filtering to use
2587
# TODO: add an --all-files option to make this configurable & consistent
2595
diff_type = 'partial'
2599
# Build the log formatter
2600
if log_format is None:
2601
log_format = log.log_formatter_registry.get_default(b)
2602
# Make a non-encoding output to include the diffs - bug 328007
2603
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2604
lf = log_format(show_ids=show_ids, to_file=self.outf,
2605
to_exact_file=unencoded_output,
2606
show_timezone=timezone,
2607
delta_format=get_verbosity_level(),
2609
show_advice=levels is None,
2610
author_list_handler=authors)
2612
# Choose the algorithm for doing the logging. It's annoying
2613
# having multiple code paths like this but necessary until
2614
# the underlying repository format is faster at generating
2615
# deltas or can provide everything we need from the indices.
2616
# The default algorithm - match-using-deltas - works for
2617
# multiple files and directories and is faster for small
2618
# amounts of history (200 revisions say). However, it's too
2619
# slow for logging a single file in a repository with deep
2620
# history, i.e. > 10K revisions. In the spirit of "do no
2621
# evil when adding features", we continue to use the
2622
# original algorithm - per-file-graph - for the "single
2623
# file that isn't a directory without showing a delta" case.
2624
partial_history = revision and b.repository._format.supports_chks
2625
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2626
or delta_type or partial_history)
2630
match_dict[''] = match
2632
match_dict['message'] = match_message
2634
match_dict['committer'] = match_committer
2636
match_dict['author'] = match_author
2638
match_dict['bugs'] = match_bugs
2640
# Build the LogRequest and execute it
2641
if len(file_ids) == 0:
2643
rqst = make_log_request_dict(
2644
direction=direction, specific_fileids=file_ids,
2645
start_revision=rev1, end_revision=rev2, limit=limit,
2646
message_search=message, delta_type=delta_type,
2647
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2648
exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
2649
signature=signatures, omit_merges=omit_merges,
2651
Logger(b, rqst).show(lf)
2654
def _get_revision_range(revisionspec_list, branch, command_name):
2655
"""Take the input of a revision option and turn it into a revision range.
2657
It returns RevisionInfo objects which can be used to obtain the rev_id's
2658
of the desired revisions. It does some user input validations.
2660
if revisionspec_list is None:
2663
elif len(revisionspec_list) == 1:
2664
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2665
elif len(revisionspec_list) == 2:
2666
start_spec = revisionspec_list[0]
2667
end_spec = revisionspec_list[1]
2668
if end_spec.get_branch() != start_spec.get_branch():
2669
# b is taken from revision[0].get_branch(), and
2670
# show_log will use its revision_history. Having
2671
# different branches will lead to weird behaviors.
2672
raise errors.BzrCommandError(gettext(
2673
"bzr %s doesn't accept two revisions in different"
2674
" branches.") % command_name)
2675
if start_spec.spec is None:
2676
# Avoid loading all the history.
2677
rev1 = RevisionInfo(branch, None, None)
2679
rev1 = start_spec.in_history(branch)
2680
# Avoid loading all of history when we know a missing
2681
# end of range means the last revision ...
2682
if end_spec.spec is None:
2683
last_revno, last_revision_id = branch.last_revision_info()
2684
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2686
rev2 = end_spec.in_history(branch)
2688
raise errors.BzrCommandError(gettext(
2689
'bzr %s --revision takes one or two values.') % command_name)
2693
def _revision_range_to_revid_range(revision_range):
2696
if revision_range[0] is not None:
2697
rev_id1 = revision_range[0].rev_id
2698
if revision_range[1] is not None:
2699
rev_id2 = revision_range[1].rev_id
2700
return rev_id1, rev_id2
1732
if revision is None:
1735
elif len(revision) == 1:
1736
rev1 = rev2 = revision[0].in_history(b)
1737
elif len(revision) == 2:
1738
if revision[1].get_branch() != revision[0].get_branch():
1739
# b is taken from revision[0].get_branch(), and
1740
# show_log will use its revision_history. Having
1741
# different branches will lead to weird behaviors.
1742
raise errors.BzrCommandError(
1743
"Log doesn't accept two revisions in different"
1745
rev1 = revision[0].in_history(b)
1746
rev2 = revision[1].in_history(b)
1748
raise errors.BzrCommandError(
1749
'bzr log --revision takes one or two values.')
1751
if log_format is None:
1752
log_format = log.log_formatter_registry.get_default(b)
1754
lf = log_format(show_ids=show_ids, to_file=self.outf,
1755
show_timezone=timezone)
1761
direction=direction,
1762
start_revision=rev1,
2702
1770
def get_log_format(long=False, short=False, line=False, default='long'):
2703
1771
log_format = default
2722
1790
@display_command
2723
1791
def run(self, filename):
2724
1792
tree, relpath = WorkingTree.open_containing(filename)
2725
1794
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:
1795
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2730
1796
self.outf.write("%6d %s\n" % (revno, what))
2733
1799
class cmd_ls(Command):
2734
__doc__ = """List files in a tree.
1800
"""List files in a tree.
2737
1803
_see_also = ['status', 'cat']
2738
1804
takes_args = ['path?']
1805
# TODO: Take a revision or remote path and list that tree instead.
2739
1806
takes_options = [
2742
Option('recursive', short_name='R',
2743
help='Recurse into subdirectories.'),
1809
Option('non-recursive',
1810
help='Don\'t recurse into subdirectories.'),
2744
1811
Option('from-root',
2745
1812
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',
1813
Option('unknown', help='Print unknown files.'),
1814
Option('versioned', help='Print versioned files.'),
1815
Option('ignored', help='Print ignored files.'),
1817
help='Write an ascii NUL (\\0) separator '
1818
'between files rather than a newline.'),
2753
1820
help='List entries of a particular kind: file, directory, symlink.',
2759
1824
@display_command
2760
1825
def run(self, revision=None, verbose=False,
2761
recursive=False, from_root=False,
1826
non_recursive=False, from_root=False,
2762
1827
unknown=False, versioned=False, ignored=False,
2763
null=False, kind=None, show_ids=False, path=None, directory=None):
1828
null=False, kind=None, show_ids=False, path=None):
2765
1830
if kind and kind not in ('file', 'directory', 'symlink'):
2766
raise errors.BzrCommandError(gettext('invalid kind specified'))
1831
raise errors.BzrCommandError('invalid kind specified')
2768
1833
if verbose and null:
2769
raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
1834
raise errors.BzrCommandError('Cannot set both --verbose and --null')
2770
1835
all = not (unknown or versioned or ignored)
2772
1837
selection = {'I':ignored, '?':unknown, 'V':versioned}
2774
1839
if path is None:
2778
raise errors.BzrCommandError(gettext('cannot specify both --from-root'
1844
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
1848
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')
1854
if revision is not None:
1855
tree = branch.repository.revision_tree(
1856
revision[0].in_history(branch).rev_id)
1858
tree = branch.basis_tree()
1862
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1863
if fp.startswith(relpath):
1864
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1865
if non_recursive and '/' in fp:
1867
if not all and not selection[fc]:
1869
if kind is not None and fkind != kind:
1872
kindch = entry.kind_character()
1873
outstring = '%-8s %s%s' % (fc, fp, kindch)
1874
if show_ids and fid is not None:
1875
outstring = "%-50s %s" % (outstring, fid)
1876
self.outf.write(outstring + '\n')
1878
self.outf.write(fp + '\0')
1881
self.outf.write(fid)
1882
self.outf.write('\0')
1890
self.outf.write('%-50s %s\n' % (fp, my_id))
1892
self.outf.write(fp + '\n')
2850
1897
class cmd_unknowns(Command):
2851
__doc__ = """List unknown files.
1898
"""List unknown files.
2855
1902
_see_also = ['ls']
2856
takes_options = ['directory']
2858
1904
@display_command
2859
def run(self, directory=u'.'):
2860
for f in WorkingTree.open_containing(directory)[0].unknowns():
1906
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2861
1907
self.outf.write(osutils.quotefn(f) + '\n')
2864
1910
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.
1911
"""Ignore specified files or patterns.
2875
1913
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.
1915
Trailing slashes on patterns are ignored.
1916
If the pattern contains a slash or is a regular expression, it is compared
1917
to the whole path from the branch root. Otherwise, it is compared to only
1918
the last component of the path. To match a file only in the root
1919
directory, prepend './'.
1921
Ignore patterns specifying absolute paths are not allowed.
1923
Ignore patterns may include globbing wildcards such as::
1925
? - Matches any single character except '/'
1926
* - Matches 0 or more characters except '/'
1927
/**/ - Matches 0 or more directories in a path
1928
[a-z] - Matches a single character from within a group of characters
1930
Ignore patterns may also be Python regular expressions.
1931
Regular expression ignore patterns are identified by a 'RE:' prefix
1932
followed by the regular expression. Regular expression ignore patterns
1933
may not include named or numbered groups.
1935
Note: ignore patterns containing shell wildcards must be quoted from
2902
1939
Ignore the top level Makefile::
2904
1941
bzr ignore ./Makefile
2906
Ignore .class files in all directories...::
1943
Ignore class files in all directories::
2908
1945
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
1947
Ignore .o files under the lib directory::
2920
1949
bzr ignore "lib/**/*.o"
2926
1955
Ignore everything but the "debian" toplevel directory::
2928
1957
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"
2938
_see_also = ['status', 'ignored', 'patterns']
1960
_see_also = ['status', 'ignored']
2939
1961
takes_args = ['name_pattern*']
2940
takes_options = ['directory',
2941
Option('default-rules',
2942
help='Display the default ignore rules that bzr uses.')
1963
Option('old-default-rules',
1964
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)
1967
def run(self, name_pattern_list=None, old_default_rules=None):
1968
from bzrlib.atomicfile import AtomicFile
1969
if old_default_rules is not None:
1970
# dump the rules and exit
1971
for pattern in ignores.OLD_DEFAULTS:
2953
1974
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)
1975
raise errors.BzrCommandError("ignore requires at least one "
1976
"NAME_PATTERN or --old-default-rules")
1977
name_pattern_list = [globbing.normalize_pattern(p)
2957
1978
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
1979
for name_pattern in name_pattern_list:
2971
if (name_pattern[0] == '/' or
1980
if (name_pattern[0] == '/' or
2972
1981
(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)
1982
raise errors.BzrCommandError(
1983
"NAME_PATTERN should not be an absolute path")
1984
tree, relpath = WorkingTree.open_containing(u'.')
1985
ifn = tree.abspath('.bzrignore')
1986
if os.path.exists(ifn):
1989
igns = f.read().decode('utf-8')
1995
# TODO: If the file already uses crlf-style termination, maybe
1996
# we should use that for the newly added lines?
1998
if igns and igns[-1] != '\n':
2000
for name_pattern in name_pattern_list:
2001
igns += name_pattern + '\n'
2003
f = AtomicFile(ifn, 'wb')
2005
f.write(igns.encode('utf-8'))
2010
if not tree.path2id('.bzrignore'):
2011
tree.add(['.bzrignore'])
2977
2013
ignored = globbing.Globster(name_pattern_list)
2979
self.add_cleanup(tree.lock_read().unlock)
2980
2016
for entry in tree.list_files():
2982
2018
if id is not None:
2983
2019
filename = entry[0]
2984
2020
if ignored.match(filename):
2985
matches.append(filename)
2021
matches.append(filename.encode('utf-8'))
2986
2023
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),))
2024
print "Warning: the following files are version controlled and" \
2025
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2993
2027
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::
2028
"""List ignored files and the patterns that matched them.
3004
2031
encoding_type = 'replace'
3005
_see_also = ['ignore', 'ls']
3006
takes_options = ['directory']
2032
_see_also = ['ignore']
3008
2034
@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))
2036
tree = WorkingTree.open_containing(u'.')[0]
2039
for path, file_class, kind, file_id, entry in tree.list_files():
2040
if file_class != 'I':
2042
## XXX: Slightly inefficient since this was already calculated
2043
pat = tree.is_ignored(path)
2044
self.outf.write('%-50s %s\n' % (path, pat))
3020
2049
class cmd_lookup_revision(Command):
3021
__doc__ = """Lookup the revision-id from a revision-number
2050
"""Lookup the revision-id from a revision-number
3024
2053
bzr lookup-revision 33
3027
2056
takes_args = ['revno']
3028
takes_options = ['directory']
3030
2058
@display_command
3031
def run(self, revno, directory=u'.'):
2059
def run(self, revno):
3033
2061
revno = int(revno)
3034
2062
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)
2063
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2065
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
3041
2068
class cmd_export(Command):
3042
__doc__ = """Export current or past revision to a destination directory or archive.
2069
"""Export current or past revision to a destination directory or archive.
3044
2071
If no revision is specified this exports the last committed revision.
3067
2094
================= =========================
3070
takes_args = ['dest', 'branch_or_subdir?']
3071
takes_options = ['directory',
2096
takes_args = ['dest', 'branch?']
3072
2098
Option('format',
3073
2099
help="Type of file to export to.",
3076
Option('filters', help='Apply content filters to export the '
3077
'convenient form.'),
3080
2104
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'.'):
2106
def run(self, dest, branch=None, revision=None, format=None, root=None):
3087
2107
from bzrlib.export import export
3089
if branch_or_subdir is None:
3090
tree = WorkingTree.open_containing(directory)[0]
2110
tree = WorkingTree.open_containing(u'.')[0]
3091
2111
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)
2113
b = Branch.open(branch)
2115
if revision is None:
2116
# should be tree.last_revision FIXME
2117
rev_id = b.last_revision()
2119
if len(revision) != 1:
2120
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2121
rev_id = revision[0].in_history(b).rev_id
2122
t = b.repository.revision_tree(rev_id)
3099
export(rev_tree, dest, format, root, subdir, filtered=filters,
3100
per_file_timestamps=per_file_timestamps)
2124
export(t, dest, format, root)
3101
2125
except errors.NoSuchExportFormat, e:
3102
raise errors.BzrCommandError(gettext('Unsupported export format: %s') % e.format)
2126
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
3105
2129
class cmd_cat(Command):
3106
__doc__ = """Write the contents of a file as of a given revision to standard output.
2130
"""Write the contents of a file as of a given revision to standard output.
3108
2132
If no revision is nominated, the last revision is used.
3110
2134
Note: Take care to redirect standard output when using this command on a
3114
2138
_see_also = ['ls']
3115
takes_options = ['directory',
3116
2140
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
2143
takes_args = ['filename']
3122
2144
encoding_type = 'exact'
3124
2146
@display_command
3125
def run(self, filename, revision=None, name_from_revision=False,
3126
filters=False, directory=None):
2147
def run(self, filename, revision=None, name_from_revision=False):
3127
2148
if revision is not None and len(revision) != 1:
3128
raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3129
" one revision specifier"))
2149
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2150
" one revision specifier")
3130
2151
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)
2152
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2155
return self._run(tree, branch, relpath, filename, revision,
3136
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2160
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
3138
2161
if tree is None:
3139
2162
tree = b.basis_tree()
3140
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3141
self.add_cleanup(rev_tree.lock_read().unlock)
2163
if revision is None:
2164
revision_id = b.last_revision()
2166
revision_id = revision[0].in_history(b).rev_id
2168
cur_file_id = tree.path2id(relpath)
2169
rev_tree = b.repository.revision_tree(revision_id)
3143
2170
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
2172
if name_from_revision:
3150
# Try in revision if requested
3151
2173
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)
2174
raise errors.BzrCommandError("%r is not present in revision %s"
2175
% (filename, revision_id))
2177
rev_tree.print_file(old_file_id)
2178
elif cur_file_id is not None:
2179
rev_tree.print_file(cur_file_id)
2180
elif old_file_id is not None:
2181
rev_tree.print_file(old_file_id)
2183
raise errors.BzrCommandError("%r is not present in revision %s" %
2184
(filename, revision_id))
3178
2187
class cmd_local_time_offset(Command):
3179
__doc__ = """Show the offset in seconds from GMT to local time."""
2188
"""Show the offset in seconds from GMT to local time."""
3181
2190
@display_command
3183
self.outf.write("%s\n" % osutils.local_time_offset())
2192
print osutils.local_time_offset()
3187
2196
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.
2197
"""Commit changes into a new revision.
2199
If no arguments are given, the entire tree is committed.
2201
If selected files are specified, only changes to those files are
2202
committed. If a directory is specified then the directory and everything
2203
within it is committed.
2205
If author of the change is not the same person as the committer, you can
2206
specify the author's name using the --author option. The name should be
2207
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2209
A selected-file commit may fail in some cases where the committed
2210
tree would be invalid. Consider::
2215
bzr commit foo -m "committing foo"
2216
bzr mv foo/bar foo/baz
2219
bzr commit foo/bar -m "committing bar but not baz"
2221
In the example above, the last commit will fail by design. This gives
2222
the user the opportunity to decide whether they want to commit the
2223
rename at the same time, separately first, or not at all. (As a general
2224
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2226
Note: A selected-file commit after a merge is not yet supported.
3244
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
2228
# TODO: Run hooks on tree to-be-committed, and after commit.
2230
# TODO: Strict commit that fails if there are deleted files.
2231
# (what does "deleted files" mean ??)
2233
# TODO: Give better message for -s, --summary, used by tla people
2235
# XXX: verbose currently does nothing
2237
_see_also = ['bugs', 'uncommit']
3245
2238
takes_args = ['selected*']
3246
2239
takes_options = [
3247
ListOption('exclude', type=str, short_name='x',
3248
help="Do not consider changes made to a given path."),
3249
2240
Option('message', type=unicode,
3250
2241
short_name='m',
3251
2242
help="Description of the new revision."),
3355
2320
if fixes is None:
3357
bug_property = bugtracker.encode_fixes_bug_urls(
3358
self._iter_bug_fix_urls(fixes, tree.branch))
2322
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
3359
2323
if bug_property:
3360
2324
properties['bugs'] = bug_property
3362
2326
if local and not tree.branch.get_bound_location():
3363
2327
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
2329
def get_message(commit_obj):
3387
2330
"""Callback to get commit message"""
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,
2331
my_message = message
2332
if my_message is None and not file:
2333
t = make_commit_message_template_encoded(tree,
3400
2334
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 \"\"."))
2335
output_encoding=bzrlib.user_encoding)
2336
my_message = edit_commit_message_encoded(t)
2337
if my_message is None:
2338
raise errors.BzrCommandError("please specify a commit"
2339
" message with either --message or --file")
2340
elif my_message and file:
2341
raise errors.BzrCommandError(
2342
"please specify either --message or --file")
2344
my_message = codecs.open(file, 'rt',
2345
bzrlib.user_encoding).read()
2346
if my_message == "":
2347
raise errors.BzrCommandError("empty commit message specified")
3420
2348
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
3427
2351
tree.commit(message_callback=get_message,
3428
2352
specific_files=selected_list,
3429
2353
allow_pointless=unchanged, strict=strict, local=local,
3430
2354
reporter=None, verbose=verbose, revprops=properties,
3431
authors=author, timestamp=commit_stamp,
3433
exclude=tree.safe_relpath_files(exclude),
3435
2356
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."))
2357
# FIXME: This should really happen before the file is read in;
2358
# perhaps prepare the commit; get the message; then actually commit
2359
raise errors.BzrCommandError("no changes to commit."
2360
" use --unchanged to commit anyhow")
3439
2361
except ConflictsInTree:
3440
raise errors.BzrCommandError(gettext('Conflicts detected in working '
2362
raise errors.BzrCommandError('Conflicts detected in working '
3441
2363
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
3443
2365
except StrictCommitFailed:
3444
raise errors.BzrCommandError(gettext("Commit refused because there are"
3445
" unknown files in the working tree."))
2366
raise errors.BzrCommandError("Commit refused because there are"
2367
" unknown files in the working tree.")
3446
2368
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 '
2369
raise errors.BzrCommandError(str(e) + "\n"
2370
'To commit to master branch, run update and then commit.\n'
2371
'You can also pass --local to commit to continue working '
3454
2375
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'::
2376
"""Validate consistency of branch history.
2378
This command checks various invariants about the branch storage to
2379
detect data corruption or bzr bugs.
2383
revisions: This is just the number of revisions checked. It doesn't
2385
versionedfiles: This is just the number of versionedfiles checked. It
2386
doesn't indicate a problem.
2387
unreferenced ancestors: Texts that are ancestors of other texts, but
2388
are not properly referenced by the revision ancestry. This is a
2389
subtle problem that Bazaar can work around.
2390
unique file texts: This is the total number of unique file contents
2391
seen in the checked revisions. It does not indicate a problem.
2392
repeated file texts: This is the total number of repeated texts seen
2393
in the checked revisions. Texts can be repeated when their file
2394
entries are modified, but the file contents are not. It does not
3504
2398
_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.")]
2399
takes_args = ['branch?']
2400
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)
2402
def run(self, branch=None, verbose=False):
2403
from bzrlib.check import check
2405
branch_obj = Branch.open_containing('.')[0]
2407
branch_obj = Branch.open(branch)
2408
check(branch_obj, verbose)
2409
# bit hacky, check the tree parent is accurate
2412
tree = WorkingTree.open_containing('.')[0]
2414
tree = WorkingTree.open(branch)
2415
except (errors.NoWorkingTree, errors.NotLocalUrl):
2418
# This is a primitive 'check' for tree state. Currently this is not
2419
# integrated into the main check logic as yet.
2422
tree_basis = tree.basis_tree()
2423
tree_basis.lock_read()
2425
repo_basis = tree.branch.repository.revision_tree(
2426
tree.last_revision())
2427
if len(list(repo_basis.iter_changes(tree_basis))):
2428
raise errors.BzrCheckError(
2429
"Mismatched basis inventory content.")
3524
2437
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/.
2438
"""Upgrade branch storage to current format.
2440
The check command or bzr developers may sometimes advise you to run
2441
this command. When the default format has changed you may also be warned
2442
during other operations to upgrade.
3557
_see_also = ['check', 'reconcile', 'formats']
2445
_see_also = ['check']
3558
2446
takes_args = ['url?']
3559
2447
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."),
2448
RegistryOption('format',
2449
help='Upgrade to a specific format. See "bzr help'
2450
' formats" for details.',
2451
registry=bzrdir.format_registry,
2452
converter=bzrdir.format_registry.make_bzrdir,
2453
value_switches=True, title='Branch format'),
3572
def run(self, url='.', format=None, clean=False, dry_run=False):
2456
def run(self, url='.', format=None):
3573
2457
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
2459
format = bzrdir.format_registry.make_bzrdir('default')
2460
upgrade(url, format)
3583
2463
class cmd_whoami(Command):
3584
__doc__ = """Show or set bzr user id.
2464
"""Show or set bzr user id.
3587
2467
Show the email of the current user::
3814
2603
'throughout the test suite.',
3815
2604
type=get_transport_type),
3816
2605
Option('benchmark',
3817
help='Run the benchmarks rather than selftests.',
2606
help='Run the benchmarks rather than selftests.'),
3819
2607
Option('lsprof-timed',
3820
2608
help='Generate lsprof output for benchmarked'
3821
2609
' sections of code.'),
3822
Option('lsprof-tests',
3823
help='Generate lsprof output for each test.'),
2610
Option('cache-dir', type=str,
2611
help='Cache intermediate benchmark output in this '
3824
2613
Option('first',
3825
2614
help='Run all tests, but run specified tests first.',
3826
2615
short_name='f',
3828
2617
Option('list-only',
3829
2618
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
2619
Option('randomize', type=str, argname="SEED",
3836
2620
help='Randomize the order of tests using the given'
3837
2621
' 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.'),
2622
Option('exclude', type=str, argname="PATTERN",
2624
help='Exclude tests that match this regular'
3844
2626
Option('strict', help='Fail on missing dependencies or '
3845
2627
'known failures.'),
3846
2628
Option('load-list', type=str, argname='TESTLISTFILE',
3847
2629
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
2631
encoding_type = 'replace'
3861
Command.__init__(self)
3862
self.additional_selftest_args = {}
3864
2633
def run(self, testspecs_list=None, verbose=False, one=False,
3865
2634
transport=None, benchmark=None,
2635
lsprof_timed=None, cache_dir=None,
3867
2636
first=False, list_only=False,
3868
2637
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
2640
from bzrlib.tests import selftest
2641
import bzrlib.benchmarks as benchmarks
2642
from bzrlib.benchmarks import tree_creator
2644
if cache_dir is not None:
2645
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2647
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2648
print ' %s (%s python%s)' % (
2650
bzrlib.version_string,
2651
'.'.join(map(str, sys.version_info)),
3874
2654
if testspecs_list is not None:
3875
2655
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
2659
test_suite_factory = benchmarks.test_suite
2660
# Unless user explicitly asks for quiet, be verbose in benchmarks
2661
verbose = not is_quiet()
2662
# TODO: should possibly lock the history file...
2663
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(
2665
test_suite_factory = None
3930
result = tests.selftest(**selftest_kwargs)
2668
result = selftest(verbose=verbose,
2670
stop_on_failure=one,
2671
transport=transport,
2672
test_suite_factory=test_suite_factory,
2673
lsprof_timed=lsprof_timed,
2674
bench_history=benchfile,
2675
matching_tests_first=first,
2676
list_only=list_only,
2677
random_seed=randomize,
2678
exclude_pattern=exclude,
2680
load_list=load_list,
2683
if benchfile is not None:
2686
note('tests passed')
2688
note('tests failed')
3933
2689
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
2692
class cmd_version(Command):
3946
__doc__ = """Show version of bzr."""
2693
"""Show version of bzr."""
3948
2695
encoding_type = 'replace'
3950
Option("short", help="Print just the version number."),
3953
2697
@display_command
3954
def run(self, short=False):
3955
2699
from bzrlib.version import show_version
3957
self.outf.write(bzrlib.version_string + '\n')
3959
show_version(to_file=self.outf)
2700
show_version(to_file=self.outf)
3962
2703
class cmd_rocks(Command):
3963
__doc__ = """Statement of optimism."""
2704
"""Statement of optimism."""
3967
2708
@display_command
3969
self.outf.write(gettext("It sure does!\n"))
2710
print "It sure does!"
3972
2713
class cmd_find_merge_base(Command):
3973
__doc__ = """Find and print a base revision for merging two branches."""
2714
"""Find and print a base revision for merging two branches."""
3974
2715
# TODO: Options to specify revisions on either side, as if
3975
2716
# merging only part of the history.
3976
2717
takes_args = ['branch', 'other']
3979
2720
@display_command
3980
2721
def run(self, branch, other):
3981
2722
from bzrlib.revision import ensure_null
3983
2724
branch1 = Branch.open_containing(branch)[0]
3984
2725
branch2 = Branch.open_containing(other)[0]
3985
self.add_cleanup(branch1.lock_read().unlock)
3986
self.add_cleanup(branch2.lock_read().unlock)
3987
last1 = ensure_null(branch1.last_revision())
3988
last2 = ensure_null(branch2.last_revision())
3990
graph = branch1.repository.get_graph(branch2.repository)
3991
base_rev_id = graph.find_unique_lca(last1, last2)
3993
self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
2730
last1 = ensure_null(branch1.last_revision())
2731
last2 = ensure_null(branch2.last_revision())
2733
graph = branch1.repository.get_graph(branch2.repository)
2734
base_rev_id = graph.find_unique_lca(last1, last2)
2736
print 'merge base is revision %s' % base_rev_id
3996
2743
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.
2744
"""Perform a three-way merge.
2746
The branch is the branch you will merge from. By default, it will merge
2747
the latest revision. If you specify a revision, that revision will be
2748
merged. If you specify two revisions, the first will be used as a BASE,
2749
and the second one as OTHER. Revision numbers are always relative to the
2752
By default, bzr will try to merge in all new work from the other
2753
branch, automatically determining an appropriate base. If this
2754
fails, you may need to give an explicit base.
4024
2756
Merge will do its best to combine the changes in two branches, but there
4025
2757
are some kinds of problems only a human can fix. When it encounters those,
4026
2758
it will mark a conflict. A conflict means that you need to fix something,
4119
2833
allow_pending = True
4120
2834
verified = 'inapplicable'
4122
2835
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'))
2836
change_reporter = delta._ChangeReporter(
2837
unversioned_filter=tree.is_ignored)
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
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:
2840
pb = ui.ui_factory.nested_progress_bar()
2841
cleanups.append(pb.finished)
2843
cleanups.append(tree.unlock)
2844
if location is not None:
2845
mergeable, other_transport = _get_mergeable_helper(location)
2848
raise errors.BzrCommandError('Cannot use --uncommitted'
2849
' with bundles or merge directives.')
2851
if revision is not None:
2852
raise errors.BzrCommandError(
2853
'Cannot use -r with merge directives or bundles')
2854
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2856
possible_transports.append(other_transport)
2858
if merger is None and uncommitted:
2859
if revision is not None and len(revision) > 0:
2860
raise errors.BzrCommandError('Cannot use --uncommitted and'
2861
' --revision at the same time.')
2862
location = self._select_branch_location(tree, location)[0]
2863
other_tree, other_path = WorkingTree.open_containing(location)
2864
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2866
allow_pending = False
2867
if other_path != '':
2868
merger.interesting_files = [other_path]
2871
merger, allow_pending = self._get_merger_from_branch(tree,
2872
location, revision, remember, possible_transports, pb)
2874
merger.merge_type = merge_type
2875
merger.reprocess = reprocess
2876
merger.show_base = show_base
2877
self.sanity_check_merger(merger)
2878
if (merger.base_rev_id == merger.other_rev_id and
2879
merger.other_rev_id != None):
2880
note('Nothing to do.')
2883
if merger.interesting_files is not None:
2884
raise errors.BzrCommandError('Cannot pull individual files')
2885
if (merger.base_rev_id == tree.last_revision()):
2886
result = tree.pull(merger.other_branch, False,
2887
merger.other_rev_id)
2888
result.report(self.outf)
2890
merger.check_basis(not force)
2892
return self._do_preview(merger)
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):
2894
return self._do_merge(merger, change_reporter, allow_pending,
2897
for cleanup in reversed(cleanups):
2900
def _do_preview(self, merger):
2901
from bzrlib.diff import show_diff_trees
4207
2902
tree_merger = merger.make_merger()
4208
2903
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)
2905
result_tree = tt.get_preview_tree()
2906
show_diff_trees(merger.this_tree, result_tree, self.outf,
2907
old_label='', new_label='')
4221
2911
def _do_merge(self, merger, change_reporter, allow_pending, verified):
4222
2912
merger.change_reporter = change_reporter
4580
3227
class cmd_shell_complete(Command):
4581
__doc__ = """Show appropriate completions for context.
3228
"""Show appropriate completions for context.
4583
3230
For a list of all available commands, say 'bzr shell-complete'.
4585
3232
takes_args = ['context?']
4586
3233
aliases = ['s-c']
4589
3236
@display_command
4590
3237
def run(self, context=None):
4591
3238
import shellcomplete
4592
3239
shellcomplete.shellcomplete(context)
3242
class cmd_fetch(Command):
3243
"""Copy in history from another branch but don't merge it.
3245
This is an internal method used for pull and merge.
3248
takes_args = ['from_branch', 'to_branch']
3249
def run(self, from_branch, to_branch):
3250
from bzrlib.fetch import Fetcher
3251
from_b = Branch.open(from_branch)
3252
to_b = Branch.open(to_branch)
3253
Fetcher(to_b, from_b)
4595
3256
class cmd_missing(Command):
4596
__doc__ = """Show unmerged/unpulled revisions between two branches.
3257
"""Show unmerged/unpulled revisions between two branches.
4598
3259
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
3262
_see_also = ['merge', 'pull']
4631
3263
takes_args = ['other_branch?']
4632
3264
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.'),
3265
Option('reverse', 'Reverse the order of revisions.'),
3267
'Display changes in the local branch only.'),
3268
Option('this' , 'Same as --mine-only.'),
3269
Option('theirs-only',
3270
'Display changes in the remote branch only.'),
3271
Option('other', 'Same as --theirs-only.'),
4656
3276
encoding_type = 'replace'
4658
3278
@display_command
4659
3279
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):
3280
theirs_only=False, log_format=None, long=False, short=False, line=False,
3281
show_ids=False, verbose=False, this=False, other=False):
4666
3282
from bzrlib.missing import find_unmerged, iter_log_revisions
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)
3289
local_branch = Branch.open_containing(u".")[0]
4702
3290
parent = local_branch.get_parent()
4703
3291
if other_branch is None:
4704
3292
other_branch = parent
4705
3293
if other_branch is None:
4706
raise errors.BzrCommandError(gettext("No peer location known"
3294
raise errors.BzrCommandError("No peer location known"
4708
3296
display_url = urlutils.unescape_for_display(parent,
4709
3297
self.outf.encoding)
4710
message(gettext("Using saved parent location: {0}\n").format(
3298
self.outf.write("Using last location: " + display_url + "\n")
4713
3300
remote_branch = Branch.open(other_branch)
4714
3301
if remote_branch.base == local_branch.base:
4715
3302
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"))
3303
local_branch.lock_read()
3305
remote_branch.lock_read()
3307
local_extra, remote_extra = find_unmerged(local_branch,
3309
if log_format is None:
3310
registry = log.log_formatter_registry
3311
log_format = registry.get_default(local_branch)
3312
lf = log_format(to_file=self.outf,
3314
show_timezone='original')
3315
if reverse is False:
3316
local_extra.reverse()
3317
remote_extra.reverse()
3318
if local_extra and not theirs_only:
3319
self.outf.write("You have %d extra revision(s):\n" %
3321
for revision in iter_log_revisions(local_extra,
3322
local_branch.repository,
3324
lf.log_revision(revision)
3325
printed_local = True
3327
printed_local = False
3328
if remote_extra and not mine_only:
3329
if printed_local is True:
3330
self.outf.write("\n\n\n")
3331
self.outf.write("You are missing %d revision(s):\n" %
3333
for revision in iter_log_revisions(remote_extra,
3334
remote_branch.repository,
3336
lf.log_revision(revision)
3337
if not remote_extra and not local_extra:
3339
self.outf.write("Branches are up to date.\n")
3343
remote_branch.unlock()
3345
local_branch.unlock()
4781
3346
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)
3347
local_branch.lock_write()
3349
# handle race conditions - a parent might be set while we run.
3350
if local_branch.get_parent() is None:
3351
local_branch.set_parent(remote_branch.base)
3353
local_branch.unlock()
4786
3354
return status_code
4789
3357
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.
3358
"""Compress the data within a repository."""
4808
3360
_see_also = ['repositories']
4809
3361
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):
3363
def run(self, branch_or_repo='.'):
4815
3364
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4817
3366
branch = dir.open_branch()
4818
3367
repository = branch.repository
4819
3368
except errors.NotBranchError:
4820
3369
repository = dir.open_repository()
4821
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4824
3373
class cmd_plugins(Command):
4825
__doc__ = """List the installed plugins.
3374
"""List the installed plugins.
4827
3376
This command displays the list of installed plugins including
4828
3377
version of plugin and a short description of each.
5229
3760
class cmd_serve(Command):
5230
__doc__ = """Run the bzr server."""
3761
"""Run the bzr server."""
5232
3763
aliases = ['server']
5234
3765
takes_options = [
5236
3767
help='Serve on stdin/out for use from inetd or sshd.'),
5237
RegistryOption('protocol',
5238
help="Protocol to serve.",
5239
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
5240
value_switches=True),
5242
3769
help='Listen for connections on nominated port of the form '
5243
3770
'[hostname:]portnumber. Passing 0 as the port number will '
5244
'result in a dynamically allocated port. The default port '
5245
'depends on the protocol.',
3771
'result in a dynamically allocated port. The default port is '
5247
custom_help('directory',
5248
help='Serve contents of this directory.'),
3775
help='Serve contents of this directory.',
5249
3777
Option('allow-writes',
5250
3778
help='By default the server is a readonly server. Supplying '
5251
3779
'--allow-writes enables write access to the contents of '
5252
'the served directory and below. Note that ``bzr serve`` '
5253
'does not perform authentication, so unless some form of '
5254
'external authentication is arranged supplying this '
5255
'option leads to global uncontrolled write access to your '
3780
'the served directory and below.'
5258
Option('client-timeout', type=float,
5259
help='Override the default idle client timeout (5min).'),
5262
def get_host_and_port(self, port):
5263
"""Return the host and port to run the smart server on.
5265
If 'port' is None, None will be returned for the host and port.
5267
If 'port' has a colon in it, the string before the colon will be
5268
interpreted as the host.
5270
:param port: A string of the port to run the server on.
5271
:return: A tuple of (host, port), where 'host' is a host name or IP,
5272
and port is an integer TCP/IP port.
5275
if port is not None:
5277
host, port = port.split(':')
5281
def run(self, port=None, inet=False, directory=None, allow_writes=False,
5282
protocol=None, client_timeout=None):
5283
from bzrlib import transport
3784
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3785
from bzrlib import lockdir
3786
from bzrlib.smart import medium, server
3787
from bzrlib.transport import get_transport
3788
from bzrlib.transport.chroot import ChrootServer
5284
3789
if directory is None:
5285
3790
directory = os.getcwd()
5286
if protocol is None:
5287
protocol = transport.transport_server_registry.get()
5288
host, port = self.get_host_and_port(port)
5289
3791
url = urlutils.local_path_to_url(directory)
5290
3792
if not allow_writes:
5291
3793
url = 'readonly+' + url
5292
t = transport.get_transport(url)
3794
chroot_server = ChrootServer(get_transport(url))
3795
chroot_server.setUp()
3796
t = get_transport(chroot_server.get_url())
3798
smart_server = medium.SmartServerPipeStreamMedium(
3799
sys.stdin, sys.stdout, t)
3801
host = medium.BZR_DEFAULT_INTERFACE
3803
port = medium.BZR_DEFAULT_PORT
3806
host, port = port.split(':')
3808
smart_server = server.SmartTCPServer(t, host=host, port=port)
3809
print 'listening on port: ', smart_server.port
3811
# for the duration of this server, no UI output is permitted.
3812
# note that this may cause problems with blackbox tests. This should
3813
# be changed with care though, as we dont want to use bandwidth sending
3814
# progress over stderr to smart server clients!
3815
old_factory = ui.ui_factory
3816
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
5294
protocol(t, host, port, inet, client_timeout)
5295
except TypeError, e:
5296
# We use symbol_versioning.deprecated_in just so that people
5297
# grepping can find it here.
5298
# symbol_versioning.deprecated_in((2, 5, 0))
5299
symbol_versioning.warn(
5300
'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5301
'Most likely it needs to be updated to support a'
5302
' "timeout" parameter (added in bzr 2.5.0)'
5303
% (e, protocol.__module__, protocol),
5305
protocol(t, host, port, inet)
3818
ui.ui_factory = ui.SilentUIFactory()
3819
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3820
smart_server.serve()
3822
ui.ui_factory = old_factory
3823
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
5308
3826
class cmd_join(Command):
5309
__doc__ = """Combine a tree into its containing tree.
5311
This command requires the target tree to be in a rich-root format.
3827
"""Combine a subtree into its containing tree.
3829
This command is for experimental use only. It requires the target tree
3830
to be in dirstate-with-subtree format, which cannot be converted into
5313
3833
The TREE argument should be an independent tree, inside another tree, but
5314
3834
not part of it. (Such trees can be produced by "bzr split", but also by
5315
3835
running "bzr branch" with the target inside a tree.)
5317
The result is a combined tree, with the subtree no longer an independent
3837
The result is a combined tree, with the subtree no longer an independant
5318
3838
part. This is marked as a merge of the subtree into the containing tree,
5319
3839
and all history is preserved.
3841
If --reference is specified, the subtree retains its independence. It can
3842
be branched by itself, and can be part of multiple projects at the same
3843
time. But operations performed in the containing tree, such as commit
3844
and merge, will recurse into the subtree.
5322
3847
_see_also = ['split']
5323
3848
takes_args = ['tree']
5324
3849
takes_options = [
5325
Option('reference', help='Join by reference.', hidden=True),
3850
Option('reference', help='Join by reference.'),
5328
3854
def run(self, tree, reference=False):
5329
3855
sub_tree = WorkingTree.open(tree)
5572
4069
'rather than the one containing the working directory.',
5573
4070
short_name='f',
5575
Option('output', short_name='o',
5576
help='Write merge directive to this file or directory; '
5577
'use - for stdout.',
4072
Option('output', short_name='o', help='Write directive to this file.',
5580
help='Refuse to send if there are uncommitted changes in'
5581
' the working tree, --no-strict disables the check.'),
5582
4074
Option('mail-to', help='Mail the request to this address.',
5586
Option('body', help='Body for the email.', type=unicode),
5587
RegistryOption('format',
5588
help='Use the specified output format.',
5589
lazy_registry=('bzrlib.send', 'format_registry')),
4078
RegistryOption.from_kwargs('format',
4079
'Use the specified output format.',
4080
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4081
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5592
4084
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5593
no_patch=False, revision=None, remember=None, output=None,
5594
format=None, mail_to=None, message=None, body=None,
5595
strict=None, **kwargs):
5596
from bzrlib.send import send
5597
return send(submit_branch, revision, public_branch, remember,
5598
format, no_bundle, no_patch, output,
5599
kwargs.get('from', '.'), mail_to, message, body,
4085
no_patch=False, revision=None, remember=False, output=None,
4086
format='4', mail_to=None, message=None, **kwargs):
4087
return self._run(submit_branch, revision, public_branch, remember,
4088
format, no_bundle, no_patch, output,
4089
kwargs.get('from', '.'), mail_to, message)
4091
def _run(self, submit_branch, revision, public_branch, remember, format,
4092
no_bundle, no_patch, output, from_, mail_to, message):
4093
from bzrlib.revision import NULL_REVISION
4094
branch = Branch.open_containing(from_)[0]
4096
outfile = StringIO()
4100
outfile = open(output, 'wb')
4101
# we may need to write data into branch's repository to calculate
4106
config = branch.get_config()
4108
mail_to = config.get_user_option('submit_to')
4109
mail_client = config.get_mail_client()
4110
if remember and submit_branch is None:
4111
raise errors.BzrCommandError(
4112
'--remember requires a branch to be specified.')
4113
stored_submit_branch = branch.get_submit_branch()
4114
remembered_submit_branch = False
4115
if submit_branch is None:
4116
submit_branch = stored_submit_branch
4117
remembered_submit_branch = True
4119
if stored_submit_branch is None or remember:
4120
branch.set_submit_branch(submit_branch)
4121
if submit_branch is None:
4122
submit_branch = branch.get_parent()
4123
remembered_submit_branch = True
4124
if submit_branch is None:
4125
raise errors.BzrCommandError('No submit branch known or'
4127
if remembered_submit_branch:
4128
note('Using saved location: %s', submit_branch)
4131
submit_config = Branch.open(submit_branch).get_config()
4132
mail_to = submit_config.get_user_option("child_submit_to")
4134
stored_public_branch = branch.get_public_branch()
4135
if public_branch is None:
4136
public_branch = stored_public_branch
4137
elif stored_public_branch is None or remember:
4138
branch.set_public_branch(public_branch)
4139
if no_bundle and public_branch is None:
4140
raise errors.BzrCommandError('No public branch specified or'
4142
base_revision_id = None
4144
if revision is not None:
4145
if len(revision) > 2:
4146
raise errors.BzrCommandError('bzr send takes '
4147
'at most two one revision identifiers')
4148
revision_id = revision[-1].in_history(branch).rev_id
4149
if len(revision) == 2:
4150
base_revision_id = revision[0].in_history(branch).rev_id
4151
if revision_id is None:
4152
revision_id = branch.last_revision()
4153
if revision_id == NULL_REVISION:
4154
raise errors.BzrCommandError('No revisions to submit.')
4156
directive = merge_directive.MergeDirective2.from_objects(
4157
branch.repository, revision_id, time.time(),
4158
osutils.local_time_offset(), submit_branch,
4159
public_branch=public_branch, include_patch=not no_patch,
4160
include_bundle=not no_bundle, message=message,
4161
base_revision_id=base_revision_id)
4162
elif format == '0.9':
4165
patch_type = 'bundle'
4167
raise errors.BzrCommandError('Format 0.9 does not'
4168
' permit bundle with no patch')
4174
directive = merge_directive.MergeDirective.from_objects(
4175
branch.repository, revision_id, time.time(),
4176
osutils.local_time_offset(), submit_branch,
4177
public_branch=public_branch, patch_type=patch_type,
4180
outfile.writelines(directive.to_lines())
4182
subject = '[MERGE] '
4183
if message is not None:
4186
revision = branch.repository.get_revision(revision_id)
4187
subject += revision.get_summary()
4188
basename = directive.get_disk_name(branch)
4189
mail_client.compose_merge_request(mail_to, subject,
4190
outfile.getvalue(), basename)
5604
4197
class cmd_bundle_revisions(cmd_send):
5605
__doc__ = """Create a merge-directive for submitting changes.
4199
"""Create a merge-directive for submiting changes.
5607
4201
A merge directive provides many things needed for requesting merges:
5684
4274
Tags are stored in the branch. Tags are copied from one branch to another
5685
4275
along when you branch, push, pull or merge.
5687
It is an error to give a tag name that already exists unless you pass
4277
It is an error to give a tag name that already exists unless you pass
5688
4278
--force, in which case the tag is moved to point to the new revision.
5690
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5691
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5693
If no tag name is specified it will be determined through the
5694
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5695
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5699
4281
_see_also = ['commit', 'tags']
5700
takes_args = ['tag_name?']
4282
takes_args = ['tag_name']
5701
4283
takes_options = [
5702
4284
Option('delete',
5703
4285
help='Delete this tag rather than placing it.',
5705
custom_help('directory',
5706
help='Branch in which to place the tag.'),
4288
help='Branch in which to place the tag.',
5707
4292
Option('force',
5708
4293
help='Replace existing tags.',
5713
def run(self, tag_name=None,
4298
def run(self, tag_name,
5719
4304
branch, relpath = Branch.open_containing(directory)
5720
self.add_cleanup(branch.lock_write().unlock)
5722
if tag_name is None:
5723
raise errors.BzrCommandError(gettext("No tag specified to delete."))
5724
branch.tags.delete_tag(tag_name)
5725
note(gettext('Deleted tag %s.') % tag_name)
5728
if len(revision) != 1:
5729
raise errors.BzrCommandError(gettext(
5730
"Tags can only be placed on a single revision, "
5732
revision_id = revision[0].as_revision_id(branch)
5734
revision_id = branch.last_revision()
5735
if tag_name is None:
5736
tag_name = branch.automatic_tag_name(revision_id)
5737
if tag_name is None:
5738
raise errors.BzrCommandError(gettext(
5739
"Please specify a tag name."))
5741
existing_target = branch.tags.lookup_tag(tag_name)
5742
except errors.NoSuchTag:
5743
existing_target = None
5744
if not force and existing_target not in (None, revision_id):
5745
raise errors.TagAlreadyExists(tag_name)
5746
if existing_target == revision_id:
5747
note(gettext('Tag %s already exists for that revision.') % tag_name)
4308
branch.tags.delete_tag(tag_name)
4309
self.outf.write('Deleted tag %s.\n' % tag_name)
4312
if len(revision) != 1:
4313
raise errors.BzrCommandError(
4314
"Tags can only be placed on a single revision, "
4316
revision_id = revision[0].in_history(branch).rev_id
4318
revision_id = branch.last_revision()
4319
if (not force) and branch.tags.has_tag(tag_name):
4320
raise errors.TagAlreadyExists(tag_name)
5749
4321
branch.tags.set_tag(tag_name, revision_id)
5750
if existing_target is None:
5751
note(gettext('Created tag %s.') % tag_name)
5753
note(gettext('Updated tag %s.') % tag_name)
4322
self.outf.write('Created tag %s.\n' % tag_name)
5756
4327
class cmd_tags(Command):
5757
__doc__ = """List tags.
5759
4330
This command shows a table of tag names and the revisions they reference.
5762
4333
_see_also = ['tag']
5763
4334
takes_options = [
5764
custom_help('directory',
5765
help='Branch whose tags should be displayed.'),
5766
RegistryOption('sort',
4336
help='Branch whose tags should be displayed.',
4340
RegistryOption.from_kwargs('sort',
5767
4341
'Sort tags by different criteria.', title='Sorting',
5768
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
4342
alpha='Sort tags lexicographically (default).',
4343
time='Sort tags chronologically.',
5774
4348
@display_command
5775
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5776
from bzrlib.tag import tag_sort_methods
5777
4354
branch, relpath = Branch.open_containing(directory)
5779
4355
tags = branch.tags.get_tag_dict().items()
5783
self.add_cleanup(branch.lock_read().unlock)
5785
# Restrict to the specified range
5786
tags = self._tags_for_range(branch, revision)
5788
sort = tag_sort_methods.get()
4358
elif sort == 'time':
4360
for tag, revid in tags:
4362
revobj = branch.repository.get_revision(revid)
4363
except errors.NoSuchRevision:
4364
timestamp = sys.maxint # place them at the end
4366
timestamp = revobj.timestamp
4367
timestamps[revid] = timestamp
4368
tags.sort(key=lambda x: timestamps[x[1]])
5790
4369
if not show_ids:
5791
4370
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5792
for index, (tag, revid) in enumerate(tags):
5794
revno = branch.revision_id_to_dotted_revno(revid)
5795
if isinstance(revno, tuple):
5796
revno = '.'.join(map(str, revno))
5797
except (errors.NoSuchRevision,
5798
errors.GhostRevisionsHaveNoRevno):
5799
# Bad tag data/merges can lead to tagged revisions
5800
# which are not in this branch. Fail gracefully ...
5802
tags[index] = (tag, revno)
4371
revno_map = branch.get_revision_id_to_revno_map()
4372
tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4373
for tag, revid in tags ]
5804
4374
for tag, revspec in tags:
5805
4375
self.outf.write('%-20s %s\n' % (tag, revspec))
5807
def _tags_for_range(self, branch, revision):
5809
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5810
revid1, revid2 = rev1.rev_id, rev2.rev_id
5811
# _get_revision_range will always set revid2 if it's not specified.
5812
# If revid1 is None, it means we want to start from the branch
5813
# origin which is always a valid ancestor. If revid1 == revid2, the
5814
# ancestry check is useless.
5815
if revid1 and revid1 != revid2:
5816
# FIXME: We really want to use the same graph than
5817
# branch.iter_merge_sorted_revisions below, but this is not
5818
# easily available -- vila 2011-09-23
5819
if branch.repository.get_graph().is_ancestor(revid2, revid1):
5820
# We don't want to output anything in this case...
5822
# only show revisions between revid1 and revid2 (inclusive)
5823
tagged_revids = branch.tags.get_reverse_tag_dict()
5825
for r in branch.iter_merge_sorted_revisions(
5826
start_revision_id=revid2, stop_revision_id=revid1,
5827
stop_rule='include'):
5828
revid_tags = tagged_revids.get(r[0], None)
5830
found.extend([(tag, r[0]) for tag in revid_tags])
5834
4378
class cmd_reconfigure(Command):
5835
__doc__ = """Reconfigure the type of a bzr directory.
4379
"""Reconfigure the type of a bzr directory.
5837
4381
A target configuration must be specified.
5845
4389
If none of these is available, --bind-to must be specified.
5848
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5849
4392
takes_args = ['location?']
5851
RegistryOption.from_kwargs(
5854
help='The relation between branch and tree.',
5855
value_switches=True, enum_switch=False,
5856
branch='Reconfigure to be an unbound branch with no working tree.',
5857
tree='Reconfigure to be an unbound branch with a working tree.',
5858
checkout='Reconfigure to be a bound branch with a working tree.',
5859
lightweight_checkout='Reconfigure to be a lightweight'
5860
' checkout (with no local history).',
5862
RegistryOption.from_kwargs(
5864
title='Repository type',
5865
help='Location fo the repository.',
5866
value_switches=True, enum_switch=False,
5867
standalone='Reconfigure to be a standalone branch '
5868
'(i.e. stop using shared repository).',
5869
use_shared='Reconfigure to use a shared repository.',
5871
RegistryOption.from_kwargs(
5873
title='Trees in Repository',
5874
help='Whether new branches in the repository have trees.',
5875
value_switches=True, enum_switch=False,
5876
with_trees='Reconfigure repository to create '
5877
'working trees on branches by default.',
5878
with_no_trees='Reconfigure repository to not create '
5879
'working trees on branches by default.'
5881
Option('bind-to', help='Branch to bind checkout to.', type=str),
5883
help='Perform reconfiguration even if local changes'
5885
Option('stacked-on',
5886
help='Reconfigure a branch to be stacked on another branch.',
5890
help='Reconfigure a branch to be unstacked. This '
5891
'may require copying substantial data into it.',
4393
takes_options = [RegistryOption.from_kwargs('target_type',
4394
title='Target type',
4395
help='The type to reconfigure the directory to.',
4396
value_switches=True, enum_switch=False,
4397
branch='Reconfigure to a branch.',
4398
tree='Reconfigure to a tree.',
4399
checkout='Reconfigure to a checkout.',
4400
lightweight_checkout='Reconfigure to a lightweight'
4402
Option('bind-to', help='Branch to bind checkout to.',
4405
help='Perform reconfiguration even if local changes'
5895
def run(self, location=None, bind_to=None, force=False,
5896
tree_type=None, repository_type=None, repository_trees=None,
5897
stacked_on=None, unstacked=None):
4409
def run(self, location=None, target_type=None, bind_to=None, force=False):
5898
4410
directory = bzrdir.BzrDir.open(location)
5899
if stacked_on and unstacked:
5900
raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
5901
elif stacked_on is not None:
5902
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5904
reconfigure.ReconfigureUnstacked().apply(directory)
5905
# At the moment you can use --stacked-on and a different
5906
# reconfiguration shape at the same time; there seems no good reason
5908
if (tree_type is None and
5909
repository_type is None and
5910
repository_trees is None):
5911
if stacked_on or unstacked:
5914
raise errors.BzrCommandError(gettext('No target configuration '
5916
reconfiguration = None
5917
if tree_type == 'branch':
4411
if target_type is None:
4412
raise errors.BzrCommandError('No target configuration specified')
4413
elif target_type == 'branch':
5918
4414
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5919
elif tree_type == 'tree':
4415
elif target_type == 'tree':
5920
4416
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5921
elif tree_type == 'checkout':
5922
reconfiguration = reconfigure.Reconfigure.to_checkout(
5924
elif tree_type == 'lightweight-checkout':
4417
elif target_type == 'checkout':
4418
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4420
elif target_type == 'lightweight-checkout':
5925
4421
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5926
4422
directory, bind_to)
5928
reconfiguration.apply(force)
5929
reconfiguration = None
5930
if repository_type == 'use-shared':
5931
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5932
elif repository_type == 'standalone':
5933
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5935
reconfiguration.apply(force)
5936
reconfiguration = None
5937
if repository_trees == 'with-trees':
5938
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5940
elif repository_trees == 'with-no-trees':
5941
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5944
reconfiguration.apply(force)
5945
reconfiguration = None
4423
reconfiguration.apply(force)
5948
4426
class cmd_switch(Command):
5949
__doc__ = """Set the branch of a checkout and update.
4427
"""Set the branch of a checkout and update.
5951
4429
For lightweight checkouts, this changes the branch being referenced.
5952
4430
For heavyweight checkouts, this checks that there are no local commits
5953
4431
versus the current bound branch, then it makes the local branch a mirror
5954
4432
of the new location and binds to it.
5956
4434
In both cases, the working tree is updated and uncommitted changes
5957
4435
are merged. The user can commit or revert these as they desire.
5959
4437
Pending merges need to be committed or reverted before using switch.
5961
The path to the branch to switch to can be specified relative to the parent
5962
directory of the current branch. For example, if you are currently in a
5963
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5966
Bound branches use the nickname of its master branch unless it is set
5967
locally, in which case switching will update the local nickname to be
5971
takes_args = ['to_location?']
5972
takes_options = ['directory',
5974
help='Switch even if local commits will be lost.'),
5976
Option('create-branch', short_name='b',
5977
help='Create the target branch from this one before'
5978
' switching to it.'),
4440
takes_args = ['to_location']
4441
takes_options = [Option('force',
4442
help='Switch even if local commits will be lost.')
5981
def run(self, to_location=None, force=False, create_branch=False,
5982
revision=None, directory=u'.'):
4445
def run(self, to_location, force=False):
5983
4446
from bzrlib import switch
5984
tree_location = directory
5985
revision = _get_one_revision('switch', revision)
4447
to_branch = Branch.open(to_location)
5986
4449
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5987
if to_location is None:
5988
if revision is None:
5989
raise errors.BzrCommandError(gettext('You must supply either a'
5990
' revision or a location'))
5991
to_location = tree_location
5993
branch = control_dir.open_branch()
5994
had_explicit_nick = branch.get_config().has_explicit_nickname()
5995
except errors.NotBranchError:
5997
had_explicit_nick = False
6000
raise errors.BzrCommandError(gettext('cannot create branch without'
6002
to_location = directory_service.directories.dereference(
6004
if '/' not in to_location and '\\' not in to_location:
6005
# This path is meant to be relative to the existing branch
6006
this_url = self._get_branch_location(control_dir)
6007
to_location = urlutils.join(this_url, '..', to_location)
6008
to_branch = branch.bzrdir.sprout(to_location,
6009
possible_transports=[branch.bzrdir.root_transport],
6010
source_branch=branch).open_branch()
6013
to_branch = Branch.open(to_location)
6014
except errors.NotBranchError:
6015
this_url = self._get_branch_location(control_dir)
6016
to_branch = Branch.open(
6017
urlutils.join(this_url, '..', to_location))
6018
if revision is not None:
6019
revision = revision.as_revision_id(to_branch)
6020
switch.switch(control_dir, to_branch, force, revision_id=revision)
6021
if had_explicit_nick:
6022
branch = control_dir.open_branch() #get the new branch!
6023
branch.nick = to_branch.nick
6024
note(gettext('Switched to branch: %s'),
4450
switch.switch(control_dir, to_branch, force)
4451
note('Switched to branch: %s',
6025
4452
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6027
def _get_branch_location(self, control_dir):
6028
"""Return location of branch for this control dir."""
6030
this_branch = control_dir.open_branch()
6031
# This may be a heavy checkout, where we want the master branch
6032
master_location = this_branch.get_bound_location()
6033
if master_location is not None:
6034
return master_location
6035
# If not, use a local sibling
6036
return this_branch.base
6037
except errors.NotBranchError:
6038
format = control_dir.find_branch_format()
6039
if getattr(format, 'get_reference', None) is not None:
6040
return format.get_reference(control_dir)
6042
return control_dir.root_transport.base
6045
class cmd_view(Command):
6046
__doc__ = """Manage filtered views.
6048
Views provide a mask over the tree so that users can focus on
6049
a subset of a tree when doing their work. After creating a view,
6050
commands that support a list of files - status, diff, commit, etc -
6051
effectively have that list of files implicitly given each time.
6052
An explicit list of files can still be given but those files
6053
must be within the current view.
6055
In most cases, a view has a short life-span: it is created to make
6056
a selected change and is deleted once that change is committed.
6057
At other times, you may wish to create one or more named views
6058
and switch between them.
6060
To disable the current view without deleting it, you can switch to
6061
the pseudo view called ``off``. This can be useful when you need
6062
to see the whole tree for an operation or two (e.g. merge) but
6063
want to switch back to your view after that.
6066
To define the current view::
6068
bzr view file1 dir1 ...
6070
To list the current view::
6074
To delete the current view::
6078
To disable the current view without deleting it::
6080
bzr view --switch off
6082
To define a named view and switch to it::
6084
bzr view --name view-name file1 dir1 ...
6086
To list a named view::
6088
bzr view --name view-name
6090
To delete a named view::
6092
bzr view --name view-name --delete
6094
To switch to a named view::
6096
bzr view --switch view-name
6098
To list all views defined::
6102
To delete all views::
6104
bzr view --delete --all
6108
takes_args = ['file*']
6111
help='Apply list or delete action to all views.',
6114
help='Delete the view.',
6117
help='Name of the view to define, list or delete.',
6121
help='Name of the view to switch to.',
6126
def run(self, file_list,
6132
tree, file_list = WorkingTree.open_containing_paths(file_list,
6134
current_view, view_dict = tree.views.get_view_info()
6139
raise errors.BzrCommandError(gettext(
6140
"Both --delete and a file list specified"))
6142
raise errors.BzrCommandError(gettext(
6143
"Both --delete and --switch specified"))
6145
tree.views.set_view_info(None, {})
6146
self.outf.write(gettext("Deleted all views.\n"))
6148
raise errors.BzrCommandError(gettext("No current view to delete"))
6150
tree.views.delete_view(name)
6151
self.outf.write(gettext("Deleted '%s' view.\n") % name)
6154
raise errors.BzrCommandError(gettext(
6155
"Both --switch and a file list specified"))
6157
raise errors.BzrCommandError(gettext(
6158
"Both --switch and --all specified"))
6159
elif switch == 'off':
6160
if current_view is None:
6161
raise errors.BzrCommandError(gettext("No current view to disable"))
6162
tree.views.set_view_info(None, view_dict)
6163
self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
6165
tree.views.set_view_info(switch, view_dict)
6166
view_str = views.view_display_str(tree.views.lookup_view())
6167
self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
6170
self.outf.write(gettext('Views defined:\n'))
6171
for view in sorted(view_dict):
6172
if view == current_view:
6176
view_str = views.view_display_str(view_dict[view])
6177
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6179
self.outf.write(gettext('No views defined.\n'))
6182
# No name given and no current view set
6185
raise errors.BzrCommandError(gettext(
6186
"Cannot change the 'off' pseudo view"))
6187
tree.views.set_view(name, sorted(file_list))
6188
view_str = views.view_display_str(tree.views.lookup_view())
6189
self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
6193
# No name given and no current view set
6194
self.outf.write(gettext('No current view.\n'))
6196
view_str = views.view_display_str(tree.views.lookup_view(name))
6197
self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
6200
4455
class cmd_hooks(Command):
6201
__doc__ = """Show hooks."""
6206
for hook_key in sorted(hooks.known_hooks.keys()):
6207
some_hooks = hooks.known_hooks_key_to_object(hook_key)
6208
self.outf.write("%s:\n" % type(some_hooks).__name__)
6209
for hook_name, hook_point in sorted(some_hooks.items()):
6210
self.outf.write(" %s:\n" % (hook_name,))
6211
found_hooks = list(hook_point)
6213
for hook in found_hooks:
6214
self.outf.write(" %s\n" %
6215
(some_hooks.get_hook_name(hook),))
6217
self.outf.write(gettext(" <no hooks installed>\n"))
6220
class cmd_remove_branch(Command):
6221
__doc__ = """Remove a branch.
6223
This will remove the branch from the specified location but
6224
will keep any working tree or repository in place.
6228
Remove the branch at repo/trunk::
6230
bzr remove-branch repo/trunk
6234
takes_args = ["location?"]
6236
aliases = ["rmbranch"]
6238
def run(self, location=None):
6239
if location is None:
6241
branch = Branch.open_containing(location)[0]
6242
branch.bzrdir.destroy_branch()
6245
class cmd_shelve(Command):
6246
__doc__ = """Temporarily set aside some changes from the current tree.
6248
Shelve allows you to temporarily put changes you've made "on the shelf",
6249
ie. out of the way, until a later time when you can bring them back from
6250
the shelf with the 'unshelve' command. The changes are stored alongside
6251
your working tree, and so they aren't propagated along with your branch nor
6252
will they survive its deletion.
6254
If shelve --list is specified, previously-shelved changes are listed.
6256
Shelve is intended to help separate several sets of changes that have
6257
been inappropriately mingled. If you just want to get rid of all changes
6258
and you don't need to restore them later, use revert. If you want to
6259
shelve all text changes at once, use shelve --all.
6261
If filenames are specified, only the changes to those files will be
6262
shelved. Other files will be left untouched.
6264
If a revision is specified, changes since that revision will be shelved.
6266
You can put multiple items on the shelf, and by default, 'unshelve' will
6267
restore the most recently shelved changes.
6269
For complicated changes, it is possible to edit the changes in a separate
6270
editor program to decide what the file remaining in the working copy
6271
should look like. To do this, add the configuration option
6273
change_editor = PROGRAM @new_path @old_path
6275
where @new_path is replaced with the path of the new version of the
6276
file and @old_path is replaced with the path of the old version of
6277
the file. The PROGRAM should save the new file with the desired
6278
contents of the file in the working tree.
6282
takes_args = ['file*']
6287
Option('all', help='Shelve all changes.'),
6289
RegistryOption('writer', 'Method to use for writing diffs.',
6290
bzrlib.option.diff_writer_registry,
6291
value_switches=True, enum_switch=False),
6293
Option('list', help='List shelved changes.'),
6295
help='Destroy removed changes instead of shelving them.'),
6297
_see_also = ['unshelve', 'configuration']
6299
def run(self, revision=None, all=False, file_list=None, message=None,
6300
writer=None, list=False, destroy=False, directory=None):
6302
return self.run_for_list(directory=directory)
6303
from bzrlib.shelf_ui import Shelver
6305
writer = bzrlib.option.diff_writer_registry.get()
6307
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6308
file_list, message, destroy=destroy, directory=directory)
6313
except errors.UserAbort:
6316
def run_for_list(self, directory=None):
6317
if directory is None:
6319
tree = WorkingTree.open_containing(directory)[0]
6320
self.add_cleanup(tree.lock_read().unlock)
6321
manager = tree.get_shelf_manager()
6322
shelves = manager.active_shelves()
6323
if len(shelves) == 0:
6324
note(gettext('No shelved changes.'))
6326
for shelf_id in reversed(shelves):
6327
message = manager.get_metadata(shelf_id).get('message')
6329
message = '<no message>'
6330
self.outf.write('%3d: %s\n' % (shelf_id, message))
6334
class cmd_unshelve(Command):
6335
__doc__ = """Restore shelved changes.
6337
By default, the most recently shelved changes are restored. However if you
6338
specify a shelf by id those changes will be restored instead. This works
6339
best when the changes don't depend on each other.
6342
takes_args = ['shelf_id?']
6345
RegistryOption.from_kwargs(
6346
'action', help="The action to perform.",
6347
enum_switch=False, value_switches=True,
6348
apply="Apply changes and remove from the shelf.",
6349
dry_run="Show changes, but do not apply or remove them.",
6350
preview="Instead of unshelving the changes, show the diff that "
6351
"would result from unshelving.",
6352
delete_only="Delete changes without applying them.",
6353
keep="Apply changes but don't delete them.",
6356
_see_also = ['shelve']
6358
def run(self, shelf_id=None, action='apply', directory=u'.'):
6359
from bzrlib.shelf_ui import Unshelver
6360
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6364
unshelver.tree.unlock()
6367
class cmd_clean_tree(Command):
6368
__doc__ = """Remove unwanted files from working tree.
6370
By default, only unknown files, not ignored files, are deleted. Versioned
6371
files are never deleted.
6373
Another class is 'detritus', which includes files emitted by bzr during
6374
normal operations and selftests. (The value of these files decreases with
6377
If no options are specified, unknown files are deleted. Otherwise, option
6378
flags are respected, and may be combined.
6380
To check what clean-tree will do, use --dry-run.
6382
takes_options = ['directory',
6383
Option('ignored', help='Delete all ignored files.'),
6384
Option('detritus', help='Delete conflict files, merge and revert'
6385
' backups, and failed selftest dirs.'),
6387
help='Delete files unknown to bzr (default).'),
6388
Option('dry-run', help='Show files to delete instead of'
6390
Option('force', help='Do not prompt before deleting.')]
6391
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6392
force=False, directory=u'.'):
6393
from bzrlib.clean_tree import clean_tree
6394
if not (unknown or ignored or detritus):
6398
clean_tree(directory, unknown=unknown, ignored=ignored,
6399
detritus=detritus, dry_run=dry_run, no_prompt=force)
6402
class cmd_reference(Command):
6403
__doc__ = """list, view and set branch locations for nested trees.
6405
If no arguments are provided, lists the branch locations for nested trees.
6406
If one argument is provided, display the branch location for that tree.
6407
If two arguments are provided, set the branch location for that tree.
6412
takes_args = ['path?', 'location?']
6414
def run(self, path=None, location=None):
6416
if path is not None:
6418
tree, branch, relpath =(
6419
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6420
if path is not None:
6423
tree = branch.basis_tree()
4456
"""Show a branch's currently registered hooks.
4460
takes_args = ['path?']
4462
def run(self, path=None):
6424
4463
if path is None:
6425
info = branch._get_all_reference_info().iteritems()
6426
self._display_reference_info(tree, branch, info)
4465
branch_hooks = Branch.open(path).hooks
4466
for hook_type in branch_hooks:
4467
hooks = branch_hooks[hook_type]
4468
self.outf.write("%s:\n" % (hook_type,))
4471
self.outf.write(" %s\n" %
4472
(branch_hooks.get_hook_name(hook),))
4474
self.outf.write(" <no hooks installed>\n")
4477
def _create_prefix(cur_transport):
4478
needed = [cur_transport]
4479
# Recurse upwards until we can create a directory successfully
4481
new_transport = cur_transport.clone('..')
4482
if new_transport.base == cur_transport.base:
4483
raise errors.BzrCommandError(
4484
"Failed to create path prefix for %s."
4485
% cur_transport.base)
4487
new_transport.mkdir('.')
4488
except errors.NoSuchFile:
4489
needed.append(new_transport)
4490
cur_transport = new_transport
6428
file_id = tree.path2id(path)
6430
raise errors.NotVersionedError(path)
6431
if location is None:
6432
info = [(file_id, branch.get_reference_info(file_id))]
6433
self._display_reference_info(tree, branch, info)
6435
branch.set_reference_info(file_id, path, location)
6437
def _display_reference_info(self, tree, branch, info):
6439
for file_id, (path, location) in info:
6441
path = tree.id2path(file_id)
6442
except errors.NoSuchId:
6444
ref_list.append((path, location))
6445
for path, location in sorted(ref_list):
6446
self.outf.write('%s %s\n' % (path, location))
6449
class cmd_export_pot(Command):
6450
__doc__ = """Export command helps and error messages in po format."""
6455
from bzrlib.export_pot import export_pot
6456
export_pot(self.outf)
6459
def _register_lazy_builtins():
6460
# register lazy builtins from other modules; called at startup and should
6461
# be only called once.
6462
for (name, aliases, module_name) in [
6463
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6464
('cmd_config', [], 'bzrlib.config'),
6465
('cmd_dpush', [], 'bzrlib.foreign'),
6466
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6467
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6468
('cmd_conflicts', [], 'bzrlib.conflicts'),
6469
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6470
('cmd_verify_signatures', [],
6471
'bzrlib.commit_signature_commands'),
6472
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6474
builtin_command_registry.register_lazy(name, aliases, module_name)
4493
# Now we only need to create child directories
4495
cur_transport = needed.pop()
4496
cur_transport.ensure_base()
4499
def _get_mergeable_helper(location):
4500
"""Get a merge directive or bundle if 'location' points to one.
4502
Try try to identify a bundle and returns its mergeable form. If it's not,
4503
we return the tried transport anyway so that it can reused to access the
4506
:param location: can point to a bundle or a branch.
4508
:return: mergeable, transport
4511
url = urlutils.normalize_url(location)
4512
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4513
location_transport = transport.get_transport(url)
4516
# There may be redirections but we ignore the intermediate
4517
# and final transports used
4518
read = bundle.read_mergeable_from_transport
4519
mergeable, t = read(location_transport, filename)
4520
except errors.NotABundle:
4521
# Continue on considering this url a Branch but adjust the
4522
# location_transport
4523
location_transport = location_transport.clone(filename)
4524
return mergeable, location_transport
4527
# these get imported and then picked up by the scan for cmd_*
4528
# TODO: Some more consistent way to split command definitions across files;
4529
# we do need to load at least some information about them to know of
4530
# aliases. ideally we would avoid loading the implementation until the
4531
# details were needed.
4532
from bzrlib.cmd_version_info import cmd_version_info
4533
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4534
from bzrlib.bundle.commands import (
4537
from bzrlib.sign_my_commits import cmd_sign_my_commits
4538
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4539
cmd_weave_plan_merge, cmd_weave_merge_text