129
226
Text has changed since the previous revision.
229
File kind has been changed (e.g. from file to directory).
132
232
Not versioned and not matching an ignore pattern.
134
To see ignored files use 'bzr ignored'. For details in the
234
Additionally for directories, symlinks and files with an executable
235
bit, Bazaar indicates their type using a trailing character: '/', '@'
238
To see ignored files use 'bzr ignored'. For details on the
135
239
changes to file texts, use 'bzr diff'.
241
Note that --short or -S gives status flags for each item, similar
242
to Subversion's status command. To get output similar to svn -q,
137
245
If no arguments are specified, the status of the entire working
138
246
directory is shown. Otherwise, only the status of the specified
139
247
files or directories is reported. If a directory is given, status
140
248
is reported for everything inside that directory.
142
If a revision argument is given, the status is calculated against
143
that revision, or between two revisions if two are provided.
250
Before merges are committed, the pending merge tip revisions are
251
shown. To see all pending merge revisions, use the -v option.
252
To skip the display of pending merge information altogether, use
253
the no-pending option or specify a file/directory.
255
To compare the working directory to a specific revision, pass a
256
single revision to the revision argument.
258
To see which files have changed in a specific revision, or between
259
two revisions, pass a revision range to the revision argument.
260
This will produce the same results as calling 'bzr diff --summarize'.
146
263
# TODO: --no-recurse, --recurse options
148
265
takes_args = ['file*']
149
takes_options = ['show-ids', 'revision']
266
takes_options = ['show-ids', 'revision', 'change', 'verbose',
267
Option('short', help='Use short status indicators.',
269
Option('versioned', help='Only show versioned files.',
271
Option('no-pending', help='Don\'t show pending merges.',
150
274
aliases = ['st', 'stat']
152
276
encoding_type = 'replace'
277
_see_also = ['diff', 'revert', 'status-flags']
155
def run(self, show_ids=False, file_list=None, revision=None):
280
def run(self, show_ids=False, file_list=None, revision=None, short=False,
281
versioned=False, no_pending=False, verbose=False):
156
282
from bzrlib.status import show_tree_status
158
tree, file_list = tree_files(file_list)
284
if revision and len(revision) > 2:
285
raise errors.BzrCommandError('bzr status --revision takes exactly'
286
' one or two revision specifiers')
288
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
289
# Avoid asking for specific files when that is not needed.
290
if relfile_list == ['']:
292
# Don't disable pending merges for full trees other than '.'.
293
if file_list == ['.']:
295
# A specific path within a tree was given.
296
elif relfile_list is not None:
160
298
show_tree_status(tree, show_ids=show_ids,
161
specific_files=file_list, revision=revision,
299
specific_files=relfile_list, revision=revision,
300
to_file=self.outf, short=short, versioned=versioned,
301
show_pending=(not no_pending), verbose=verbose)
165
304
class cmd_cat_revision(Command):
166
"""Write out metadata for a revision.
305
__doc__ = """Write out metadata for a revision.
168
307
The revision to print can either be specified by a specific
169
308
revision identifier, or you can use --revision.
173
312
takes_args = ['revision_id?']
174
takes_options = ['revision']
313
takes_options = ['directory', 'revision']
175
314
# cat-revision is more for frontends so should be exact
176
315
encoding = 'strict'
317
def print_revision(self, revisions, revid):
318
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
319
record = stream.next()
320
if record.storage_kind == 'absent':
321
raise errors.NoSuchRevision(revisions, revid)
322
revtext = record.get_bytes_as('fulltext')
323
self.outf.write(revtext.decode('utf-8'))
179
def run(self, revision_id=None, revision=None):
326
def run(self, revision_id=None, revision=None, directory=u'.'):
181
327
if revision_id is not None and revision is not None:
182
raise BzrCommandError('You can only supply one of revision_id or --revision')
328
raise errors.BzrCommandError('You can only supply one of'
329
' revision_id or --revision')
183
330
if revision_id is None and revision is None:
184
raise BzrCommandError('You must supply either --revision or a revision_id')
185
b = WorkingTree.open_containing(u'.')[0].branch
187
# TODO: jam 20060112 should cat-revision always output utf-8?
188
if revision_id is not None:
189
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
190
elif revision is not None:
193
raise BzrCommandError('You cannot specify a NULL revision.')
194
revno, rev_id = rev.in_history(b)
195
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
331
raise errors.BzrCommandError('You must supply either'
332
' --revision or a revision_id')
333
b = WorkingTree.open_containing(directory)[0].branch
335
revisions = b.repository.revisions
336
if revisions is None:
337
raise errors.BzrCommandError('Repository %r does not support '
338
'access to raw revision texts')
340
b.repository.lock_read()
342
# TODO: jam 20060112 should cat-revision always output utf-8?
343
if revision_id is not None:
344
revision_id = osutils.safe_revision_id(revision_id, warn=False)
346
self.print_revision(revisions, revision_id)
347
except errors.NoSuchRevision:
348
msg = "The repository %s contains no revision %s." % (
349
b.repository.base, revision_id)
350
raise errors.BzrCommandError(msg)
351
elif revision is not None:
354
raise errors.BzrCommandError(
355
'You cannot specify a NULL revision.')
356
rev_id = rev.as_revision_id(b)
357
self.print_revision(revisions, rev_id)
359
b.repository.unlock()
362
class cmd_dump_btree(Command):
363
__doc__ = """Dump the contents of a btree index file to stdout.
365
PATH is a btree index file, it can be any URL. This includes things like
366
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
368
By default, the tuples stored in the index file will be displayed. With
369
--raw, we will uncompress the pages, but otherwise display the raw bytes
373
# TODO: Do we want to dump the internal nodes as well?
374
# TODO: It would be nice to be able to dump the un-parsed information,
375
# rather than only going through iter_all_entries. However, this is
376
# good enough for a start
378
encoding_type = 'exact'
379
takes_args = ['path']
380
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
381
' rather than the parsed tuples.'),
384
def run(self, path, raw=False):
385
dirname, basename = osutils.split(path)
386
t = transport.get_transport(dirname)
388
self._dump_raw_bytes(t, basename)
390
self._dump_entries(t, basename)
392
def _get_index_and_bytes(self, trans, basename):
393
"""Create a BTreeGraphIndex and raw bytes."""
394
bt = btree_index.BTreeGraphIndex(trans, basename, None)
395
bytes = trans.get_bytes(basename)
396
bt._file = cStringIO.StringIO(bytes)
397
bt._size = len(bytes)
400
def _dump_raw_bytes(self, trans, basename):
403
# We need to parse at least the root node.
404
# This is because the first page of every row starts with an
405
# uncompressed header.
406
bt, bytes = self._get_index_and_bytes(trans, basename)
407
for page_idx, page_start in enumerate(xrange(0, len(bytes),
408
btree_index._PAGE_SIZE)):
409
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
410
page_bytes = bytes[page_start:page_end]
412
self.outf.write('Root node:\n')
413
header_end, data = bt._parse_header_from_bytes(page_bytes)
414
self.outf.write(page_bytes[:header_end])
416
self.outf.write('\nPage %d\n' % (page_idx,))
417
decomp_bytes = zlib.decompress(page_bytes)
418
self.outf.write(decomp_bytes)
419
self.outf.write('\n')
421
def _dump_entries(self, trans, basename):
423
st = trans.stat(basename)
424
except errors.TransportNotPossible:
425
# We can't stat, so we'll fake it because we have to do the 'get()'
427
bt, _ = self._get_index_and_bytes(trans, basename)
429
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
430
for node in bt.iter_all_entries():
431
# Node is made up of:
432
# (index, key, value, [references])
436
refs_as_tuples = None
438
refs_as_tuples = static_tuple.as_tuples(refs)
439
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
440
self.outf.write('%s\n' % (as_tuple,))
443
class cmd_remove_tree(Command):
444
__doc__ = """Remove the working tree from a given branch/checkout.
446
Since a lightweight checkout is little more than a working tree
447
this will refuse to run against one.
449
To re-create the working tree, use "bzr checkout".
451
_see_also = ['checkout', 'working-trees']
452
takes_args = ['location*']
455
help='Remove the working tree even if it has '
456
'uncommitted or shelved changes.'),
459
def run(self, location_list, force=False):
460
if not location_list:
463
for location in location_list:
464
d = bzrdir.BzrDir.open(location)
467
working = d.open_workingtree()
468
except errors.NoWorkingTree:
469
raise errors.BzrCommandError("No working tree to remove")
470
except errors.NotLocalUrl:
471
raise errors.BzrCommandError("You cannot remove the working tree"
474
if (working.has_changes()):
475
raise errors.UncommittedChanges(working)
476
if working.get_shelf_manager().last_shelf() is not None:
477
raise errors.ShelvedChanges(working)
479
if working.user_url != working.branch.user_url:
480
raise errors.BzrCommandError("You cannot remove the working tree"
481
" from a lightweight checkout")
483
d.destroy_workingtree()
198
486
class cmd_revno(Command):
199
"""Show current revision number.
487
__doc__ = """Show current revision number.
201
489
This is equal to the number of revisions on this branch.
204
493
takes_args = ['location?']
495
Option('tree', help='Show revno of working tree'),
207
def run(self, location=u'.'):
208
self.outf.write(str(Branch.open_containing(location)[0].revno()))
209
self.outf.write('\n')
499
def run(self, tree=False, location=u'.'):
502
wt = WorkingTree.open_containing(location)[0]
503
self.add_cleanup(wt.lock_read().unlock)
504
except (errors.NoWorkingTree, errors.NotLocalUrl):
505
raise errors.NoWorkingTree(location)
506
revid = wt.last_revision()
508
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
509
except errors.NoSuchRevision:
511
revno = ".".join(str(n) for n in revno_t)
513
b = Branch.open_containing(location)[0]
514
self.add_cleanup(b.lock_read().unlock)
517
self.outf.write(str(revno) + '\n')
212
520
class cmd_revision_info(Command):
213
"""Show revision number and revision id for a given revision identifier.
521
__doc__ = """Show revision number and revision id for a given revision identifier.
216
524
takes_args = ['revision_info*']
217
takes_options = ['revision']
527
custom_help('directory',
528
help='Branch to examine, '
529
'rather than the one containing the working directory.'),
530
Option('tree', help='Show revno of working tree'),
220
def run(self, revision=None, revision_info_list=[]):
534
def run(self, revision=None, directory=u'.', tree=False,
535
revision_info_list=[]):
538
wt = WorkingTree.open_containing(directory)[0]
540
self.add_cleanup(wt.lock_read().unlock)
541
except (errors.NoWorkingTree, errors.NotLocalUrl):
543
b = Branch.open_containing(directory)[0]
544
self.add_cleanup(b.lock_read().unlock)
223
546
if revision is not None:
224
revs.extend(revision)
547
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
225
548
if revision_info_list is not None:
226
for rev in revision_info_list:
227
revs.append(RevisionSpec(rev))
229
raise BzrCommandError('You must supply a revision identifier')
231
b = WorkingTree.open_containing(u'.')[0].branch
234
revinfo = rev.in_history(b)
235
if revinfo.revno is None:
236
print ' %s' % revinfo.rev_id
549
for rev_str in revision_info_list:
550
rev_spec = RevisionSpec.from_string(rev_str)
551
revision_ids.append(rev_spec.as_revision_id(b))
552
# No arguments supplied, default to the last revision
553
if len(revision_ids) == 0:
556
raise errors.NoWorkingTree(directory)
557
revision_ids.append(wt.last_revision())
238
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
559
revision_ids.append(b.last_revision())
563
for revision_id in revision_ids:
565
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
566
revno = '.'.join(str(i) for i in dotted_revno)
567
except errors.NoSuchRevision:
569
maxlen = max(maxlen, len(revno))
570
revinfos.append([revno, revision_id])
574
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
241
577
class cmd_add(Command):
242
"""Add specified files or directories.
578
__doc__ = """Add specified files or directories.
244
580
In non-recursive mode, all the named items are added, regardless
245
581
of whether they were previously ignored. A warning is given if
359
758
class cmd_mv(Command):
360
"""Move or rename a file.
759
__doc__ = """Move or rename a file.
363
762
bzr mv OLDNAME NEWNAME
364
764
bzr mv SOURCE... DESTINATION
366
766
If the last argument is a versioned directory, all the other names
367
767
are moved into it. Otherwise, there must be exactly two arguments
368
and the file is changed to a new name, which must not already exist.
768
and the file is changed to a new name.
770
If OLDNAME does not exist on the filesystem but is versioned and
771
NEWNAME does exist on the filesystem but is not versioned, mv
772
assumes that the file has been manually moved and only updates
773
its internal inventory to reflect that change.
774
The same is valid when moving many SOURCE files to a DESTINATION.
370
776
Files cannot be moved between branches.
373
779
takes_args = ['names*']
780
takes_options = [Option("after", help="Move only the bzr identifier"
781
" of the file, because the file has already been moved."),
782
Option('auto', help='Automatically guess renames.'),
783
Option('dry-run', help='Avoid making changes when guessing renames.'),
374
785
aliases = ['move', 'rename']
375
786
encoding_type = 'replace'
377
def run(self, names_list):
788
def run(self, names_list, after=False, auto=False, dry_run=False):
790
return self.run_auto(names_list, after, dry_run)
792
raise errors.BzrCommandError('--dry-run requires --auto.')
378
793
if names_list is None:
381
795
if len(names_list) < 2:
382
raise BzrCommandError("missing file argument")
383
tree, rel_names = tree_files(names_list)
385
if os.path.isdir(names_list[-1]):
796
raise errors.BzrCommandError("missing file argument")
797
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
798
self.add_cleanup(tree.lock_tree_write().unlock)
799
self._run(tree, names_list, rel_names, after)
801
def run_auto(self, names_list, after, dry_run):
802
if names_list is not None and len(names_list) > 1:
803
raise errors.BzrCommandError('Only one path may be specified to'
806
raise errors.BzrCommandError('--after cannot be specified with'
808
work_tree, file_list = WorkingTree.open_containing_paths(
809
names_list, default_directory='.')
810
self.add_cleanup(work_tree.lock_tree_write().unlock)
811
rename_map.RenameMap.guess_renames(work_tree, dry_run)
813
def _run(self, tree, names_list, rel_names, after):
814
into_existing = osutils.isdir(names_list[-1])
815
if into_existing and len(names_list) == 2:
817
# a. case-insensitive filesystem and change case of dir
818
# b. move directory after the fact (if the source used to be
819
# a directory, but now doesn't exist in the working tree
820
# and the target is an existing directory, just rename it)
821
if (not tree.case_sensitive
822
and rel_names[0].lower() == rel_names[1].lower()):
823
into_existing = False
826
# 'fix' the case of a potential 'from'
827
from_id = tree.path2id(
828
tree.get_canonical_inventory_path(rel_names[0]))
829
if (not osutils.lexists(names_list[0]) and
830
from_id and inv.get_file_kind(from_id) == "directory"):
831
into_existing = False
386
834
# move into existing directory
387
for pair in tree.move(rel_names[:-1], rel_names[-1]):
388
self.outf.write("%s => %s\n" % pair)
835
# All entries reference existing inventory items, so fix them up
836
# for cicp file-systems.
837
rel_names = tree.get_canonical_inventory_paths(rel_names)
838
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
840
self.outf.write("%s => %s\n" % (src, dest))
390
842
if len(names_list) != 2:
391
raise BzrCommandError('to mv multiple files the destination '
392
'must be a versioned directory')
393
tree.rename_one(rel_names[0], rel_names[1])
394
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
843
raise errors.BzrCommandError('to mv multiple files the'
844
' destination must be a versioned'
847
# for cicp file-systems: the src references an existing inventory
849
src = tree.get_canonical_inventory_path(rel_names[0])
850
# Find the canonical version of the destination: In all cases, the
851
# parent of the target must be in the inventory, so we fetch the
852
# canonical version from there (we do not always *use* the
853
# canonicalized tail portion - we may be attempting to rename the
855
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
856
dest_parent = osutils.dirname(canon_dest)
857
spec_tail = osutils.basename(rel_names[1])
858
# For a CICP file-system, we need to avoid creating 2 inventory
859
# entries that differ only by case. So regardless of the case
860
# we *want* to use (ie, specified by the user or the file-system),
861
# we must always choose to use the case of any existing inventory
862
# items. The only exception to this is when we are attempting a
863
# case-only rename (ie, canonical versions of src and dest are
865
dest_id = tree.path2id(canon_dest)
866
if dest_id is None or tree.path2id(src) == dest_id:
867
# No existing item we care about, so work out what case we
868
# are actually going to use.
870
# If 'after' is specified, the tail must refer to a file on disk.
872
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
874
# pathjoin with an empty tail adds a slash, which breaks
876
dest_parent_fq = tree.basedir
878
dest_tail = osutils.canonical_relpath(
880
osutils.pathjoin(dest_parent_fq, spec_tail))
882
# not 'after', so case as specified is used
883
dest_tail = spec_tail
885
# Use the existing item so 'mv' fails with AlreadyVersioned.
886
dest_tail = os.path.basename(canon_dest)
887
dest = osutils.pathjoin(dest_parent, dest_tail)
888
mutter("attempting to move %s => %s", src, dest)
889
tree.rename_one(src, dest, after=after)
891
self.outf.write("%s => %s\n" % (src, dest))
397
894
class cmd_pull(Command):
398
"""Turn this branch into a mirror of another branch.
895
__doc__ = """Turn this branch into a mirror of another branch.
400
This command only works on branches that have not diverged. Branches are
401
considered diverged if the destination branch's most recent commit is one
402
that has not been merged (directly or indirectly) into the parent.
897
By default, this command only works on branches that have not diverged.
898
Branches are considered diverged if the destination branch's most recent
899
commit is one that has not been merged (directly or indirectly) into the
404
902
If branches have diverged, you can use 'bzr merge' to integrate the changes
405
903
from one into the other. Once one branch has merged, the other should
406
904
be able to pull it again.
408
If you want to forget your local changes and just update your branch to
409
match the remote one, use pull --overwrite.
906
If you want to replace your local changes and just want your branch to
907
match the remote one, use pull --overwrite. This will work even if the two
908
branches have diverged.
411
910
If there is no default location set, the first pull will set it. After
412
911
that, you can omit the location to use the default. To change the
413
912
default, use --remember. The value will only be saved if the remote
414
913
location can be accessed.
915
Note: The location can be specified either in the form of a branch,
916
or in the form of a path to a file containing a merge directive generated
417
takes_options = ['remember', 'overwrite', 'revision', 'verbose']
920
_see_also = ['push', 'update', 'status-flags', 'send']
921
takes_options = ['remember', 'overwrite', 'revision',
922
custom_help('verbose',
923
help='Show logs of pulled revisions.'),
924
custom_help('directory',
925
help='Branch to pull into, '
926
'rather than the one containing the working directory.'),
928
help="Perform a local pull in a bound "
929
"branch. Local pulls are not applied to "
933
help="Show base revision text in conflicts.")
418
935
takes_args = ['location?']
419
936
encoding_type = 'replace'
421
def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
938
def run(self, location=None, remember=False, overwrite=False,
939
revision=None, verbose=False,
940
directory=None, local=False,
422
942
# FIXME: too much stuff is in the command class
945
if directory is None:
424
tree_to = WorkingTree.open_containing(u'.')[0]
948
tree_to = WorkingTree.open_containing(directory)[0]
425
949
branch_to = tree_to.branch
426
except NoWorkingTree:
950
self.add_cleanup(tree_to.lock_write().unlock)
951
except errors.NoWorkingTree:
428
branch_to = Branch.open_containing(u'.')[0]
953
branch_to = Branch.open_containing(directory)[0]
954
self.add_cleanup(branch_to.lock_write().unlock)
956
if tree_to is None and show_base:
957
raise errors.BzrCommandError("Need working tree for --show-base.")
959
if local and not branch_to.get_bound_location():
960
raise errors.LocalRequiresBoundBranch()
962
possible_transports = []
431
963
if location is not None:
433
reader = bundle.read_bundle_from_url(location)
435
pass # Continue on considering this url a Branch
965
mergeable = bundle.read_mergeable_from_url(location,
966
possible_transports=possible_transports)
967
except errors.NotABundle:
437
970
stored_loc = branch_to.get_parent()
438
971
if location is None:
439
972
if stored_loc is None:
440
raise BzrCommandError("No pull location known or specified.")
973
raise errors.BzrCommandError("No pull location known or"
442
976
display_url = urlutils.unescape_for_display(stored_loc,
443
977
self.outf.encoding)
444
self.outf.write("Using saved location: %s\n" % display_url)
979
self.outf.write("Using saved parent location: %s\n" % display_url)
445
980
location = stored_loc
448
if reader is not None:
449
install_bundle(branch_to.repository, reader)
982
revision = _get_one_revision('pull', revision)
983
if mergeable is not None:
984
if revision is not None:
985
raise errors.BzrCommandError(
986
'Cannot use -r with merge directives or bundles')
987
mergeable.install_revisions(branch_to.repository)
988
base_revision_id, revision_id, verified = \
989
mergeable.get_merge_request(branch_to.repository)
450
990
branch_from = branch_to
452
branch_from = Branch.open(location)
992
branch_from = Branch.open(location,
993
possible_transports=possible_transports)
994
self.add_cleanup(branch_from.lock_read().unlock)
454
996
if branch_to.get_parent() is None or remember:
455
997
branch_to.set_parent(branch_from.base)
459
if reader is not None:
460
rev_id = reader.target
461
elif len(revision) == 1:
462
rev_id = revision[0].in_history(branch_from).rev_id
464
raise BzrCommandError('bzr pull --revision takes one value.')
999
if revision is not None:
1000
revision_id = revision.as_revision_id(branch_from)
466
old_rh = branch_to.revision_history()
467
1002
if tree_to is not None:
468
count = tree_to.pull(branch_from, overwrite, rev_id)
1003
view_info = _get_view_info_for_change_reporter(tree_to)
1004
change_reporter = delta._ChangeReporter(
1005
unversioned_filter=tree_to.is_ignored,
1006
view_info=view_info)
1007
result = tree_to.pull(
1008
branch_from, overwrite, revision_id, change_reporter,
1009
possible_transports=possible_transports, local=local,
1010
show_base=show_base)
470
count = branch_to.pull(branch_from, overwrite, rev_id)
471
note('%d revision(s) pulled.' % (count,))
1012
result = branch_to.pull(
1013
branch_from, overwrite, revision_id, local=local)
474
new_rh = branch_to.revision_history()
477
from bzrlib.log import show_changed_revisions
478
show_changed_revisions(branch_to, old_rh, new_rh,
1015
result.report(self.outf)
1016
if verbose and result.old_revid != result.new_revid:
1017
log.show_branch_change(
1018
branch_to, self.outf, result.old_revno,
482
1022
class cmd_push(Command):
483
"""Update a mirror of this branch.
1023
__doc__ = """Update a mirror of this branch.
485
1025
The target branch will not have its working tree populated because this
486
1026
is both expensive, and is not supported on remote file systems.
488
1028
Some smart servers or protocols *may* put the working tree in place in
505
1045
location can be accessed.
508
takes_options = ['remember', 'overwrite', 'verbose',
509
Option('create-prefix',
510
help='Create the path leading up to the branch '
511
'if it does not already exist')]
1048
_see_also = ['pull', 'update', 'working-trees']
1049
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
1050
Option('create-prefix',
1051
help='Create the path leading up to the branch '
1052
'if it does not already exist.'),
1053
custom_help('directory',
1054
help='Branch to push from, '
1055
'rather than the one containing the working directory.'),
1056
Option('use-existing-dir',
1057
help='By default push will fail if the target'
1058
' directory exists, but does not already'
1059
' have a control directory. This flag will'
1060
' allow push to proceed.'),
1062
help='Create a stacked branch that references the public location '
1063
'of the parent branch.'),
1064
Option('stacked-on',
1065
help='Create a stacked branch that refers to another branch '
1066
'for the commit history. Only the work not present in the '
1067
'referenced branch is included in the branch created.',
1070
help='Refuse to push if there are uncommitted changes in'
1071
' the working tree, --no-strict disables the check.'),
1073
help="Don't populate the working tree, even for protocols"
1074
" that support it."),
512
1076
takes_args = ['location?']
513
1077
encoding_type = 'replace'
515
1079
def run(self, location=None, remember=False, overwrite=False,
516
create_prefix=False, verbose=False):
517
# FIXME: Way too big! Put this into a function called from the
519
from bzrlib.transport import get_transport
521
br_from = Branch.open_containing('.')[0]
522
stored_loc = br_from.get_push_location()
1080
create_prefix=False, verbose=False, revision=None,
1081
use_existing_dir=False, directory=None, stacked_on=None,
1082
stacked=False, strict=None, no_tree=False):
1083
from bzrlib.push import _show_push_branch
1085
if directory is None:
1087
# Get the source branch
1089
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1090
# Get the tip's revision_id
1091
revision = _get_one_revision('push', revision)
1092
if revision is not None:
1093
revision_id = revision.in_history(br_from).rev_id
1096
if tree is not None and revision_id is None:
1097
tree.check_changed_or_out_of_date(
1098
strict, 'push_strict',
1099
more_error='Use --no-strict to force the push.',
1100
more_warning='Uncommitted changes will not be pushed.')
1101
# Get the stacked_on branch, if any
1102
if stacked_on is not None:
1103
stacked_on = urlutils.normalize_url(stacked_on)
1105
parent_url = br_from.get_parent()
1107
parent = Branch.open(parent_url)
1108
stacked_on = parent.get_public_branch()
1110
# I considered excluding non-http url's here, thus forcing
1111
# 'public' branches only, but that only works for some
1112
# users, so it's best to just depend on the user spotting an
1113
# error by the feedback given to them. RBC 20080227.
1114
stacked_on = parent_url
1116
raise errors.BzrCommandError(
1117
"Could not determine branch to refer to.")
1119
# Get the destination location
523
1120
if location is None:
1121
stored_loc = br_from.get_push_location()
524
1122
if stored_loc is None:
525
raise BzrCommandError("No push location known or specified.")
1123
raise errors.BzrCommandError(
1124
"No push location known or specified.")
527
1126
display_url = urlutils.unescape_for_display(stored_loc,
528
1127
self.outf.encoding)
529
self.outf.write("Using saved location: %s\n" % display_url)
1128
self.outf.write("Using saved push location: %s\n" % display_url)
530
1129
location = stored_loc
532
transport = get_transport(location)
533
location_url = transport.base
537
dir_to = bzrdir.BzrDir.open(location_url)
538
br_to = dir_to.open_branch()
539
except NotBranchError:
541
transport = transport.clone('..')
542
if not create_prefix:
544
relurl = transport.relpath(location_url)
545
mutter('creating directory %s => %s', location_url, relurl)
546
transport.mkdir(relurl)
548
raise BzrCommandError("Parent directory of %s "
549
"does not exist." % location)
551
current = transport.base
552
needed = [(transport, transport.relpath(location_url))]
555
transport, relpath = needed[-1]
556
transport.mkdir(relpath)
559
new_transport = transport.clone('..')
560
needed.append((new_transport,
561
new_transport.relpath(transport.base)))
562
if new_transport.base == transport.base:
563
raise BzrCommandError("Could not create "
565
dir_to = br_from.bzrdir.clone(location_url,
566
revision_id=br_from.last_revision())
567
br_to = dir_to.open_branch()
568
count = len(br_to.revision_history())
569
# We successfully created the target, remember it
570
if br_from.get_push_location() is None or remember:
571
br_from.set_push_location(br_to.base)
573
# We were able to connect to the remote location, so remember it
574
# we don't need to successfully push because of possible divergence.
575
if br_from.get_push_location() is None or remember:
576
br_from.set_push_location(br_to.base)
577
old_rh = br_to.revision_history()
580
tree_to = dir_to.open_workingtree()
581
except errors.NotLocalUrl:
582
warning('This transport does not update the working '
583
'tree of: %s' % (br_to.base,))
584
count = br_to.pull(br_from, overwrite)
585
except NoWorkingTree:
586
count = br_to.pull(br_from, overwrite)
588
count = tree_to.pull(br_from, overwrite)
589
except DivergedBranches:
590
raise BzrCommandError("These branches have diverged."
591
" Try a merge then push with overwrite.")
592
note('%d revision(s) pushed.' % (count,))
595
new_rh = br_to.revision_history()
598
from bzrlib.log import show_changed_revisions
599
show_changed_revisions(br_to, old_rh, new_rh,
1131
_show_push_branch(br_from, revision_id, location, self.outf,
1132
verbose=verbose, overwrite=overwrite, remember=remember,
1133
stacked_on=stacked_on, create_prefix=create_prefix,
1134
use_existing_dir=use_existing_dir, no_tree=no_tree)
603
1137
class cmd_branch(Command):
604
"""Create a new copy of a branch.
1138
__doc__ = """Create a new branch that is a copy of an existing branch.
606
1140
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
607
1141
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1142
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
1143
is derived from the FROM_LOCATION by stripping a leading scheme or drive
1144
identifier, if any. For example, "branch lp:foo-bar" will attempt to
609
1147
To retrieve the branch as of a particular revision, supply the --revision
610
1148
parameter, as in "branch foo/bar -r 5".
612
--basis is to speed up branching from remote branches. When specified, it
613
copies all the file-contents, inventory and revision data from the basis
614
branch before copying anything from the remote branch.
1151
_see_also = ['checkout']
616
1152
takes_args = ['from_location', 'to_location?']
617
takes_options = ['revision', 'basis']
1153
takes_options = ['revision',
1154
Option('hardlink', help='Hard-link working tree files where possible.'),
1155
Option('files-from', type=str,
1156
help="Get file contents from this tree."),
1158
help="Create a branch without a working-tree."),
1160
help="Switch the checkout in the current directory "
1161
"to the new branch."),
1163
help='Create a stacked branch referring to the source branch. '
1164
'The new branch will depend on the availability of the source '
1165
'branch for all operations.'),
1166
Option('standalone',
1167
help='Do not use a shared repository, even if available.'),
1168
Option('use-existing-dir',
1169
help='By default branch will fail if the target'
1170
' directory exists, but does not already'
1171
' have a control directory. This flag will'
1172
' allow branch to proceed.'),
1174
help="Bind new branch to from location."),
618
1176
aliases = ['get', 'clone']
620
def run(self, from_location, to_location=None, revision=None, basis=None):
621
from bzrlib.transport import get_transport
624
elif len(revision) > 1:
625
raise BzrCommandError(
626
'bzr branch --revision takes exactly 1 revision value')
628
br_from = Branch.open(from_location)
630
if e.errno == errno.ENOENT:
631
raise BzrCommandError('Source location "%s" does not'
632
' exist.' % to_location)
637
if basis is not None:
638
basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
641
if len(revision) == 1 and revision[0] is not None:
642
revision_id = revision[0].in_history(br_from)[1]
644
# FIXME - wt.last_revision, fallback to branch, fall back to
645
# None or perhaps NULL_REVISION to mean copy nothing
647
revision_id = br_from.last_revision()
648
if to_location is None:
649
to_location = os.path.basename(from_location.rstrip("/\\"))
652
name = os.path.basename(to_location) + '\n'
654
to_transport = get_transport(to_location)
656
to_transport.mkdir('.')
657
except errors.FileExists:
658
raise BzrCommandError('Target directory "%s" already'
659
' exists.' % to_location)
660
except errors.NoSuchFile:
661
raise BzrCommandError('Parent of "%s" does not exist.' %
664
# preserve whatever source format we have.
665
dir = br_from.bzrdir.sprout(to_transport.base,
666
revision_id, basis_dir)
667
branch = dir.open_branch()
668
except errors.NoSuchRevision:
669
to_transport.delete_tree('.')
670
msg = "The branch %s has no revision %s." % (from_location, revision[0])
671
raise BzrCommandError(msg)
672
except errors.UnlistableBranch:
673
osutils.rmtree(to_location)
674
msg = "The branch %s cannot be used as a --basis" % (basis,)
675
raise BzrCommandError(msg)
677
branch.control_files.put_utf8('branch-name', name)
1178
def run(self, from_location, to_location=None, revision=None,
1179
hardlink=False, stacked=False, standalone=False, no_tree=False,
1180
use_existing_dir=False, switch=False, bind=False,
1182
from bzrlib import switch as _mod_switch
1183
from bzrlib.tag import _merge_tags_if_possible
1184
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1186
if not (hardlink or files_from):
1187
# accelerator_tree is usually slower because you have to read N
1188
# files (no readahead, lots of seeks, etc), but allow the user to
1189
# explicitly request it
1190
accelerator_tree = None
1191
if files_from is not None and files_from != from_location:
1192
accelerator_tree = WorkingTree.open(files_from)
1193
revision = _get_one_revision('branch', revision)
1194
self.add_cleanup(br_from.lock_read().unlock)
1195
if revision is not None:
1196
revision_id = revision.as_revision_id(br_from)
1198
# FIXME - wt.last_revision, fallback to branch, fall back to
1199
# None or perhaps NULL_REVISION to mean copy nothing
1201
revision_id = br_from.last_revision()
1202
if to_location is None:
1203
to_location = urlutils.derive_to_location(from_location)
1204
to_transport = transport.get_transport(to_location)
1206
to_transport.mkdir('.')
1207
except errors.FileExists:
1208
if not use_existing_dir:
1209
raise errors.BzrCommandError('Target directory "%s" '
1210
'already exists.' % to_location)
1213
bzrdir.BzrDir.open_from_transport(to_transport)
1214
except errors.NotBranchError:
1217
raise errors.AlreadyBranchError(to_location)
1218
except errors.NoSuchFile:
1219
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1222
# preserve whatever source format we have.
1223
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1224
possible_transports=[to_transport],
1225
accelerator_tree=accelerator_tree,
1226
hardlink=hardlink, stacked=stacked,
1227
force_new_repo=standalone,
1228
create_tree_if_local=not no_tree,
1229
source_branch=br_from)
1230
branch = dir.open_branch()
1231
except errors.NoSuchRevision:
1232
to_transport.delete_tree('.')
1233
msg = "The branch %s has no revision %s." % (from_location,
1235
raise errors.BzrCommandError(msg)
1236
_merge_tags_if_possible(br_from, branch)
1237
# If the source branch is stacked, the new branch may
1238
# be stacked whether we asked for that explicitly or not.
1239
# We therefore need a try/except here and not just 'if stacked:'
1241
note('Created new stacked branch referring to %s.' %
1242
branch.get_stacked_on_url())
1243
except (errors.NotStacked, errors.UnstackableBranchFormat,
1244
errors.UnstackableRepositoryFormat), e:
678
1245
note('Branched %d revision(s).' % branch.revno())
1247
# Bind to the parent
1248
parent_branch = Branch.open(from_location)
1249
branch.bind(parent_branch)
1250
note('New branch bound to %s' % from_location)
1252
# Switch to the new branch
1253
wt, _ = WorkingTree.open_containing('.')
1254
_mod_switch.switch(wt.bzrdir, branch)
1255
note('Switched to branch: %s',
1256
urlutils.unescape_for_display(branch.base, 'utf-8'))
683
1259
class cmd_checkout(Command):
684
"""Create a new checkout of an existing branch.
1260
__doc__ = """Create a new checkout of an existing branch.
686
1262
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
687
1263
the branch found in '.'. This is useful if you have removed the working tree
688
1264
or if it was never created - i.e. if you pushed the branch to its current
689
1265
location using SFTP.
691
1267
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
692
1268
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1269
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1270
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1271
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
694
1274
To retrieve the branch as of a particular revision, supply the --revision
695
1275
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
696
1276
out of date [so you cannot commit] but it may be useful (i.e. to examine old
699
--basis is to speed up checking out from remote branches. When specified, it
700
uses the inventory and file contents from the basis branch in preference to the
701
branch being checked out.
1280
_see_also = ['checkouts', 'branch']
703
1281
takes_args = ['branch_location?', 'to_location?']
704
takes_options = ['revision', # , 'basis']
1282
takes_options = ['revision',
705
1283
Option('lightweight',
706
help="perform a lightweight checkout. Lightweight "
1284
help="Perform a lightweight checkout. Lightweight "
707
1285
"checkouts depend on access to the branch for "
708
"every operation. Normal checkouts can perform "
1286
"every operation. Normal checkouts can perform "
709
1287
"common operations like diff and status without "
710
1288
"such access, and also support local commits."
1290
Option('files-from', type=str,
1291
help="Get file contents from this tree."),
1293
help='Hard-link working tree files where possible.'
713
1296
aliases = ['co']
715
def run(self, branch_location=None, to_location=None, revision=None, basis=None,
719
elif len(revision) > 1:
720
raise BzrCommandError(
721
'bzr checkout --revision takes exactly 1 revision value')
1298
def run(self, branch_location=None, to_location=None, revision=None,
1299
lightweight=False, files_from=None, hardlink=False):
722
1300
if branch_location is None:
723
1301
branch_location = osutils.getcwd()
724
1302
to_location = branch_location
725
source = Branch.open(branch_location)
726
if len(revision) == 1 and revision[0] is not None:
727
revision_id = revision[0].in_history(source)[1]
1303
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1305
if not (hardlink or files_from):
1306
# accelerator_tree is usually slower because you have to read N
1307
# files (no readahead, lots of seeks, etc), but allow the user to
1308
# explicitly request it
1309
accelerator_tree = None
1310
revision = _get_one_revision('checkout', revision)
1311
if files_from is not None and files_from != branch_location:
1312
accelerator_tree = WorkingTree.open(files_from)
1313
if revision is not None:
1314
revision_id = revision.as_revision_id(source)
729
1316
revision_id = None
730
1317
if to_location is None:
731
to_location = os.path.basename(branch_location.rstrip("/\\"))
732
# if the source and to_location are the same,
1318
to_location = urlutils.derive_to_location(branch_location)
1319
# if the source and to_location are the same,
733
1320
# and there is no working tree,
734
1321
# then reconstitute a branch
735
if (osutils.abspath(to_location) ==
1322
if (osutils.abspath(to_location) ==
736
1323
osutils.abspath(branch_location)):
738
1325
source.bzrdir.open_workingtree()
739
1326
except errors.NoWorkingTree:
740
source.bzrdir.create_workingtree()
1327
source.bzrdir.create_workingtree(revision_id)
743
os.mkdir(to_location)
745
if e.errno == errno.EEXIST:
746
raise BzrCommandError('Target directory "%s" already'
747
' exists.' % to_location)
748
if e.errno == errno.ENOENT:
749
raise BzrCommandError('Parent of "%s" does not exist.' %
753
old_format = bzrdir.BzrDirFormat.get_default_format()
754
bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
757
checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
758
branch.BranchReferenceFormat().initialize(checkout, source)
760
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
761
to_location, force_new_tree=False)
762
checkout = checkout_branch.bzrdir
763
checkout_branch.bind(source)
764
if revision_id is not None:
765
rh = checkout_branch.revision_history()
766
checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
767
checkout.create_workingtree(revision_id)
769
bzrdir.BzrDirFormat.set_default_format(old_format)
1329
source.create_checkout(to_location, revision_id, lightweight,
1330
accelerator_tree, hardlink)
772
1333
class cmd_renames(Command):
773
"""Show list of renamed files.
1334
__doc__ = """Show list of renamed files.
775
1336
# TODO: Option to show renames between two historical versions.
777
1338
# TODO: Only show renames under dir, rather than in the whole branch.
1339
_see_also = ['status']
778
1340
takes_args = ['dir?']
780
1342
@display_command
781
1343
def run(self, dir=u'.'):
782
from bzrlib.tree import find_renames
783
1344
tree = WorkingTree.open_containing(dir)[0]
784
old_inv = tree.basis_tree().inventory
785
new_inv = tree.read_working_inventory()
786
renames = list(find_renames(old_inv, new_inv))
1345
self.add_cleanup(tree.lock_read().unlock)
1346
new_inv = tree.inventory
1347
old_tree = tree.basis_tree()
1348
self.add_cleanup(old_tree.lock_read().unlock)
1349
old_inv = old_tree.inventory
1351
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1352
for f, paths, c, v, p, n, k, e in iterator:
1353
if paths[0] == paths[1]:
1357
renames.append(paths)
788
1359
for old_name, new_name in renames:
789
1360
self.outf.write("%s => %s\n" % (old_name, new_name))
792
1363
class cmd_update(Command):
793
"""Update a tree to have the latest code committed to its branch.
1364
__doc__ = """Update a tree to have the latest code committed to its branch.
795
1366
This will perform a merge into the working tree, and may generate
796
conflicts. If you have any local changes, you will still
1367
conflicts. If you have any local changes, you will still
797
1368
need to commit them after the update for the update to be complete.
799
If you want to discard your local changes, you can just do a
1370
If you want to discard your local changes, you can just do a
800
1371
'bzr revert' instead of 'bzr commit' after the update.
1373
If you want to restore a file that has been removed locally, use
1374
'bzr revert' instead of 'bzr update'.
1376
If the tree's branch is bound to a master branch, it will also update
1377
the branch from the master.
1380
_see_also = ['pull', 'working-trees', 'status-flags']
802
1381
takes_args = ['dir?']
1382
takes_options = ['revision',
1384
help="Show base revision text in conflicts."),
804
def run(self, dir='.'):
1388
def run(self, dir='.', revision=None, show_base=None):
1389
if revision is not None and len(revision) != 1:
1390
raise errors.BzrCommandError(
1391
"bzr update --revision takes exactly one revision")
805
1392
tree = WorkingTree.open_containing(dir)[0]
1393
branch = tree.branch
1394
possible_transports = []
1395
master = branch.get_master_branch(
1396
possible_transports=possible_transports)
1397
if master is not None:
1398
branch_location = master.base
1401
branch_location = tree.branch.base
1402
tree.lock_tree_write()
1403
self.add_cleanup(tree.unlock)
1404
# get rid of the final '/' and be ready for display
1405
branch_location = urlutils.unescape_for_display(
1406
branch_location.rstrip('/'),
1408
existing_pending_merges = tree.get_parent_ids()[1:]
1412
# may need to fetch data into a heavyweight checkout
1413
# XXX: this may take some time, maybe we should display a
1415
old_tip = branch.update(possible_transports)
1416
if revision is not None:
1417
revision_id = revision[0].as_revision_id(branch)
1419
revision_id = branch.last_revision()
1420
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1421
revno = branch.revision_id_to_dotted_revno(revision_id)
1422
note("Tree is up to date at revision %s of branch %s" %
1423
('.'.join(map(str, revno)), branch_location))
1425
view_info = _get_view_info_for_change_reporter(tree)
1426
change_reporter = delta._ChangeReporter(
1427
unversioned_filter=tree.is_ignored,
1428
view_info=view_info)
808
last_rev = tree.last_revision()
809
if last_rev == tree.branch.last_revision():
810
# may be up to date, check master too.
811
master = tree.branch.get_master_branch()
812
if master is None or last_rev == master.last_revision():
813
revno = tree.branch.revision_id_to_revno(last_rev)
814
note("Tree is up to date at revision %d." % (revno,))
816
conflicts = tree.update()
817
revno = tree.branch.revision_id_to_revno(tree.last_revision())
818
note('Updated to revision %d.' % (revno,))
1430
conflicts = tree.update(
1432
possible_transports=possible_transports,
1433
revision=revision_id,
1435
show_base=show_base)
1436
except errors.NoSuchRevision, e:
1437
raise errors.BzrCommandError(
1438
"branch has no revision %s\n"
1439
"bzr update --revision only works"
1440
" for a revision in the branch history"
1442
revno = tree.branch.revision_id_to_dotted_revno(
1443
_mod_revision.ensure_null(tree.last_revision()))
1444
note('Updated to revision %s of branch %s' %
1445
('.'.join(map(str, revno)), branch_location))
1446
parent_ids = tree.get_parent_ids()
1447
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1448
note('Your local commits will now show as pending merges with '
1449
"'bzr status', and can be committed with 'bzr commit'.")
827
1456
class cmd_info(Command):
828
"""Show information about a working tree, branch or repository.
1457
__doc__ = """Show information about a working tree, branch or repository.
830
1459
This command will show all known locations and formats associated to the
831
tree, branch or repository. Statistical information is included with
1460
tree, branch or repository.
1462
In verbose mode, statistical information is included with each report.
1463
To see extended statistic information, use a verbosity level of 2 or
1464
higher by specifying the verbose option multiple times, e.g. -vv.
834
1466
Branches and working trees will also report any missing revisions.
1470
Display information on the format and related locations:
1474
Display the above together with extended format information and
1475
basic statistics (like the number of files in the working tree and
1476
number of revisions in the branch and repository):
1480
Display the above together with number of committers to the branch:
1484
_see_also = ['revno', 'working-trees', 'repositories']
836
1485
takes_args = ['location?']
837
1486
takes_options = ['verbose']
1487
encoding_type = 'replace'
839
1489
@display_command
840
1490
def run(self, location=None, verbose=False):
1492
noise_level = get_verbosity_level()
841
1495
from bzrlib.info import show_bzrdir_info
842
1496
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1497
verbose=noise_level, outfile=self.outf)
846
1500
class cmd_remove(Command):
847
"""Make a file unversioned.
849
This makes bzr stop tracking changes to a versioned file. It does
850
not delete the working copy.
852
You can specify one or more files, and/or --new. If you specify --new,
853
only 'added' files will be removed. If you specify both, then new files
854
in the specified directories will be removed. If the directories are
855
also new, they will also be removed.
1501
__doc__ = """Remove files or directories.
1503
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1504
delete them if they can easily be recovered using revert otherwise they
1505
will be backed up (adding an extention of the form .~#~). If no options or
1506
parameters are given Bazaar will scan for files that are being tracked by
1507
Bazaar but missing in your tree and stop tracking them for you.
857
1509
takes_args = ['file*']
858
takes_options = ['verbose', Option('new', help='remove newly-added files')]
1510
takes_options = ['verbose',
1511
Option('new', help='Only remove files that have never been committed.'),
1512
RegistryOption.from_kwargs('file-deletion-strategy',
1513
'The file deletion mode to be used.',
1514
title='Deletion Strategy', value_switches=True, enum_switch=False,
1515
safe='Backup changed files (default).',
1516
keep='Delete from bzr but leave the working copy.',
1517
no_backup='Don\'t backup changed files.',
1518
force='Delete all the specified files, even if they can not be '
1519
'recovered and even if they are non-empty directories. '
1520
'(deprecated, use no-backup)')]
1521
aliases = ['rm', 'del']
860
1522
encoding_type = 'replace'
862
def run(self, file_list, verbose=False, new=False):
863
tree, file_list = tree_files(file_list)
865
if file_list is None:
866
raise BzrCommandError('Specify one or more files to remove, or'
869
from bzrlib.delta import compare_trees
870
added = [compare_trees(tree.basis_tree(), tree,
871
specific_files=file_list).added]
872
file_list = sorted([f[0] for f in added[0]], reverse=True)
1524
def run(self, file_list, verbose=False, new=False,
1525
file_deletion_strategy='safe'):
1526
if file_deletion_strategy == 'force':
1527
note("(The --force option is deprecated, rather use --no-backup "
1529
file_deletion_strategy = 'no-backup'
1531
tree, file_list = WorkingTree.open_containing_paths(file_list)
1533
if file_list is not None:
1534
file_list = [f for f in file_list]
1536
self.add_cleanup(tree.lock_write().unlock)
1537
# Heuristics should probably all move into tree.remove_smart or
1540
added = tree.changes_from(tree.basis_tree(),
1541
specific_files=file_list).added
1542
file_list = sorted([f[0] for f in added], reverse=True)
873
1543
if len(file_list) == 0:
874
raise BzrCommandError('No matching files.')
875
tree.remove(file_list, verbose=verbose, to_file=self.outf)
1544
raise errors.BzrCommandError('No matching files.')
1545
elif file_list is None:
1546
# missing files show up in iter_changes(basis) as
1547
# versioned-with-no-kind.
1549
for change in tree.iter_changes(tree.basis_tree()):
1550
# Find paths in the working tree that have no kind:
1551
if change[1][1] is not None and change[6][1] is None:
1552
missing.append(change[1][1])
1553
file_list = sorted(missing, reverse=True)
1554
file_deletion_strategy = 'keep'
1555
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1556
keep_files=file_deletion_strategy=='keep',
1557
force=(file_deletion_strategy=='no-backup'))
878
1560
class cmd_file_id(Command):
879
"""Print file_id of a particular file or directory.
1561
__doc__ = """Print file_id of a particular file or directory.
881
1563
The file_id is assigned when the file is first added and remains the
882
1564
same through all revisions where the file exists, even when it is
975
1671
last_revision = wt.last_revision()
977
1673
revision_ids = b.repository.get_ancestry(last_revision)
978
assert revision_ids[0] == None
979
1674
revision_ids.pop(0)
980
1675
for revision_id in revision_ids:
981
1676
self.outf.write(revision_id + '\n')
984
1679
class cmd_init(Command):
985
"""Make a directory into a versioned branch.
1680
__doc__ = """Make a directory into a versioned branch.
987
1682
Use this to create an empty branch, or before importing an
988
1683
existing project.
990
If there is a repository in a parent directory of the location, then
1685
If there is a repository in a parent directory of the location, then
991
1686
the history of the branch will be stored in the repository. Otherwise
992
init creates a standalone branch which carries its own history in
1687
init creates a standalone branch which carries its own history
1688
in the .bzr directory.
995
1690
If there is already a branch at the location but it has no working tree,
996
1691
the tree can be populated with 'bzr checkout'.
998
Recipe for importing a tree of files:
1693
Recipe for importing a tree of files::
1003
bzr commit -m 'imported project'
1699
bzr commit -m "imported project"
1702
_see_also = ['init-repository', 'branch', 'checkout']
1005
1703
takes_args = ['location?']
1006
1704
takes_options = [
1008
help='Specify a format for this branch. Current'
1009
' formats are: default, knit, metaweave and'
1010
' weave. Default is knit; metaweave and'
1011
' weave are deprecated',
1012
type=get_format_type),
1014
def run(self, location=None, format=None):
1705
Option('create-prefix',
1706
help='Create the path leading up to the branch '
1707
'if it does not already exist.'),
1708
RegistryOption('format',
1709
help='Specify a format for this branch. '
1710
'See "help formats".',
1711
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1712
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1713
value_switches=True,
1714
title="Branch format",
1716
Option('append-revisions-only',
1717
help='Never change revnos or the existing log.'
1718
' Append revisions to it only.'),
1720
'Create a branch without a working tree.')
1722
def run(self, location=None, format=None, append_revisions_only=False,
1723
create_prefix=False, no_tree=False):
1015
1724
if format is None:
1016
format = get_format_type('default')
1725
format = bzrdir.format_registry.make_bzrdir('default')
1017
1726
if location is None:
1018
1727
location = u'.'
1020
# The path has to exist to initialize a
1021
# branch inside of it.
1022
# Just using os.mkdir, since I don't
1023
# believe that we want to create a bunch of
1024
# locations if the user supplies an extended path
1025
if not os.path.exists(location):
1028
existing_bzrdir = bzrdir.BzrDir.open(location)
1029
except NotBranchError:
1729
to_transport = transport.get_transport(location)
1731
# The path has to exist to initialize a
1732
# branch inside of it.
1733
# Just using os.mkdir, since I don't
1734
# believe that we want to create a bunch of
1735
# locations if the user supplies an extended path
1737
to_transport.ensure_base()
1738
except errors.NoSuchFile:
1739
if not create_prefix:
1740
raise errors.BzrCommandError("Parent directory of %s"
1742
"\nYou may supply --create-prefix to create all"
1743
" leading parent directories."
1745
to_transport.create_prefix()
1748
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1749
except errors.NotBranchError:
1030
1750
# really a NotBzrDir error...
1031
bzrdir.BzrDir.create_branch_convenience(location, format=format)
1751
create_branch = bzrdir.BzrDir.create_branch_convenience
1753
force_new_tree = False
1755
force_new_tree = None
1756
branch = create_branch(to_transport.base, format=format,
1757
possible_transports=[to_transport],
1758
force_new_tree=force_new_tree)
1759
a_bzrdir = branch.bzrdir
1033
if existing_bzrdir.has_branch():
1034
if existing_bzrdir.has_workingtree():
1035
raise errors.AlreadyBranchError(location)
1037
raise errors.BranchExistsWithoutWorkingTree(location)
1039
existing_bzrdir.create_branch()
1040
existing_bzrdir.create_workingtree()
1761
from bzrlib.transport.local import LocalTransport
1762
if a_bzrdir.has_branch():
1763
if (isinstance(to_transport, LocalTransport)
1764
and not a_bzrdir.has_workingtree()):
1765
raise errors.BranchExistsWithoutWorkingTree(location)
1766
raise errors.AlreadyBranchError(location)
1767
branch = a_bzrdir.create_branch()
1769
a_bzrdir.create_workingtree()
1770
if append_revisions_only:
1772
branch.set_append_revisions_only(True)
1773
except errors.UpgradeRequired:
1774
raise errors.BzrCommandError('This branch format cannot be set'
1775
' to append-revisions-only. Try --default.')
1777
from bzrlib.info import describe_layout, describe_format
1779
tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
1780
except (errors.NoWorkingTree, errors.NotLocalUrl):
1782
repository = branch.repository
1783
layout = describe_layout(repository, branch, tree).lower()
1784
format = describe_format(a_bzrdir, repository, branch, tree)
1785
self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1786
if repository.is_shared():
1787
#XXX: maybe this can be refactored into transport.path_or_url()
1788
url = repository.bzrdir.root_transport.external_url()
1790
url = urlutils.local_path_from_url(url)
1791
except errors.InvalidURL:
1793
self.outf.write("Using shared repository: %s\n" % url)
1043
1796
class cmd_init_repository(Command):
1044
"""Create a shared repository to hold branches.
1046
New branches created under the repository directory will store their revisions
1047
in the repository, not in the branch directory, if the branch format supports
1053
bzr checkout --lightweight repo/trunk trunk-checkout
1797
__doc__ = """Create a shared repository for branches to share storage space.
1799
New branches created under the repository directory will store their
1800
revisions in the repository, not in the branch directory. For branches
1801
with shared history, this reduces the amount of storage needed and
1802
speeds up the creation of new branches.
1804
If the --no-trees option is given then the branches in the repository
1805
will not have working trees by default. They will still exist as
1806
directories on disk, but they will not have separate copies of the
1807
files at a certain revision. This can be useful for repositories that
1808
store branches which are interacted with through checkouts or remote
1809
branches, such as on a server.
1812
Create a shared repository holding just branches::
1814
bzr init-repo --no-trees repo
1817
Make a lightweight checkout elsewhere::
1819
bzr checkout --lightweight repo/trunk trunk-checkout
1057
takes_args = ["location"]
1058
takes_options = [Option('format',
1059
help='Specify a format for this repository.'
1060
' Current formats are: default, knit,'
1061
' metaweave and weave. Default is knit;'
1062
' metaweave and weave are deprecated',
1063
type=get_format_type),
1065
help='Allows branches in repository to have'
1824
_see_also = ['init', 'branch', 'checkout', 'repositories']
1825
takes_args = ["location"]
1826
takes_options = [RegistryOption('format',
1827
help='Specify a format for this repository. See'
1828
' "bzr help formats" for details.',
1829
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1830
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1831
value_switches=True, title='Repository format'),
1833
help='Branches in the repository will default to'
1834
' not having a working tree.'),
1067
1836
aliases = ["init-repo"]
1068
def run(self, location, format=None, trees=False):
1069
from bzrlib.transport import get_transport
1838
def run(self, location, format=None, no_trees=False):
1070
1839
if format is None:
1071
format = get_format_type('default')
1072
transport = get_transport(location)
1073
if not transport.has('.'):
1075
newdir = format.initialize_on_transport(transport)
1840
format = bzrdir.format_registry.make_bzrdir('default')
1842
if location is None:
1845
to_transport = transport.get_transport(location)
1846
to_transport.ensure_base()
1848
newdir = format.initialize_on_transport(to_transport)
1076
1849
repo = newdir.create_repository(shared=True)
1077
repo.set_make_working_trees(trees)
1850
repo.set_make_working_trees(not no_trees)
1852
from bzrlib.info import show_bzrdir_info
1853
show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1080
1856
class cmd_diff(Command):
1081
"""Show differences in working tree.
1083
If files are listed, only the changes in those files are listed.
1084
Otherwise, all changes for the tree are listed.
1857
__doc__ = """Show differences in the working tree, between revisions or branches.
1859
If no arguments are given, all changes for the current tree are listed.
1860
If files are given, only the changes in those files are listed.
1861
Remote and multiple branches can be compared by using the --old and
1862
--new options. If not provided, the default for both is derived from
1863
the first argument, if any, or the current tree if no arguments are
1086
1866
"bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1087
1867
produces patches suitable for "patch -p1".
1093
bzr diff --diff-prefix old/:new/
1094
bzr diff bzr.mine bzr.dev
1869
Note that when using the -r argument with a range of revisions, the
1870
differences are computed between the two specified revisions. That
1871
is, the command does not show the changes introduced by the first
1872
revision in the range. This differs from the interpretation of
1873
revision ranges used by "bzr log" which includes the first revision
1878
2 - unrepresentable changes
1883
Shows the difference in the working tree versus the last commit::
1887
Difference between the working tree and revision 1::
1891
Difference between revision 3 and revision 1::
1895
Difference between revision 3 and revision 1 for branch xxx::
1899
The changes introduced by revision 2 (equivalent to -r1..2)::
1903
To see the changes introduced by revision X::
1907
Note that in the case of a merge, the -c option shows the changes
1908
compared to the left hand parent. To see the changes against
1909
another parent, use::
1911
bzr diff -r<chosen_parent>..X
1913
The changes between the current revision and the previous revision
1914
(equivalent to -c-1 and -r-2..-1)
1918
Show just the differences for file NEWS::
1922
Show the differences in working tree xxx for file NEWS::
1926
Show the differences from branch xxx to this working tree:
1930
Show the differences between two branches for file NEWS::
1932
bzr diff --old xxx --new yyy NEWS
1934
Same as 'bzr diff' but prefix paths with old/ and new/::
1936
bzr diff --prefix old/:new/
1938
Show the differences using a custom diff program with options::
1940
bzr diff --using /usr/bin/diff --diff-options -wu
1097
# TODO: Option to use external diff command; could be GNU diff, wdiff,
1098
# or a graphical diff.
1100
# TODO: Python difflib is not exactly the same as unidiff; should
1101
# either fix it up or prefer to use an external diff.
1103
# TODO: Selected-file diff is inefficient and doesn't show you
1106
# TODO: This probably handles non-Unix newlines poorly.
1942
_see_also = ['status']
1108
1943
takes_args = ['file*']
1109
takes_options = ['revision', 'diff-options', 'prefix']
1945
Option('diff-options', type=str,
1946
help='Pass these options to the external diff program.'),
1947
Option('prefix', type=str,
1949
help='Set prefixes added to old and new filenames, as '
1950
'two values separated by a colon. (eg "old/:new/").'),
1952
help='Branch/tree to compare from.',
1956
help='Branch/tree to compare to.',
1962
help='Use this command to compare files.',
1965
RegistryOption('format',
1966
help='Diff format to use.',
1967
lazy_registry=('bzrlib.diff', 'format_registry'),
1968
value_switches=False, title='Diff format'),
1110
1970
aliases = ['di', 'dif']
1111
1971
encoding_type = 'exact'
1113
1973
@display_command
1114
1974
def run(self, revision=None, file_list=None, diff_options=None,
1116
from bzrlib.diff import diff_cmd_helper, show_diff_trees
1975
prefix=None, old=None, new=None, using=None, format=None):
1976
from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
1118
1979
if (prefix is None) or (prefix == '0'):
1119
1980
# diff -p0 format
1238
2104
self.outf.write(tree.basedir + '\n')
2107
def _parse_limit(limitstring):
2109
return int(limitstring)
2111
msg = "The limit argument must be an integer."
2112
raise errors.BzrCommandError(msg)
2115
def _parse_levels(s):
2119
msg = "The levels argument must be an integer."
2120
raise errors.BzrCommandError(msg)
1241
2123
class cmd_log(Command):
1242
"""Show log of a branch, file, or directory.
1244
By default show the log of the branch containing the working directory.
1246
To request a range of logs, you can use the command -r begin..end
1247
-r revision requests a specific revision, -r ..end or -r begin.. are
1253
bzr log -r -10.. http://server/branch
2124
__doc__ = """Show historical log for a branch or subset of a branch.
2126
log is bzr's default tool for exploring the history of a branch.
2127
The branch to use is taken from the first parameter. If no parameters
2128
are given, the branch containing the working directory is logged.
2129
Here are some simple examples::
2131
bzr log log the current branch
2132
bzr log foo.py log a file in its branch
2133
bzr log http://server/branch log a branch on a server
2135
The filtering, ordering and information shown for each revision can
2136
be controlled as explained below. By default, all revisions are
2137
shown sorted (topologically) so that newer revisions appear before
2138
older ones and descendants always appear before ancestors. If displayed,
2139
merged revisions are shown indented under the revision in which they
2144
The log format controls how information about each revision is
2145
displayed. The standard log formats are called ``long``, ``short``
2146
and ``line``. The default is long. See ``bzr help log-formats``
2147
for more details on log formats.
2149
The following options can be used to control what information is
2152
-l N display a maximum of N revisions
2153
-n N display N levels of revisions (0 for all, 1 for collapsed)
2154
-v display a status summary (delta) for each revision
2155
-p display a diff (patch) for each revision
2156
--show-ids display revision-ids (and file-ids), not just revnos
2158
Note that the default number of levels to display is a function of the
2159
log format. If the -n option is not used, the standard log formats show
2160
just the top level (mainline).
2162
Status summaries are shown using status flags like A, M, etc. To see
2163
the changes explained using words like ``added`` and ``modified``
2164
instead, use the -vv option.
2168
To display revisions from oldest to newest, use the --forward option.
2169
In most cases, using this option will have little impact on the total
2170
time taken to produce a log, though --forward does not incrementally
2171
display revisions like --reverse does when it can.
2173
:Revision filtering:
2175
The -r option can be used to specify what revision or range of revisions
2176
to filter against. The various forms are shown below::
2178
-rX display revision X
2179
-rX.. display revision X and later
2180
-r..Y display up to and including revision Y
2181
-rX..Y display from X to Y inclusive
2183
See ``bzr help revisionspec`` for details on how to specify X and Y.
2184
Some common examples are given below::
2186
-r-1 show just the tip
2187
-r-10.. show the last 10 mainline revisions
2188
-rsubmit:.. show what's new on this branch
2189
-rancestor:path.. show changes since the common ancestor of this
2190
branch and the one at location path
2191
-rdate:yesterday.. show changes since yesterday
2193
When logging a range of revisions using -rX..Y, log starts at
2194
revision Y and searches back in history through the primary
2195
("left-hand") parents until it finds X. When logging just the
2196
top level (using -n1), an error is reported if X is not found
2197
along the way. If multi-level logging is used (-n0), X may be
2198
a nested merge revision and the log will be truncated accordingly.
2202
If parameters are given and the first one is not a branch, the log
2203
will be filtered to show only those revisions that changed the
2204
nominated files or directories.
2206
Filenames are interpreted within their historical context. To log a
2207
deleted file, specify a revision range so that the file existed at
2208
the end or start of the range.
2210
Historical context is also important when interpreting pathnames of
2211
renamed files/directories. Consider the following example:
2213
* revision 1: add tutorial.txt
2214
* revision 2: modify tutorial.txt
2215
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2219
* ``bzr log guide.txt`` will log the file added in revision 1
2221
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2223
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2224
the original file in revision 2.
2226
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2227
was no file called guide.txt in revision 2.
2229
Renames are always followed by log. By design, there is no need to
2230
explicitly ask for this (and no way to stop logging a file back
2231
until it was last renamed).
2235
The --message option can be used for finding revisions that match a
2236
regular expression in a commit message.
2240
GUI tools and IDEs are often better at exploring history than command
2241
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2242
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2243
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2244
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2246
You may find it useful to add the aliases below to ``bazaar.conf``::
2250
top = log -l10 --line
2253
``bzr tip`` will then show the latest revision while ``bzr top``
2254
will show the last 10 mainline revisions. To see the details of a
2255
particular revision X, ``bzr show -rX``.
2257
If you are interested in looking deeper into a particular merge X,
2258
use ``bzr log -n0 -rX``.
2260
``bzr log -v`` on a branch with lots of history is currently
2261
very slow. A fix for this issue is currently under development.
2262
With or without that fix, it is recommended that a revision range
2263
be given when using the -v option.
2265
bzr has a generic full-text matching plugin, bzr-search, that can be
2266
used to find revisions matching user names, commit messages, etc.
2267
Among other features, this plugin can find all revisions containing
2268
a list of words but not others.
2270
When exploring non-mainline history on large projects with deep
2271
history, the performance of log can be greatly improved by installing
2272
the historycache plugin. This plugin buffers historical information
2273
trading disk space for faster speed.
1256
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1258
takes_args = ['location?']
1259
takes_options = [Option('forward',
1260
help='show from oldest to newest'),
1263
help='show files changed in each revision'),
1264
'show-ids', 'revision',
1268
help='show revisions whose message matches this regexp',
2275
takes_args = ['file*']
2276
_see_also = ['log-formats', 'revisionspec']
2279
help='Show from oldest to newest.'),
2281
custom_help('verbose',
2282
help='Show files changed in each revision.'),
2286
type=bzrlib.option._parse_revision_str,
2288
help='Show just the specified revision.'
2289
' See also "help revisionspec".'),
2291
RegistryOption('authors',
2292
'What names to list as authors - first, all or committer.',
2294
lazy_registry=('bzrlib.log', 'author_list_registry'),
2298
help='Number of levels to display - 0 for all, 1 for flat.',
2300
type=_parse_levels),
2303
help='Show revisions whose message matches this '
2304
'regular expression.',
2308
help='Limit the output to the first N revisions.',
2313
help='Show changes made in each revision as a patch.'),
2314
Option('include-merges',
2315
help='Show merged revisions like --levels 0 does.'),
2316
Option('exclude-common-ancestry',
2317
help='Display only the revisions that are not part'
2318
' of both ancestries (require -rX..Y)'
1272
2321
encoding_type = 'replace'
1274
2323
@display_command
1275
def run(self, location=None, timezone='original',
2324
def run(self, file_list=None, timezone='original',
1277
2326
show_ids=False,
1280
2330
log_format=None,
1285
from bzrlib.log import log_formatter, show_log
1286
assert message is None or isinstance(message, basestring), \
1287
"invalid message argument %r" % message
2335
include_merges=False,
2337
exclude_common_ancestry=False,
2339
from bzrlib.log import (
2341
make_log_request_dict,
2342
_get_info_for_log_files,
1288
2344
direction = (forward and 'forward') or 'reverse'
1293
# find the file id to log:
1295
dir, fp = bzrdir.BzrDir.open_containing(location)
1296
b = dir.open_branch()
1300
inv = dir.open_workingtree().inventory
1301
except (errors.NotBranchError, errors.NotLocalUrl):
1302
# either no tree, or is remote.
1303
inv = b.basis_tree().inventory
1304
file_id = inv.path2id(fp)
1307
# FIXME ? log the current subdir only RBC 20060203
1308
dir, relpath = bzrdir.BzrDir.open_containing('.')
1309
b = dir.open_branch()
1311
if revision is None:
1314
elif len(revision) == 1:
1315
rev1 = rev2 = revision[0].in_history(b).revno
1316
elif len(revision) == 2:
1317
if revision[0].spec is None:
1318
# missing begin-range means first revision
1321
rev1 = revision[0].in_history(b).revno
1323
if revision[1].spec is None:
1324
# missing end-range means last known revision
1327
rev2 = revision[1].in_history(b).revno
1329
raise BzrCommandError('bzr log --revision takes one or two values.')
1331
# By this point, the revision numbers are converted to the +ve
1332
# form if they were supplied in the -ve form, so we can do
1333
# this comparison in relative safety
1335
(rev2, rev1) = (rev1, rev2)
1337
if (log_format == None):
1338
default = b.get_config().log_format()
1339
log_format = get_log_format(long=long, short=short, line=line,
1341
lf = log_formatter(log_format,
1344
show_timezone=timezone)
1350
direction=direction,
1351
start_revision=rev1,
2345
if (exclude_common_ancestry
2346
and (revision is None or len(revision) != 2)):
2347
raise errors.BzrCommandError(
2348
'--exclude-common-ancestry requires -r with two revisions')
2353
raise errors.BzrCommandError(
2354
'--levels and --include-merges are mutually exclusive')
2356
if change is not None:
2358
raise errors.RangeInChangeOption()
2359
if revision is not None:
2360
raise errors.BzrCommandError(
2361
'--revision and --change are mutually exclusive')
2366
filter_by_dir = False
2368
# find the file ids to log and check for directory filtering
2369
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2370
revision, file_list, self.add_cleanup)
2371
for relpath, file_id, kind in file_info_list:
2373
raise errors.BzrCommandError(
2374
"Path unknown at end or start of revision range: %s" %
2376
# If the relpath is the top of the tree, we log everything
2381
file_ids.append(file_id)
2382
filter_by_dir = filter_by_dir or (
2383
kind in ['directory', 'tree-reference'])
2386
# FIXME ? log the current subdir only RBC 20060203
2387
if revision is not None \
2388
and len(revision) > 0 and revision[0].get_branch():
2389
location = revision[0].get_branch()
2392
dir, relpath = bzrdir.BzrDir.open_containing(location)
2393
b = dir.open_branch()
2394
self.add_cleanup(b.lock_read().unlock)
2395
rev1, rev2 = _get_revision_range(revision, b, self.name())
2397
# Decide on the type of delta & diff filtering to use
2398
# TODO: add an --all-files option to make this configurable & consistent
2406
diff_type = 'partial'
2410
# Build the log formatter
2411
if log_format is None:
2412
log_format = log.log_formatter_registry.get_default(b)
2413
# Make a non-encoding output to include the diffs - bug 328007
2414
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2415
lf = log_format(show_ids=show_ids, to_file=self.outf,
2416
to_exact_file=unencoded_output,
2417
show_timezone=timezone,
2418
delta_format=get_verbosity_level(),
2420
show_advice=levels is None,
2421
author_list_handler=authors)
2423
# Choose the algorithm for doing the logging. It's annoying
2424
# having multiple code paths like this but necessary until
2425
# the underlying repository format is faster at generating
2426
# deltas or can provide everything we need from the indices.
2427
# The default algorithm - match-using-deltas - works for
2428
# multiple files and directories and is faster for small
2429
# amounts of history (200 revisions say). However, it's too
2430
# slow for logging a single file in a repository with deep
2431
# history, i.e. > 10K revisions. In the spirit of "do no
2432
# evil when adding features", we continue to use the
2433
# original algorithm - per-file-graph - for the "single
2434
# file that isn't a directory without showing a delta" case.
2435
partial_history = revision and b.repository._format.supports_chks
2436
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2437
or delta_type or partial_history)
2439
# Build the LogRequest and execute it
2440
if len(file_ids) == 0:
2442
rqst = make_log_request_dict(
2443
direction=direction, specific_fileids=file_ids,
2444
start_revision=rev1, end_revision=rev2, limit=limit,
2445
message_search=message, delta_type=delta_type,
2446
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2447
exclude_common_ancestry=exclude_common_ancestry,
2449
Logger(b, rqst).show(lf)
2452
def _get_revision_range(revisionspec_list, branch, command_name):
2453
"""Take the input of a revision option and turn it into a revision range.
2455
It returns RevisionInfo objects which can be used to obtain the rev_id's
2456
of the desired revisions. It does some user input validations.
2458
if revisionspec_list is None:
2461
elif len(revisionspec_list) == 1:
2462
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2463
elif len(revisionspec_list) == 2:
2464
start_spec = revisionspec_list[0]
2465
end_spec = revisionspec_list[1]
2466
if end_spec.get_branch() != start_spec.get_branch():
2467
# b is taken from revision[0].get_branch(), and
2468
# show_log will use its revision_history. Having
2469
# different branches will lead to weird behaviors.
2470
raise errors.BzrCommandError(
2471
"bzr %s doesn't accept two revisions in different"
2472
" branches." % command_name)
2473
if start_spec.spec is None:
2474
# Avoid loading all the history.
2475
rev1 = RevisionInfo(branch, None, None)
2477
rev1 = start_spec.in_history(branch)
2478
# Avoid loading all of history when we know a missing
2479
# end of range means the last revision ...
2480
if end_spec.spec is None:
2481
last_revno, last_revision_id = branch.last_revision_info()
2482
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2484
rev2 = end_spec.in_history(branch)
2486
raise errors.BzrCommandError(
2487
'bzr %s --revision takes one or two values.' % command_name)
2491
def _revision_range_to_revid_range(revision_range):
2494
if revision_range[0] is not None:
2495
rev_id1 = revision_range[0].rev_id
2496
if revision_range[1] is not None:
2497
rev_id2 = revision_range[1].rev_id
2498
return rev_id1, rev_id2
1356
2500
def get_log_format(long=False, short=False, line=False, default='long'):
1357
2501
log_format = default
1376
2520
@display_command
1377
2521
def run(self, filename):
1378
2522
tree, relpath = WorkingTree.open_containing(filename)
2523
file_id = tree.path2id(relpath)
1379
2524
b = tree.branch
1380
inv = tree.read_working_inventory()
1381
file_id = inv.path2id(relpath)
1382
for revno, revision_id, what in log.find_touching_revisions(b, file_id):
2525
self.add_cleanup(b.lock_read().unlock)
2526
touching_revs = log.find_touching_revisions(b, file_id)
2527
for revno, revision_id, what in touching_revs:
1383
2528
self.outf.write("%6d %s\n" % (revno, what))
1386
2531
class cmd_ls(Command):
1387
"""List files in a tree.
2532
__doc__ = """List files in a tree.
1389
# TODO: Take a revision or remote path and list that tree instead.
1391
takes_options = ['verbose', 'revision',
1392
Option('non-recursive',
1393
help='don\'t recurse into sub-directories'),
1395
help='Print all paths from the root of the branch.'),
1396
Option('unknown', help='Print unknown files'),
1397
Option('versioned', help='Print versioned files'),
1398
Option('ignored', help='Print ignored files'),
1400
Option('null', help='Null separate the files'),
2535
_see_also = ['status', 'cat']
2536
takes_args = ['path?']
2540
Option('recursive', short_name='R',
2541
help='Recurse into subdirectories.'),
2543
help='Print paths relative to the root of the branch.'),
2544
Option('unknown', short_name='u',
2545
help='Print unknown files.'),
2546
Option('versioned', help='Print versioned files.',
2548
Option('ignored', short_name='i',
2549
help='Print ignored files.'),
2550
Option('kind', short_name='k',
2551
help='List entries of a particular kind: file, directory, symlink.',
1402
2557
@display_command
1403
def run(self, revision=None, verbose=False,
1404
non_recursive=False, from_root=False,
2558
def run(self, revision=None, verbose=False,
2559
recursive=False, from_root=False,
1405
2560
unknown=False, versioned=False, ignored=False,
2561
null=False, kind=None, show_ids=False, path=None, directory=None):
2563
if kind and kind not in ('file', 'directory', 'symlink'):
2564
raise errors.BzrCommandError('invalid kind specified')
1408
2566
if verbose and null:
1409
raise BzrCommandError('Cannot set both --verbose and --null')
2567
raise errors.BzrCommandError('Cannot set both --verbose and --null')
1410
2568
all = not (unknown or versioned or ignored)
1412
2570
selection = {'I':ignored, '?':unknown, 'V':versioned}
1414
tree, relpath = WorkingTree.open_containing(u'.')
2576
raise errors.BzrCommandError('cannot specify both --from-root'
2579
tree, branch, relpath = \
2580
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2582
# Calculate the prefix to use
1419
if revision is not None:
1420
tree = tree.branch.repository.revision_tree(
1421
revision[0].in_history(tree.branch).rev_id)
1423
for fp, fc, kind, fid, entry in tree.list_files():
1424
if fp.startswith(relpath):
1425
fp = fp[len(relpath):]
1426
if non_recursive and '/' in fp:
1428
if not all and not selection[fc]:
1431
kindch = entry.kind_character()
1432
self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1434
self.outf.write(fp + '\0')
2586
prefix = relpath + '/'
2587
elif fs_path != '.' and not fs_path.endswith('/'):
2588
prefix = fs_path + '/'
2590
if revision is not None or tree is None:
2591
tree = _get_one_revision_tree('ls', revision, branch=branch)
2594
if isinstance(tree, WorkingTree) and tree.supports_views():
2595
view_files = tree.views.lookup_view()
2598
view_str = views.view_display_str(view_files)
2599
note("Ignoring files outside view. View is %s" % view_str)
2601
self.add_cleanup(tree.lock_read().unlock)
2602
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2603
from_dir=relpath, recursive=recursive):
2604
# Apply additional masking
2605
if not all and not selection[fc]:
2607
if kind is not None and fkind != kind:
2612
fullpath = osutils.pathjoin(relpath, fp)
2615
views.check_path_in_view(tree, fullpath)
2616
except errors.FileOutsideView:
2621
fp = osutils.pathjoin(prefix, fp)
2622
kindch = entry.kind_character()
2623
outstring = fp + kindch
2624
ui.ui_factory.clear_term()
2626
outstring = '%-8s %s' % (fc, outstring)
2627
if show_ids and fid is not None:
2628
outstring = "%-50s %s" % (outstring, fid)
2629
self.outf.write(outstring + '\n')
2631
self.outf.write(fp + '\0')
2634
self.outf.write(fid)
2635
self.outf.write('\0')
2643
self.outf.write('%-50s %s\n' % (outstring, my_id))
1437
self.outf.write(fp + '\n')
2645
self.outf.write(outstring + '\n')
1440
2648
class cmd_unknowns(Command):
1441
"""List unknown files."""
2649
__doc__ = """List unknown files.
2654
takes_options = ['directory']
1442
2656
@display_command
1444
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2657
def run(self, directory=u'.'):
2658
for f in WorkingTree.open_containing(directory)[0].unknowns():
1445
2659
self.outf.write(osutils.quotefn(f) + '\n')
1448
2662
class cmd_ignore(Command):
1449
"""Ignore a command or pattern.
2663
__doc__ = """Ignore specified files or patterns.
2665
See ``bzr help patterns`` for details on the syntax of patterns.
2667
If a .bzrignore file does not exist, the ignore command
2668
will create one and add the specified files or patterns to the newly
2669
created file. The ignore command will also automatically add the
2670
.bzrignore file to be versioned. Creating a .bzrignore file without
2671
the use of the ignore command will require an explicit add command.
1451
2673
To remove patterns from the ignore list, edit the .bzrignore file.
1453
If the pattern contains a slash, it is compared to the whole path
1454
from the branch root. Otherwise, it is compared to only the last
1455
component of the path. To match a file only in the root directory,
1458
Ignore patterns are case-insensitive on case-insensitive systems.
1460
Note: wildcards must be quoted from the shell on Unix.
1463
bzr ignore ./Makefile
1464
bzr ignore '*.class'
2674
After adding, editing or deleting that file either indirectly by
2675
using this command or directly by using an editor, be sure to commit
2678
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2679
the global ignore file can be found in the application data directory as
2680
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2681
Global ignores are not touched by this command. The global ignore file
2682
can be edited directly using an editor.
2684
Patterns prefixed with '!' are exceptions to ignore patterns and take
2685
precedence over regular ignores. Such exceptions are used to specify
2686
files that should be versioned which would otherwise be ignored.
2688
Patterns prefixed with '!!' act as regular ignore patterns, but have
2689
precedence over the '!' exception patterns.
2693
* Ignore patterns containing shell wildcards must be quoted from
2696
* Ignore patterns starting with "#" act as comments in the ignore file.
2697
To ignore patterns that begin with that character, use the "RE:" prefix.
2700
Ignore the top level Makefile::
2702
bzr ignore ./Makefile
2704
Ignore .class files in all directories...::
2706
bzr ignore "*.class"
2708
...but do not ignore "special.class"::
2710
bzr ignore "!special.class"
2712
Ignore files whose name begins with the "#" character::
2716
Ignore .o files under the lib directory::
2718
bzr ignore "lib/**/*.o"
2720
Ignore .o files under the lib directory::
2722
bzr ignore "RE:lib/.*\.o"
2724
Ignore everything but the "debian" toplevel directory::
2726
bzr ignore "RE:(?!debian/).*"
2728
Ignore everything except the "local" toplevel directory,
2729
but always ignore "*~" autosave files, even under local/::
2732
bzr ignore "!./local"
1466
# TODO: Complain if the filename is absolute
1467
takes_args = ['name_pattern?']
1469
Option('old-default-rules',
1470
help='Out the ignore rules bzr < 0.9 always used.')
1473
def run(self, name_pattern=None, old_default_rules=None):
1474
from bzrlib.atomicfile import AtomicFile
1475
if old_default_rules is not None:
1476
# dump the rules and exit
1477
for pattern in bzrlib.DEFAULT_IGNORE:
2736
_see_also = ['status', 'ignored', 'patterns']
2737
takes_args = ['name_pattern*']
2738
takes_options = ['directory',
2739
Option('default-rules',
2740
help='Display the default ignore rules that bzr uses.')
2743
def run(self, name_pattern_list=None, default_rules=None,
2745
from bzrlib import ignores
2746
if default_rules is not None:
2747
# dump the default rules and exit
2748
for pattern in ignores.USER_DEFAULTS:
2749
self.outf.write("%s\n" % pattern)
1480
if name_pattern is None:
1481
raise BzrCommandError("ignore requires a NAME_PATTERN")
1482
tree, relpath = WorkingTree.open_containing(u'.')
1483
ifn = tree.abspath('.bzrignore')
1484
if os.path.exists(ifn):
1487
igns = f.read().decode('utf-8')
1493
# TODO: If the file already uses crlf-style termination, maybe
1494
# we should use that for the newly added lines?
1496
if igns and igns[-1] != '\n':
1498
igns += name_pattern + '\n'
1500
f = AtomicFile(ifn, 'wt')
1502
f.write(igns.encode('utf-8'))
1507
inv = tree.inventory
1508
if inv.path2id('.bzrignore'):
1509
mutter('.bzrignore is already versioned')
1511
mutter('need to make new .bzrignore file versioned')
1512
tree.add(['.bzrignore'])
2751
if not name_pattern_list:
2752
raise errors.BzrCommandError("ignore requires at least one "
2753
"NAME_PATTERN or --default-rules.")
2754
name_pattern_list = [globbing.normalize_pattern(p)
2755
for p in name_pattern_list]
2757
for p in name_pattern_list:
2758
if not globbing.Globster.is_pattern_valid(p):
2759
bad_patterns += ('\n %s' % p)
2761
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2762
ui.ui_factory.show_error(msg)
2763
raise errors.InvalidPattern('')
2764
for name_pattern in name_pattern_list:
2765
if (name_pattern[0] == '/' or
2766
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2767
raise errors.BzrCommandError(
2768
"NAME_PATTERN should not be an absolute path")
2769
tree, relpath = WorkingTree.open_containing(directory)
2770
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2771
ignored = globbing.Globster(name_pattern_list)
2773
self.add_cleanup(tree.lock_read().unlock)
2774
for entry in tree.list_files():
2778
if ignored.match(filename):
2779
matches.append(filename)
2780
if len(matches) > 0:
2781
self.outf.write("Warning: the following files are version controlled and"
2782
" match your ignore pattern:\n%s"
2783
"\nThese files will continue to be version controlled"
2784
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1515
2787
class cmd_ignored(Command):
1516
"""List ignored files and the patterns that matched them.
1518
See also: bzr ignore"""
2788
__doc__ = """List ignored files and the patterns that matched them.
2790
List all the ignored files and the ignore pattern that caused the file to
2793
Alternatively, to list just the files::
2798
encoding_type = 'replace'
2799
_see_also = ['ignore', 'ls']
2800
takes_options = ['directory']
1519
2802
@display_command
1521
tree = WorkingTree.open_containing(u'.')[0]
2803
def run(self, directory=u'.'):
2804
tree = WorkingTree.open_containing(directory)[0]
2805
self.add_cleanup(tree.lock_read().unlock)
1522
2806
for path, file_class, kind, file_id, entry in tree.list_files():
1523
2807
if file_class != 'I':
1525
2809
## XXX: Slightly inefficient since this was already calculated
1526
2810
pat = tree.is_ignored(path)
1527
print '%-50s %s' % (path, pat)
2811
self.outf.write('%-50s %s\n' % (path, pat))
1530
2814
class cmd_lookup_revision(Command):
1531
"""Lookup the revision-id from a revision-number
2815
__doc__ = """Lookup the revision-id from a revision-number
1534
2818
bzr lookup-revision 33
1537
2821
takes_args = ['revno']
2822
takes_options = ['directory']
1539
2824
@display_command
1540
def run(self, revno):
2825
def run(self, revno, directory=u'.'):
1542
2827
revno = int(revno)
1543
2828
except ValueError:
1544
raise BzrCommandError("not a valid revision-number: %r" % revno)
1546
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2829
raise errors.BzrCommandError("not a valid revision-number: %r"
2831
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2832
self.outf.write("%s\n" % revid)
1549
2835
class cmd_export(Command):
1550
"""Export past revision to destination directory.
2836
__doc__ = """Export current or past revision to a destination directory or archive.
1552
2838
If no revision is specified this exports the last committed revision.
1555
2841
given, try to find the format with the extension. If no extension
1556
2842
is found exports to a directory (equivalent to --format=dir).
1558
Root may be the top directory for tar, tgz and tbz2 formats. If none
1559
is given, the top directory will be the root name of the file.
1561
Note: export of tree with non-ascii filenames to zip is not supported.
1563
Supported formats Autodetected by extension
1564
----------------- -------------------------
2844
If root is supplied, it will be used as the root directory inside
2845
container formats (tar, zip, etc). If it is not supplied it will default
2846
to the exported filename. The root option has no effect for 'dir' format.
2848
If branch is omitted then the branch containing the current working
2849
directory will be used.
2851
Note: Export of tree with non-ASCII filenames to zip is not supported.
2853
================= =========================
2854
Supported formats Autodetected by extension
2855
================= =========================
1567
2858
tbz2 .tar.bz2, .tbz2
1568
2859
tgz .tar.gz, .tgz
2861
================= =========================
1571
takes_args = ['dest']
1572
takes_options = ['revision', 'format', 'root']
1573
def run(self, dest, revision=None, format=None, root=None):
2863
takes_args = ['dest', 'branch_or_subdir?']
2864
takes_options = ['directory',
2866
help="Type of file to export to.",
2869
Option('filters', help='Apply content filters to export the '
2870
'convenient form.'),
2873
help="Name of the root directory inside the exported file."),
2874
Option('per-file-timestamps',
2875
help='Set modification time of files to that of the last '
2876
'revision in which it was changed.'),
2878
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2879
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
1574
2880
from bzrlib.export import export
1575
tree = WorkingTree.open_containing(u'.')[0]
1577
if revision is None:
1578
# should be tree.last_revision FIXME
1579
rev_id = b.last_revision()
2882
if branch_or_subdir is None:
2883
tree = WorkingTree.open_containing(directory)[0]
1581
if len(revision) != 1:
1582
raise BzrError('bzr export --revision takes exactly 1 argument')
1583
rev_id = revision[0].in_history(b).rev_id
1584
t = b.repository.revision_tree(rev_id)
2887
b, subdir = Branch.open_containing(branch_or_subdir)
2890
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
1586
export(t, dest, format, root)
2892
export(rev_tree, dest, format, root, subdir, filtered=filters,
2893
per_file_timestamps=per_file_timestamps)
1587
2894
except errors.NoSuchExportFormat, e:
1588
raise BzrCommandError('Unsupported export format: %s' % e.format)
2895
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1591
2898
class cmd_cat(Command):
1592
"""Write a file's text from a previous revision."""
1594
takes_options = ['revision']
2899
__doc__ = """Write the contents of a file as of a given revision to standard output.
2901
If no revision is nominated, the last revision is used.
2903
Note: Take care to redirect standard output when using this command on a
2908
takes_options = ['directory',
2909
Option('name-from-revision', help='The path name in the old tree.'),
2910
Option('filters', help='Apply content filters to display the '
2911
'convenience form.'),
1595
2914
takes_args = ['filename']
2915
encoding_type = 'exact'
1597
2917
@display_command
1598
def run(self, filename, revision=None):
2918
def run(self, filename, revision=None, name_from_revision=False,
2919
filters=False, directory=None):
1599
2920
if revision is not None and len(revision) != 1:
1600
raise BzrCommandError("bzr cat --revision takes exactly one number")
1603
tree, relpath = WorkingTree.open_containing(filename)
1605
except NotBranchError:
2921
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2922
" one revision specifier")
2923
tree, branch, relpath = \
2924
_open_directory_or_containing_tree_or_branch(filename, directory)
2925
self.add_cleanup(branch.lock_read().unlock)
2926
return self._run(tree, branch, relpath, filename, revision,
2927
name_from_revision, filters)
2929
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
1608
2931
if tree is None:
1609
b, relpath = Branch.open_containing(filename)
1610
if revision is None:
1611
revision_id = b.last_revision()
1613
revision_id = revision[0].in_history(b).rev_id
1614
b.print_file(relpath, revision_id)
2932
tree = b.basis_tree()
2933
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2934
self.add_cleanup(rev_tree.lock_read().unlock)
2936
old_file_id = rev_tree.path2id(relpath)
2938
if name_from_revision:
2939
# Try in revision if requested
2940
if old_file_id is None:
2941
raise errors.BzrCommandError(
2942
"%r is not present in revision %s" % (
2943
filename, rev_tree.get_revision_id()))
2945
content = rev_tree.get_file_text(old_file_id)
2947
cur_file_id = tree.path2id(relpath)
2949
if cur_file_id is not None:
2950
# Then try with the actual file id
2952
content = rev_tree.get_file_text(cur_file_id)
2954
except errors.NoSuchId:
2955
# The actual file id didn't exist at that time
2957
if not found and old_file_id is not None:
2958
# Finally try with the old file id
2959
content = rev_tree.get_file_text(old_file_id)
2962
# Can't be found anywhere
2963
raise errors.BzrCommandError(
2964
"%r is not present in revision %s" % (
2965
filename, rev_tree.get_revision_id()))
2967
from bzrlib.filters import (
2968
ContentFilterContext,
2969
filtered_output_bytes,
2971
filters = rev_tree._content_filter_stack(relpath)
2972
chunks = content.splitlines(True)
2973
content = filtered_output_bytes(chunks, filters,
2974
ContentFilterContext(relpath, rev_tree))
2976
self.outf.writelines(content)
2979
self.outf.write(content)
1617
2982
class cmd_local_time_offset(Command):
1618
"""Show the offset in seconds from GMT to local time."""
2983
__doc__ = """Show the offset in seconds from GMT to local time."""
1620
2985
@display_command
1622
print osutils.local_time_offset()
2987
self.outf.write("%s\n" % osutils.local_time_offset())
1626
2991
class cmd_commit(Command):
1627
"""Commit changes into a new revision.
1629
If no arguments are given, the entire tree is committed.
1631
If selected files are specified, only changes to those files are
1632
committed. If a directory is specified then the directory and everything
1633
within it is committed.
1635
A selected-file commit may fail in some cases where the committed
1636
tree would be invalid, such as trying to commit a file in a
1637
newly-added directory that is not itself committed.
2992
__doc__ = """Commit changes into a new revision.
2994
An explanatory message needs to be given for each commit. This is
2995
often done by using the --message option (getting the message from the
2996
command line) or by using the --file option (getting the message from
2997
a file). If neither of these options is given, an editor is opened for
2998
the user to enter the message. To see the changed files in the
2999
boilerplate text loaded into the editor, use the --show-diff option.
3001
By default, the entire tree is committed and the person doing the
3002
commit is assumed to be the author. These defaults can be overridden
3007
If selected files are specified, only changes to those files are
3008
committed. If a directory is specified then the directory and
3009
everything within it is committed.
3011
When excludes are given, they take precedence over selected files.
3012
For example, to commit only changes within foo, but not changes
3015
bzr commit foo -x foo/bar
3017
A selective commit after a merge is not yet supported.
3021
If the author of the change is not the same person as the committer,
3022
you can specify the author's name using the --author option. The
3023
name should be in the same format as a committer-id, e.g.
3024
"John Doe <jdoe@example.com>". If there is more than one author of
3025
the change you can specify the option multiple times, once for each
3030
A common mistake is to forget to add a new file or directory before
3031
running the commit command. The --strict option checks for unknown
3032
files and aborts the commit if any are found. More advanced pre-commit
3033
checks can be implemented by defining hooks. See ``bzr help hooks``
3038
If you accidentially commit the wrong changes or make a spelling
3039
mistake in the commit message say, you can use the uncommit command
3040
to undo it. See ``bzr help uncommit`` for details.
3042
Hooks can also be configured to run after a commit. This allows you
3043
to trigger updates to external systems like bug trackers. The --fixes
3044
option can be used to record the association between a revision and
3045
one or more bugs. See ``bzr help bugs`` for details.
3047
A selective commit may fail in some cases where the committed
3048
tree would be invalid. Consider::
3053
bzr commit foo -m "committing foo"
3054
bzr mv foo/bar foo/baz
3057
bzr commit foo/bar -m "committing bar but not baz"
3059
In the example above, the last commit will fail by design. This gives
3060
the user the opportunity to decide whether they want to commit the
3061
rename at the same time, separately first, or not at all. (As a general
3062
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
1639
3064
# TODO: Run hooks on tree to-be-committed, and after commit.
1646
3071
# XXX: verbose currently does nothing
3073
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
1648
3074
takes_args = ['selected*']
1649
takes_options = ['message', 'verbose',
1651
help='commit even if nothing has changed'),
1652
Option('file', type=str,
1654
help='file containing commit message'),
1656
help="refuse to commit if there are unknown "
1657
"files in the working tree."),
1659
help="perform a local only commit in a bound "
1660
"branch. Such commits are not pushed to "
1661
"the master branch until a normal commit "
3076
ListOption('exclude', type=str, short_name='x',
3077
help="Do not consider changes made to a given path."),
3078
Option('message', type=unicode,
3080
help="Description of the new revision."),
3083
help='Commit even if nothing has changed.'),
3084
Option('file', type=str,
3087
help='Take commit message from this file.'),
3089
help="Refuse to commit if there are unknown "
3090
"files in the working tree."),
3091
Option('commit-time', type=str,
3092
help="Manually set a commit time using commit date "
3093
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3094
ListOption('fixes', type=str,
3095
help="Mark a bug as being fixed by this revision "
3096
"(see \"bzr help bugs\")."),
3097
ListOption('author', type=unicode,
3098
help="Set the author's name, if it's different "
3099
"from the committer."),
3101
help="Perform a local commit in a bound "
3102
"branch. Local commits are not pushed to "
3103
"the master branch until a normal commit "
3106
Option('show-diff', short_name='p',
3107
help='When no message is supplied, show the diff along'
3108
' with the status summary in the message editor.'),
1665
3110
aliases = ['ci', 'checkin']
1667
def run(self, message=None, file=None, verbose=True, selected_list=None,
1668
unchanged=False, strict=False, local=False):
1669
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
1670
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1672
from bzrlib.msgeditor import edit_commit_message, \
1673
make_commit_message_template
1674
from tempfile import TemporaryFile
3112
def _iter_bug_fix_urls(self, fixes, branch):
3113
# Configure the properties for bug fixing attributes.
3114
for fixed_bug in fixes:
3115
tokens = fixed_bug.split(':')
3116
if len(tokens) != 2:
3117
raise errors.BzrCommandError(
3118
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3119
"See \"bzr help bugs\" for more information on this "
3120
"feature.\nCommit refused." % fixed_bug)
3121
tag, bug_id = tokens
3123
yield bugtracker.get_bug_url(tag, branch, bug_id)
3124
except errors.UnknownBugTrackerAbbreviation:
3125
raise errors.BzrCommandError(
3126
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3127
except errors.MalformedBugIdentifier, e:
3128
raise errors.BzrCommandError(
3129
"%s\nCommit refused." % (str(e),))
3131
def run(self, message=None, file=None, verbose=False, selected_list=None,
3132
unchanged=False, strict=False, local=False, fixes=None,
3133
author=None, show_diff=False, exclude=None, commit_time=None):
3134
from bzrlib.errors import (
3139
from bzrlib.msgeditor import (
3140
edit_commit_message_encoded,
3141
generate_commit_message_template,
3142
make_commit_message_template_encoded
3145
commit_stamp = offset = None
3146
if commit_time is not None:
3148
commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3149
except ValueError, e:
3150
raise errors.BzrCommandError(
3151
"Could not parse --commit-time: " + str(e))
1676
3153
# TODO: Need a blackbox test for invoking the external editor; may be
1677
3154
# slightly problematic to run this cross-platform.
1679
# TODO: do more checks that the commit will succeed before
3156
# TODO: do more checks that the commit will succeed before
1680
3157
# spending the user's valuable time typing a commit message.
1682
# TODO: if the commit *does* happen to fail, then save the commit
1683
# message to a temporary file where it can be recovered
1684
tree, selected_list = tree_files(selected_list)
3161
tree, selected_list = WorkingTree.open_containing_paths(selected_list)
1685
3162
if selected_list == ['']:
1686
3163
# workaround - commit of root of tree should be exactly the same
1687
3164
# as just default commit in that tree, and succeed even though
1688
3165
# selected-file merge commit is not done yet
1689
3166
selected_list = []
3170
bug_property = bugtracker.encode_fixes_bug_urls(
3171
self._iter_bug_fix_urls(fixes, tree.branch))
3173
properties['bugs'] = bug_property
1691
3175
if local and not tree.branch.get_bound_location():
1692
3176
raise errors.LocalRequiresBoundBranch()
1693
if message is None and not file:
1694
template = make_commit_message_template(tree, selected_list)
1695
message = edit_commit_message(template)
1697
raise BzrCommandError("please specify a commit message"
1698
" with either --message or --file")
1699
elif message and file:
1700
raise BzrCommandError("please specify either --message or --file")
1703
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1706
raise BzrCommandError("empty commit message specified")
1709
reporter = ReportCommitToLog()
1711
reporter = NullCommitReporter()
3178
if message is not None:
3180
file_exists = osutils.lexists(message)
3181
except UnicodeError:
3182
# The commit message contains unicode characters that can't be
3183
# represented in the filesystem encoding, so that can't be a
3188
'The commit message is a file name: "%(f)s".\n'
3189
'(use --file "%(f)s" to take commit message from that file)'
3191
ui.ui_factory.show_warning(warning_msg)
3193
message = message.replace('\r\n', '\n')
3194
message = message.replace('\r', '\n')
3196
raise errors.BzrCommandError(
3197
"please specify either --message or --file")
3199
def get_message(commit_obj):
3200
"""Callback to get commit message"""
3204
my_message = f.read().decode(osutils.get_user_encoding())
3207
elif message is not None:
3208
my_message = message
3210
# No message supplied: make one up.
3211
# text is the status of the tree
3212
text = make_commit_message_template_encoded(tree,
3213
selected_list, diff=show_diff,
3214
output_encoding=osutils.get_user_encoding())
3215
# start_message is the template generated from hooks
3216
# XXX: Warning - looks like hooks return unicode,
3217
# make_commit_message_template_encoded returns user encoding.
3218
# We probably want to be using edit_commit_message instead to
3220
start_message = generate_commit_message_template(commit_obj)
3221
my_message = edit_commit_message_encoded(text,
3222
start_message=start_message)
3223
if my_message is None:
3224
raise errors.BzrCommandError("please specify a commit"
3225
" message with either --message or --file")
3226
if my_message == "":
3227
raise errors.BzrCommandError("empty commit message specified")
3230
# The API permits a commit with a filter of [] to mean 'select nothing'
3231
# but the command line should not do that.
3232
if not selected_list:
3233
selected_list = None
1714
tree.commit(message, specific_files=selected_list,
3235
tree.commit(message_callback=get_message,
3236
specific_files=selected_list,
1715
3237
allow_pointless=unchanged, strict=strict, local=local,
3238
reporter=None, verbose=verbose, revprops=properties,
3239
authors=author, timestamp=commit_stamp,
3241
exclude=tree.safe_relpath_files(exclude))
1717
3242
except PointlessCommit:
1718
# FIXME: This should really happen before the file is read in;
1719
# perhaps prepare the commit; get the message; then actually commit
1720
raise BzrCommandError("no changes to commit."
1721
" use --unchanged to commit anyhow")
3243
raise errors.BzrCommandError("No changes to commit."
3244
" Use --unchanged to commit anyhow.")
1722
3245
except ConflictsInTree:
1723
raise BzrCommandError("Conflicts detected in working tree. "
1724
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
3246
raise errors.BzrCommandError('Conflicts detected in working '
3247
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
1725
3249
except StrictCommitFailed:
1726
raise BzrCommandError("Commit refused because there are unknown "
1727
"files in the working tree.")
3250
raise errors.BzrCommandError("Commit refused because there are"
3251
" unknown files in the working tree.")
1728
3252
except errors.BoundBranchOutOfDate, e:
1729
raise BzrCommandError(str(e)
1730
+ ' Either unbind, update, or'
1731
' pass --local to commit.')
3253
e.extra_help = ("\n"
3254
'To commit to master branch, run update and then commit.\n'
3255
'You can also pass --local to commit to continue working '
1734
3260
class cmd_check(Command):
1735
"""Validate consistency of branch history.
1737
This command checks various invariants about the branch storage to
1738
detect data corruption or bzr bugs.
3261
__doc__ = """Validate working tree structure, branch consistency and repository history.
3263
This command checks various invariants about branch and repository storage
3264
to detect data corruption or bzr bugs.
3266
The working tree and branch checks will only give output if a problem is
3267
detected. The output fields of the repository check are:
3270
This is just the number of revisions checked. It doesn't
3274
This is just the number of versionedfiles checked. It
3275
doesn't indicate a problem.
3277
unreferenced ancestors
3278
Texts that are ancestors of other texts, but
3279
are not properly referenced by the revision ancestry. This is a
3280
subtle problem that Bazaar can work around.
3283
This is the total number of unique file contents
3284
seen in the checked revisions. It does not indicate a problem.
3287
This is the total number of repeated texts seen
3288
in the checked revisions. Texts can be repeated when their file
3289
entries are modified, but the file contents are not. It does not
3292
If no restrictions are specified, all Bazaar data that is found at the given
3293
location will be checked.
3297
Check the tree and branch at 'foo'::
3299
bzr check --tree --branch foo
3301
Check only the repository at 'bar'::
3303
bzr check --repo bar
3305
Check everything at 'baz'::
1740
takes_args = ['branch?']
1741
takes_options = ['verbose']
1743
def run(self, branch=None, verbose=False):
1744
from bzrlib.check import check
1746
tree = WorkingTree.open_containing()[0]
1747
branch = tree.branch
1749
branch = Branch.open(branch)
1750
check(branch, verbose)
1753
class cmd_scan_cache(Command):
1756
from bzrlib.hashcache import HashCache
1762
print '%6d stats' % c.stat_count
1763
print '%6d in hashcache' % len(c._cache)
1764
print '%6d files removed from cache' % c.removed_count
1765
print '%6d hashes updated' % c.update_count
1766
print '%6d files changed too recently to cache' % c.danger_count
3310
_see_also = ['reconcile']
3311
takes_args = ['path?']
3312
takes_options = ['verbose',
3313
Option('branch', help="Check the branch related to the"
3314
" current directory."),
3315
Option('repo', help="Check the repository related to the"
3316
" current directory."),
3317
Option('tree', help="Check the working tree related to"
3318
" the current directory.")]
3320
def run(self, path=None, verbose=False, branch=False, repo=False,
3322
from bzrlib.check import check_dwim
3325
if not branch and not repo and not tree:
3326
branch = repo = tree = True
3327
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
1772
3330
class cmd_upgrade(Command):
1773
"""Upgrade branch storage to current format.
3331
__doc__ = """Upgrade branch storage to current format.
1775
3333
The check command or bzr developers may sometimes advise you to run
1776
3334
this command. When the default format has changed you may also be warned
1777
3335
during other operations to upgrade.
3338
_see_also = ['check']
1779
3339
takes_args = ['url?']
1780
3340
takes_options = [
1782
help='Upgrade to a specific format. Current formats'
1783
' are: default, knit, metaweave and weave.'
1784
' Default is knit; metaweave and weave are'
1786
type=get_format_type),
3341
RegistryOption('format',
3342
help='Upgrade to a specific format. See "bzr help'
3343
' formats" for details.',
3344
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3345
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3346
value_switches=True, title='Branch format'),
1790
3349
def run(self, url='.', format=None):
1791
3350
from bzrlib.upgrade import upgrade
1793
format = get_format_type('default')
1794
3351
upgrade(url, format)
1797
3354
class cmd_whoami(Command):
1798
"""Show or set bzr user id.
1802
bzr whoami 'Frank Chu <fchu@example.com>'
3355
__doc__ = """Show or set bzr user id.
3358
Show the email of the current user::
3362
Set the current user::
3364
bzr whoami "Frank Chu <fchu@example.com>"
1804
takes_options = [ Option('email',
1805
help='display email address only'),
3366
takes_options = [ 'directory',
3368
help='Display email address only.'),
1806
3369
Option('branch',
1807
help='set identity for the current branch instead of '
3370
help='Set identity for the current branch instead of '
1810
3373
takes_args = ['name?']
1811
3374
encoding_type = 'replace'
1813
3376
@display_command
1814
def run(self, email=False, branch=False, name=None):
3377
def run(self, email=False, branch=False, name=None, directory=None):
1815
3378
if name is None:
1816
# use branch if we're inside one; otherwise global config
1818
c = Branch.open_containing('.')[0].get_config()
1819
except NotBranchError:
1820
c = config.GlobalConfig()
3379
if directory is None:
3380
# use branch if we're inside one; otherwise global config
3382
c = Branch.open_containing(u'.')[0].get_config()
3383
except errors.NotBranchError:
3384
c = _mod_config.GlobalConfig()
3386
c = Branch.open(directory).get_config()
1822
3388
self.outf.write(c.user_email() + '\n')
1824
3390
self.outf.write(c.username() + '\n')
3393
# display a warning if an email address isn't included in the given name.
3395
_mod_config.extract_email_address(name)
3396
except errors.NoEmailInUsername, e:
3397
warning('"%s" does not seem to contain an email address. '
3398
'This is allowed, but not recommended.', name)
1827
3400
# use global config unless --branch given
1829
c = Branch.open_containing('.')[0].get_config()
3402
if directory is None:
3403
c = Branch.open_containing(u'.')[0].get_config()
3405
c = Branch.open(directory).get_config()
1831
c = config.GlobalConfig()
3407
c = _mod_config.GlobalConfig()
1832
3408
c.set_user_option('email', name)
1835
3411
class cmd_nick(Command):
1836
"""Print or set the branch nickname.
1838
If unset, the tree root directory name is used as the nickname
1839
To print the current nickname, execute with no argument.
3412
__doc__ = """Print or set the branch nickname.
3414
If unset, the tree root directory name is used as the nickname.
3415
To print the current nickname, execute with no argument.
3417
Bound branches use the nickname of its master branch unless it is set
3421
_see_also = ['info']
1841
3422
takes_args = ['nickname?']
1842
def run(self, nickname=None):
1843
branch = Branch.open_containing(u'.')[0]
3423
takes_options = ['directory']
3424
def run(self, nickname=None, directory=u'.'):
3425
branch = Branch.open_containing(directory)[0]
1844
3426
if nickname is None:
1845
3427
self.printme(branch)
1849
3431
@display_command
1850
3432
def printme(self, branch):
3433
self.outf.write('%s\n' % branch.nick)
3436
class cmd_alias(Command):
3437
__doc__ = """Set/unset and display aliases.
3440
Show the current aliases::
3444
Show the alias specified for 'll'::
3448
Set an alias for 'll'::
3450
bzr alias ll="log --line -r-10..-1"
3452
To remove an alias for 'll'::
3454
bzr alias --remove ll
3457
takes_args = ['name?']
3459
Option('remove', help='Remove the alias.'),
3462
def run(self, name=None, remove=False):
3464
self.remove_alias(name)
3466
self.print_aliases()
3468
equal_pos = name.find('=')
3470
self.print_alias(name)
3472
self.set_alias(name[:equal_pos], name[equal_pos+1:])
3474
def remove_alias(self, alias_name):
3475
if alias_name is None:
3476
raise errors.BzrCommandError(
3477
'bzr alias --remove expects an alias to remove.')
3478
# If alias is not found, print something like:
3479
# unalias: foo: not found
3480
c = _mod_config.GlobalConfig()
3481
c.unset_alias(alias_name)
3484
def print_aliases(self):
3485
"""Print out the defined aliases in a similar format to bash."""
3486
aliases = _mod_config.GlobalConfig().get_aliases()
3487
for key, value in sorted(aliases.iteritems()):
3488
self.outf.write('bzr alias %s="%s"\n' % (key, value))
3491
def print_alias(self, alias_name):
3492
from bzrlib.commands import get_alias
3493
alias = get_alias(alias_name)
3495
self.outf.write("bzr alias: %s: not found\n" % alias_name)
3498
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
3500
def set_alias(self, alias_name, alias_command):
3501
"""Save the alias in the global config."""
3502
c = _mod_config.GlobalConfig()
3503
c.set_alias(alias_name, alias_command)
1854
3506
class cmd_selftest(Command):
1855
"""Run internal test suite.
1857
This creates temporary test directories in the working directory,
1858
but not existing data is affected. These directories are deleted
1859
if the tests pass, or left behind to help in debugging if they
1860
fail and --keep-output is specified.
1862
If arguments are given, they are regular expressions that say
1863
which tests should run.
3507
__doc__ = """Run internal test suite.
3509
If arguments are given, they are regular expressions that say which tests
3510
should run. Tests matching any expression are run, and other tests are
3513
Alternatively if --first is given, matching tests are run first and then
3514
all other tests are run. This is useful if you have been working in a
3515
particular area, but want to make sure nothing else was broken.
3517
If --exclude is given, tests that match that regular expression are
3518
excluded, regardless of whether they match --first or not.
3520
To help catch accidential dependencies between tests, the --randomize
3521
option is useful. In most cases, the argument used is the word 'now'.
3522
Note that the seed used for the random number generator is displayed
3523
when this option is used. The seed can be explicitly passed as the
3524
argument to this option if required. This enables reproduction of the
3525
actual ordering used if and when an order sensitive problem is encountered.
3527
If --list-only is given, the tests that would be run are listed. This is
3528
useful when combined with --first, --exclude and/or --randomize to
3529
understand their impact. The test harness reports "Listed nn tests in ..."
3530
instead of "Ran nn tests in ..." when list mode is enabled.
1865
3532
If the global option '--no-plugins' is given, plugins are not loaded
1866
3533
before running the selftests. This has two effects: features provided or
1867
3534
modified by plugins will not be tested, and tests provided by plugins will
1872
bzr --no-plugins selftest -v
3537
Tests that need working space on disk use a common temporary directory,
3538
typically inside $TMPDIR or /tmp.
3540
If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3541
into a pdb postmortem session.
3543
The --coverage=DIRNAME global option produces a report with covered code
3547
Run only tests relating to 'ignore'::
3551
Disable plugins and list tests as they're run::
3553
bzr --no-plugins selftest -v
1874
# TODO: --list should give a list of all available tests
1876
3555
# NB: this is used from the class without creating an instance, which is
1877
3556
# why it does not have a self parameter.
1878
3557
def get_transport_type(typestring):
1879
3558
"""Parse and return a transport specifier."""
1880
3559
if typestring == "sftp":
1881
from bzrlib.transport.sftp import SFTPAbsoluteServer
1882
return SFTPAbsoluteServer
3560
from bzrlib.tests import stub_sftp
3561
return stub_sftp.SFTPAbsoluteServer
1883
3562
if typestring == "memory":
1884
from bzrlib.transport.memory import MemoryServer
3563
from bzrlib.tests import test_server
3564
return memory.MemoryServer
1886
3565
if typestring == "fakenfs":
1887
from bzrlib.transport.fakenfs import FakeNFSServer
1888
return FakeNFSServer
3566
from bzrlib.tests import test_server
3567
return test_server.FakeNFSServer
1889
3568
msg = "No known transport type %s. Supported types are: sftp\n" %\
1891
raise BzrCommandError(msg)
3570
raise errors.BzrCommandError(msg)
1894
3573
takes_args = ['testspecs*']
1895
3574
takes_options = ['verbose',
1896
Option('one', help='stop when one test fails'),
1897
Option('keep-output',
1898
help='keep output directories when tests fail'),
3576
help='Stop when one test fails.',
1900
3580
help='Use a different transport by default '
1901
3581
'throughout the test suite.',
1902
3582
type=get_transport_type),
1903
Option('benchmark', help='run the bzr bencharks.'),
3584
help='Run the benchmarks rather than selftests.',
1904
3586
Option('lsprof-timed',
1905
help='generate lsprof output for benchmarked'
3587
help='Generate lsprof output for benchmarked'
1906
3588
' sections of code.'),
3589
Option('lsprof-tests',
3590
help='Generate lsprof output for each test.'),
3592
help='Run all tests, but run specified tests first.',
3596
help='List the tests instead of running them.'),
3597
RegistryOption('parallel',
3598
help="Run the test suite in parallel.",
3599
lazy_registry=('bzrlib.tests', 'parallel_registry'),
3600
value_switches=False,
3602
Option('randomize', type=str, argname="SEED",
3603
help='Randomize the order of tests using the given'
3604
' seed or "now" for the current time.'),
3605
Option('exclude', type=str, argname="PATTERN",
3607
help='Exclude tests that match this regular'
3610
help='Output test progress via subunit.'),
3611
Option('strict', help='Fail on missing dependencies or '
3613
Option('load-list', type=str, argname='TESTLISTFILE',
3614
help='Load a test id list from a text file.'),
3615
ListOption('debugflag', type=str, short_name='E',
3616
help='Turn on a selftest debug flag.'),
3617
ListOption('starting-with', type=str, argname='TESTID',
3618
param_name='starting_with', short_name='s',
3620
'Load only the tests starting with TESTID.'),
1909
def run(self, testspecs_list=None, verbose=None, one=False,
1910
keep_output=False, transport=None, benchmark=None,
1913
from bzrlib.tests import selftest
1914
import bzrlib.benchmarks as benchmarks
1915
# we don't want progress meters from the tests to go to the
1916
# real output; and we don't want log messages cluttering up
1918
save_ui = ui.ui_factory
1919
print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
1920
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
1922
info('running tests...')
3622
encoding_type = 'replace'
3625
Command.__init__(self)
3626
self.additional_selftest_args = {}
3628
def run(self, testspecs_list=None, verbose=False, one=False,
3629
transport=None, benchmark=None,
3631
first=False, list_only=False,
3632
randomize=None, exclude=None, strict=False,
3633
load_list=None, debugflag=None, starting_with=None, subunit=False,
3634
parallel=None, lsprof_tests=False):
3635
from bzrlib import tests
3637
if testspecs_list is not None:
3638
pattern = '|'.join(testspecs_list)
3643
from bzrlib.tests import SubUnitBzrRunner
3645
raise errors.BzrCommandError("subunit not available. subunit "
3646
"needs to be installed to use --subunit.")
3647
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3648
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3649
# stdout, which would corrupt the subunit stream.
3650
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3651
# following code can be deleted when it's sufficiently deployed
3652
# -- vila/mgz 20100514
3653
if (sys.platform == "win32"
3654
and getattr(sys.stdout, 'fileno', None) is not None):
3656
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3658
self.additional_selftest_args.setdefault(
3659
'suite_decorators', []).append(parallel)
3661
raise errors.BzrCommandError(
3662
"--benchmark is no longer supported from bzr 2.2; "
3663
"use bzr-usertest instead")
3664
test_suite_factory = None
3665
selftest_kwargs = {"verbose": verbose,
3667
"stop_on_failure": one,
3668
"transport": transport,
3669
"test_suite_factory": test_suite_factory,
3670
"lsprof_timed": lsprof_timed,
3671
"lsprof_tests": lsprof_tests,
3672
"matching_tests_first": first,
3673
"list_only": list_only,
3674
"random_seed": randomize,
3675
"exclude_pattern": exclude,
3677
"load_list": load_list,
3678
"debug_flags": debugflag,
3679
"starting_with": starting_with
3681
selftest_kwargs.update(self.additional_selftest_args)
3683
# Make deprecation warnings visible, unless -Werror is set
3684
cleanup = symbol_versioning.activate_deprecation_warnings(
1924
ui.ui_factory = ui.SilentUIFactory()
1925
if testspecs_list is not None:
1926
pattern = '|'.join(testspecs_list)
1930
test_suite_factory = benchmarks.test_suite
1934
test_suite_factory = None
1937
result = selftest(verbose=verbose,
1939
stop_on_failure=one,
1940
keep_output=keep_output,
1941
transport=transport,
1942
test_suite_factory=test_suite_factory,
1943
lsprof_timed=lsprof_timed)
1945
info('tests passed')
1947
info('tests failed')
1948
return int(not result)
3687
result = tests.selftest(**selftest_kwargs)
1950
ui.ui_factory = save_ui
1953
def _get_bzr_branch():
1954
"""If bzr is run from a branch, return Branch or None"""
1955
from os.path import dirname
1958
branch = Branch.open(dirname(osutils.abspath(dirname(__file__))))
1960
except errors.BzrError:
1966
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1967
# is bzrlib itself in a branch?
1968
branch = _get_bzr_branch()
1970
rh = branch.revision_history()
1972
print " bzr checkout, revision %d" % (revno,)
1973
print " nick: %s" % (branch.nick,)
1975
print " revid: %s" % (rh[-1],)
1976
print "Using python interpreter:", sys.executable
1978
print "Using python standard library:", os.path.dirname(site.__file__)
1979
print "Using bzrlib:",
1980
if len(bzrlib.__path__) > 1:
1981
# print repr, which is a good enough way of making it clear it's
1982
# more than one element (eg ['/foo/bar', '/foo/bzr'])
1983
print repr(bzrlib.__path__)
1985
print bzrlib.__path__[0]
1988
print bzrlib.__copyright__
1989
print "http://bazaar-vcs.org/"
1991
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1992
print "you may use, modify and redistribute it under the terms of the GNU"
1993
print "General Public License version 2 or later."
3690
return int(not result)
1996
3693
class cmd_version(Command):
1997
"""Show version of bzr."""
3694
__doc__ = """Show version of bzr."""
3696
encoding_type = 'replace'
3698
Option("short", help="Print just the version number."),
1998
3701
@display_command
3702
def run(self, short=False):
3703
from bzrlib.version import show_version
3705
self.outf.write(bzrlib.version_string + '\n')
3707
show_version(to_file=self.outf)
2002
3710
class cmd_rocks(Command):
2003
"""Statement of optimism."""
3711
__doc__ = """Statement of optimism."""
2005
3715
@display_command
2007
print "it sure does!"
3717
self.outf.write("It sure does!\n")
2010
3720
class cmd_find_merge_base(Command):
2011
"""Find and print a base revision for merging two branches.
3721
__doc__ = """Find and print a base revision for merging two branches."""
2013
3722
# TODO: Options to specify revisions on either side, as if
2014
3723
# merging only part of the history.
2015
3724
takes_args = ['branch', 'other']
2018
3727
@display_command
2019
3728
def run(self, branch, other):
2020
from bzrlib.revision import common_ancestor, MultipleRevisionSources
3729
from bzrlib.revision import ensure_null
2022
3731
branch1 = Branch.open_containing(branch)[0]
2023
3732
branch2 = Branch.open_containing(other)[0]
2025
history_1 = branch1.revision_history()
2026
history_2 = branch2.revision_history()
2028
last1 = branch1.last_revision()
2029
last2 = branch2.last_revision()
2031
source = MultipleRevisionSources(branch1.repository,
2034
base_rev_id = common_ancestor(last1, last2, source)
2036
print 'merge base is revision %s' % base_rev_id
3733
self.add_cleanup(branch1.lock_read().unlock)
3734
self.add_cleanup(branch2.lock_read().unlock)
3735
last1 = ensure_null(branch1.last_revision())
3736
last2 = ensure_null(branch2.last_revision())
3738
graph = branch1.repository.get_graph(branch2.repository)
3739
base_rev_id = graph.find_unique_lca(last1, last2)
3741
self.outf.write('merge base is revision %s\n' % base_rev_id)
2039
3744
class cmd_merge(Command):
2040
"""Perform a three-way merge.
2042
The branch is the branch you will merge from. By default, it will merge
2043
the latest revision. If you specify a revision, that revision will be
2044
merged. If you specify two revisions, the first will be used as a BASE,
2045
and the second one as OTHER. Revision numbers are always relative to the
3745
__doc__ = """Perform a three-way merge.
3747
The source of the merge can be specified either in the form of a branch,
3748
or in the form of a path to a file containing a merge directive generated
3749
with bzr send. If neither is specified, the default is the upstream branch
3750
or the branch most recently merged using --remember.
3752
When merging a branch, by default the tip will be merged. To pick a different
3753
revision, pass --revision. If you specify two values, the first will be used as
3754
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3755
available revisions, like this is commonly referred to as "cherrypicking".
3757
Revision numbers are always relative to the branch being merged.
2048
3759
By default, bzr will try to merge in all new work from the other
2049
3760
branch, automatically determining an appropriate base. If this
2050
3761
fails, you may need to give an explicit base.
2052
3763
Merge will do its best to combine the changes in two branches, but there
2053
3764
are some kinds of problems only a human can fix. When it encounters those,
2054
3765
it will mark a conflict. A conflict means that you need to fix something,
2061
3772
default, use --remember. The value will only be saved if the remote
2062
3773
location can be accessed.
2066
To merge the latest revision from bzr.dev
2067
bzr merge ../bzr.dev
2069
To merge changes up to and including revision 82 from bzr.dev
2070
bzr merge -r 82 ../bzr.dev
2072
To merge the changes introduced by 82, without previous changes:
2073
bzr merge -r 81..82 ../bzr.dev
3775
The results of the merge are placed into the destination working
3776
directory, where they can be reviewed (with bzr diff), tested, and then
3777
committed to record the result of the merge.
2075
3779
merge refuses to run if there are any uncommitted changes, unless
2078
The following merge types are available:
3780
--force is given. The --force option can also be used to create a
3781
merge revision which has more than two parents.
3783
If one would like to merge changes from the working tree of the other
3784
branch without merging any committed revisions, the --uncommitted option
3787
To select only some changes to merge, use "merge -i", which will prompt
3788
you to apply each diff hunk and file change, similar to "shelve".
3791
To merge the latest revision from bzr.dev::
3793
bzr merge ../bzr.dev
3795
To merge changes up to and including revision 82 from bzr.dev::
3797
bzr merge -r 82 ../bzr.dev
3799
To merge the changes introduced by 82, without previous changes::
3801
bzr merge -r 81..82 ../bzr.dev
3803
To apply a merge directive contained in /tmp/merge::
3805
bzr merge /tmp/merge
3807
To create a merge revision with three parents from two branches
3808
feature1a and feature1b:
3810
bzr merge ../feature1a
3811
bzr merge ../feature1b --force
3812
bzr commit -m 'revision with three parents'
2080
takes_args = ['branch?']
2081
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
2082
Option('show-base', help="Show base revision text in "
2086
from merge import merge_type_help
2087
from inspect import getdoc
2088
return getdoc(self) + '\n' + merge_type_help()
2090
def run(self, branch=None, revision=None, force=False, merge_type=None,
2091
show_base=False, reprocess=False, remember=False):
3815
encoding_type = 'exact'
3816
_see_also = ['update', 'remerge', 'status-flags', 'send']
3817
takes_args = ['location?']
3822
help='Merge even if the destination tree has uncommitted changes.'),
3826
Option('show-base', help="Show base revision text in "
3828
Option('uncommitted', help='Apply uncommitted changes'
3829
' from a working copy, instead of branch changes.'),
3830
Option('pull', help='If the destination is already'
3831
' completely merged into the source, pull from the'
3832
' source rather than merging. When this happens,'
3833
' you do not need to commit the result.'),
3834
custom_help('directory',
3835
help='Branch to merge into, '
3836
'rather than the one containing the working directory.'),
3837
Option('preview', help='Instead of merging, show a diff of the'
3839
Option('interactive', help='Select changes interactively.',
3843
def run(self, location=None, revision=None, force=False,
3844
merge_type=None, show_base=False, reprocess=None, remember=False,
3845
uncommitted=False, pull=False,
2092
3850
if merge_type is None:
2093
merge_type = Merge3Merger
2095
tree = WorkingTree.open_containing(u'.')[0]
2097
if branch is not None:
2099
reader = bundle.read_bundle_from_url(branch)
2101
pass # Continue on considering this url a Branch
2103
conflicts = merge_bundle(reader, tree, not force, merge_type,
2104
reprocess, show_base)
2110
branch = self._get_remembered_parent(tree, branch, 'Merging from')
2112
if revision is None or len(revision) < 1:
2114
other = [branch, -1]
2115
other_branch, path = Branch.open_containing(branch)
2117
if len(revision) == 1:
2119
other_branch, path = Branch.open_containing(branch)
2120
revno = revision[0].in_history(other_branch).revno
2121
other = [branch, revno]
2123
assert len(revision) == 2
2124
if None in revision:
2125
raise BzrCommandError(
2126
"Merge doesn't permit that revision specifier.")
2127
other_branch, path = Branch.open_containing(branch)
2129
base = [branch, revision[0].in_history(other_branch).revno]
2130
other = [branch, revision[1].in_history(other_branch).revno]
2132
if tree.branch.get_parent() is None or remember:
2133
tree.branch.set_parent(other_branch.base)
2136
interesting_files = [path]
2138
interesting_files = None
3851
merge_type = _mod_merge.Merge3Merger
3853
if directory is None: directory = u'.'
3854
possible_transports = []
3856
allow_pending = True
3857
verified = 'inapplicable'
3858
tree = WorkingTree.open_containing(directory)[0]
3861
basis_tree = tree.revision_tree(tree.last_revision())
3862
except errors.NoSuchRevision:
3863
basis_tree = tree.basis_tree()
3865
# die as quickly as possible if there are uncommitted changes
3867
if tree.has_changes():
3868
raise errors.UncommittedChanges(tree)
3870
view_info = _get_view_info_for_change_reporter(tree)
3871
change_reporter = delta._ChangeReporter(
3872
unversioned_filter=tree.is_ignored, view_info=view_info)
2139
3873
pb = ui.ui_factory.nested_progress_bar()
3874
self.add_cleanup(pb.finished)
3875
self.add_cleanup(tree.lock_write().unlock)
3876
if location is not None:
2142
conflict_count = merge(other, base, check_clean=(not force),
2143
merge_type=merge_type,
2144
reprocess=reprocess,
2145
show_base=show_base,
2146
pb=pb, file_list=interesting_files)
2149
if conflict_count != 0:
3878
mergeable = bundle.read_mergeable_from_url(location,
3879
possible_transports=possible_transports)
3880
except errors.NotABundle:
3884
raise errors.BzrCommandError('Cannot use --uncommitted'
3885
' with bundles or merge directives.')
3887
if revision is not None:
3888
raise errors.BzrCommandError(
3889
'Cannot use -r with merge directives or bundles')
3890
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3893
if merger is None and uncommitted:
3894
if revision is not None and len(revision) > 0:
3895
raise errors.BzrCommandError('Cannot use --uncommitted and'
3896
' --revision at the same time.')
3897
merger = self.get_merger_from_uncommitted(tree, location, None)
3898
allow_pending = False
3901
merger, allow_pending = self._get_merger_from_branch(tree,
3902
location, revision, remember, possible_transports, None)
3904
merger.merge_type = merge_type
3905
merger.reprocess = reprocess
3906
merger.show_base = show_base
3907
self.sanity_check_merger(merger)
3908
if (merger.base_rev_id == merger.other_rev_id and
3909
merger.other_rev_id is not None):
3910
note('Nothing to do.')
3913
if merger.interesting_files is not None:
3914
raise errors.BzrCommandError('Cannot pull individual files')
3915
if (merger.base_rev_id == tree.last_revision()):
3916
result = tree.pull(merger.other_branch, False,
3917
merger.other_rev_id)
3918
result.report(self.outf)
2153
except errors.AmbiguousBase, e:
2154
m = ("sorry, bzr can't determine the right merge base yet\n"
2155
"candidates are:\n "
2156
+ "\n ".join(e.bases)
2158
"please specify an explicit base with -r,\n"
2159
"and (if you want) report this to the bzr developers\n")
2162
# TODO: move up to common parent; this isn't merge-specific anymore.
2163
def _get_remembered_parent(self, tree, supplied_location, verb_string):
3920
if merger.this_basis is None:
3921
raise errors.BzrCommandError(
3922
"This branch has no commits."
3923
" (perhaps you would prefer 'bzr pull')")
3925
return self._do_preview(merger)
3927
return self._do_interactive(merger)
3929
return self._do_merge(merger, change_reporter, allow_pending,
3932
def _get_preview(self, merger):
3933
tree_merger = merger.make_merger()
3934
tt = tree_merger.make_preview_transform()
3935
self.add_cleanup(tt.finalize)
3936
result_tree = tt.get_preview_tree()
3939
def _do_preview(self, merger):
3940
from bzrlib.diff import show_diff_trees
3941
result_tree = self._get_preview(merger)
3942
path_encoding = osutils.get_diff_header_encoding()
3943
show_diff_trees(merger.this_tree, result_tree, self.outf,
3944
old_label='', new_label='',
3945
path_encoding=path_encoding)
3947
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3948
merger.change_reporter = change_reporter
3949
conflict_count = merger.do_merge()
3951
merger.set_pending()
3952
if verified == 'failed':
3953
warning('Preview patch does not match changes')
3954
if conflict_count != 0:
3959
def _do_interactive(self, merger):
3960
"""Perform an interactive merge.
3962
This works by generating a preview tree of the merge, then using
3963
Shelver to selectively remove the differences between the working tree
3964
and the preview tree.
3966
from bzrlib import shelf_ui
3967
result_tree = self._get_preview(merger)
3968
writer = bzrlib.option.diff_writer_registry.get()
3969
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3970
reporter=shelf_ui.ApplyReporter(),
3971
diff_writer=writer(sys.stdout))
3977
def sanity_check_merger(self, merger):
3978
if (merger.show_base and
3979
not merger.merge_type is _mod_merge.Merge3Merger):
3980
raise errors.BzrCommandError("Show-base is not supported for this"
3981
" merge type. %s" % merger.merge_type)
3982
if merger.reprocess is None:
3983
if merger.show_base:
3984
merger.reprocess = False
3986
# Use reprocess if the merger supports it
3987
merger.reprocess = merger.merge_type.supports_reprocess
3988
if merger.reprocess and not merger.merge_type.supports_reprocess:
3989
raise errors.BzrCommandError("Conflict reduction is not supported"
3990
" for merge type %s." %
3992
if merger.reprocess and merger.show_base:
3993
raise errors.BzrCommandError("Cannot do conflict reduction and"
3996
def _get_merger_from_branch(self, tree, location, revision, remember,
3997
possible_transports, pb):
3998
"""Produce a merger from a location, assuming it refers to a branch."""
3999
from bzrlib.tag import _merge_tags_if_possible
4000
# find the branch locations
4001
other_loc, user_location = self._select_branch_location(tree, location,
4003
if revision is not None and len(revision) == 2:
4004
base_loc, _unused = self._select_branch_location(tree,
4005
location, revision, 0)
4007
base_loc = other_loc
4009
other_branch, other_path = Branch.open_containing(other_loc,
4010
possible_transports)
4011
if base_loc == other_loc:
4012
base_branch = other_branch
4014
base_branch, base_path = Branch.open_containing(base_loc,
4015
possible_transports)
4016
# Find the revision ids
4017
other_revision_id = None
4018
base_revision_id = None
4019
if revision is not None:
4020
if len(revision) >= 1:
4021
other_revision_id = revision[-1].as_revision_id(other_branch)
4022
if len(revision) == 2:
4023
base_revision_id = revision[0].as_revision_id(base_branch)
4024
if other_revision_id is None:
4025
other_revision_id = _mod_revision.ensure_null(
4026
other_branch.last_revision())
4027
# Remember where we merge from
4028
if ((remember or tree.branch.get_submit_branch() is None) and
4029
user_location is not None):
4030
tree.branch.set_submit_branch(other_branch.base)
4031
_merge_tags_if_possible(other_branch, tree.branch)
4032
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4033
other_revision_id, base_revision_id, other_branch, base_branch)
4034
if other_path != '':
4035
allow_pending = False
4036
merger.interesting_files = [other_path]
4038
allow_pending = True
4039
return merger, allow_pending
4041
def get_merger_from_uncommitted(self, tree, location, pb):
4042
"""Get a merger for uncommitted changes.
4044
:param tree: The tree the merger should apply to.
4045
:param location: The location containing uncommitted changes.
4046
:param pb: The progress bar to use for showing progress.
4048
location = self._select_branch_location(tree, location)[0]
4049
other_tree, other_path = WorkingTree.open_containing(location)
4050
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
4051
if other_path != '':
4052
merger.interesting_files = [other_path]
4055
def _select_branch_location(self, tree, user_location, revision=None,
4057
"""Select a branch location, according to possible inputs.
4059
If provided, branches from ``revision`` are preferred. (Both
4060
``revision`` and ``index`` must be supplied.)
4062
Otherwise, the ``location`` parameter is used. If it is None, then the
4063
``submit`` or ``parent`` location is used, and a note is printed.
4065
:param tree: The working tree to select a branch for merging into
4066
:param location: The location entered by the user
4067
:param revision: The revision parameter to the command
4068
:param index: The index to use for the revision parameter. Negative
4069
indices are permitted.
4070
:return: (selected_location, user_location). The default location
4071
will be the user-entered location.
4073
if (revision is not None and index is not None
4074
and revision[index] is not None):
4075
branch = revision[index].get_branch()
4076
if branch is not None:
4077
return branch, branch
4078
if user_location is None:
4079
location = self._get_remembered(tree, 'Merging from')
4081
location = user_location
4082
return location, user_location
4084
def _get_remembered(self, tree, verb_string):
2164
4085
"""Use tree.branch's parent if none was supplied.
2166
4087
Report if the remembered location was used.
2168
if supplied_location is not None:
2169
return supplied_location
2170
stored_location = tree.branch.get_parent()
4089
stored_location = tree.branch.get_submit_branch()
4090
stored_location_type = "submit"
4091
if stored_location is None:
4092
stored_location = tree.branch.get_parent()
4093
stored_location_type = "parent"
2171
4094
mutter("%s", stored_location)
2172
4095
if stored_location is None:
2173
raise BzrCommandError("No location specified or remembered")
2174
display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2175
self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
4096
raise errors.BzrCommandError("No location specified or remembered")
4097
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4098
note(u"%s remembered %s location %s", verb_string,
4099
stored_location_type, display_url)
2176
4100
return stored_location
2179
4103
class cmd_remerge(Command):
4104
__doc__ = """Redo a merge.
2182
4106
Use this if you want to try a different merge technique while resolving
2183
conflicts. Some merge techniques are better than others, and remerge
4107
conflicts. Some merge techniques are better than others, and remerge
2184
4108
lets you try different ones on different files.
2186
4110
The options for remerge have the same meaning and defaults as the ones for
2187
4111
merge. The difference is that remerge can (only) be run when there is a
2188
4112
pending merge, and it lets you specify particular files.
2191
$ bzr remerge --show-base
2192
4115
Re-do the merge of all conflicted files, and show the base text in
2193
conflict regions, in addition to the usual THIS and OTHER texts.
2195
$ bzr remerge --merge-type weave --reprocess foobar
4116
conflict regions, in addition to the usual THIS and OTHER texts::
4118
bzr remerge --show-base
2196
4120
Re-do the merge of "foobar", using the weave merge algorithm, with
2197
additional processing to reduce the size of conflict regions.
2199
The following merge types are available:"""
4121
additional processing to reduce the size of conflict regions::
4123
bzr remerge --merge-type weave --reprocess foobar
2200
4125
takes_args = ['file*']
2201
takes_options = ['merge-type', 'reprocess',
2202
Option('show-base', help="Show base revision text in "
2206
from merge import merge_type_help
2207
from inspect import getdoc
2208
return getdoc(self) + '\n' + merge_type_help()
4130
help="Show base revision text in conflicts."),
2210
4133
def run(self, file_list=None, merge_type=None, show_base=False,
2211
4134
reprocess=False):
2212
from bzrlib.merge import merge_inner, transform_tree
4135
from bzrlib.conflicts import restore
2213
4136
if merge_type is None:
2214
merge_type = Merge3Merger
2215
tree, file_list = tree_files(file_list)
4137
merge_type = _mod_merge.Merge3Merger
4138
tree, file_list = WorkingTree.open_containing_paths(file_list)
4139
self.add_cleanup(tree.lock_write().unlock)
4140
parents = tree.get_parent_ids()
4141
if len(parents) != 2:
4142
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4143
" merges. Not cherrypicking or"
4145
repository = tree.branch.repository
4146
interesting_ids = None
4148
conflicts = tree.conflicts()
4149
if file_list is not None:
4150
interesting_ids = set()
4151
for filename in file_list:
4152
file_id = tree.path2id(filename)
4154
raise errors.NotVersionedError(filename)
4155
interesting_ids.add(file_id)
4156
if tree.kind(file_id) != "directory":
4159
for name, ie in tree.inventory.iter_entries(file_id):
4160
interesting_ids.add(ie.file_id)
4161
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4163
# Remerge only supports resolving contents conflicts
4164
allowed_conflicts = ('text conflict', 'contents conflict')
4165
restore_files = [c.path for c in conflicts
4166
if c.typestring in allowed_conflicts]
4167
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4168
tree.set_conflicts(ConflictList(new_conflicts))
4169
if file_list is not None:
4170
restore_files = file_list
4171
for filename in restore_files:
4173
restore(tree.abspath(filename))
4174
except errors.NotConflicted:
4176
# Disable pending merges, because the file texts we are remerging
4177
# have not had those merges performed. If we use the wrong parents
4178
# list, we imply that the working tree text has seen and rejected
4179
# all the changes from the other tree, when in fact those changes
4180
# have not yet been seen.
4181
tree.set_parent_ids(parents[:1])
2218
pending_merges = tree.pending_merges()
2219
if len(pending_merges) != 1:
2220
raise BzrCommandError("Sorry, remerge only works after normal"
2221
" merges. Not cherrypicking or"
2223
repository = tree.branch.repository
2224
base_revision = common_ancestor(tree.branch.last_revision(),
2225
pending_merges[0], repository)
2226
base_tree = repository.revision_tree(base_revision)
2227
other_tree = repository.revision_tree(pending_merges[0])
2228
interesting_ids = None
2230
conflicts = tree.conflicts()
2231
if file_list is not None:
2232
interesting_ids = set()
2233
for filename in file_list:
2234
file_id = tree.path2id(filename)
2236
raise NotVersionedError(filename)
2237
interesting_ids.add(file_id)
2238
if tree.kind(file_id) != "directory":
2241
for name, ie in tree.inventory.iter_entries(file_id):
2242
interesting_ids.add(ie.file_id)
2243
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2244
transform_tree(tree, tree.basis_tree(), interesting_ids)
2245
tree.set_conflicts(ConflictList(new_conflicts))
2246
if file_list is None:
2247
restore_files = list(tree.iter_conflicts())
2249
restore_files = file_list
2250
for filename in restore_files:
2252
restore(tree.abspath(filename))
2253
except NotConflicted:
2255
conflicts = merge_inner(tree.branch, other_tree, base_tree,
2257
interesting_ids=interesting_ids,
2258
other_rev_id=pending_merges[0],
2259
merge_type=merge_type,
2260
show_base=show_base,
2261
reprocess=reprocess)
4183
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4184
merger.interesting_ids = interesting_ids
4185
merger.merge_type = merge_type
4186
merger.show_base = show_base
4187
merger.reprocess = reprocess
4188
conflicts = merger.do_merge()
4190
tree.set_parent_ids(parents)
2264
4191
if conflicts > 0:
2269
4197
class cmd_revert(Command):
2270
"""Reverse all changes since the last commit.
2272
Only versioned files are affected. Specify filenames to revert only
2273
those files. By default, any files that are changed will be backed up
2274
first. Backup files have a '~' appended to their name.
4198
__doc__ = """Revert files to a previous revision.
4200
Giving a list of files will revert only those files. Otherwise, all files
4201
will be reverted. If the revision is not specified with '--revision', the
4202
last committed revision is used.
4204
To remove only some changes, without reverting to a prior version, use
4205
merge instead. For example, "merge . --revision -2..-3" will remove the
4206
changes introduced by -2, without affecting the changes introduced by -1.
4207
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4209
By default, any files that have been manually changed will be backed up
4210
first. (Files changed only by merge are not backed up.) Backup files have
4211
'.~#~' appended to their name, where # is a number.
4213
When you provide files, you can use their current pathname or the pathname
4214
from the target revision. So you can use revert to "undelete" a file by
4215
name. If you name a directory, all the contents of that directory will be
4218
If you have newly added files since the target revision, they will be
4219
removed. If the files to be removed have been changed, backups will be
4220
created as above. Directories containing unknown files will not be
4223
The working tree contains a list of revisions that have been merged but
4224
not yet committed. These revisions will be included as additional parents
4225
of the next commit. Normally, using revert clears that list as well as
4226
reverting the files. If any files are specified, revert leaves the list
4227
of uncommitted merges alone and reverts only the files. Use ``bzr revert
4228
.`` in the tree root to revert all files but keep the recorded merges,
4229
and ``bzr revert --forget-merges`` to clear the pending merge list without
4230
reverting any files.
4232
Using "bzr revert --forget-merges", it is possible to apply all of the
4233
changes from a branch in a single revision. To do this, perform the merge
4234
as desired. Then doing revert with the "--forget-merges" option will keep
4235
the content of the tree as it was, but it will clear the list of pending
4236
merges. The next commit will then contain all of the changes that are
4237
present in the other branch, but without any other parent revisions.
4238
Because this technique forgets where these changes originated, it may
4239
cause additional conflicts on later merges involving the same source and
2276
takes_options = ['revision', 'no-backup']
4243
_see_also = ['cat', 'export']
4246
Option('no-backup', "Do not save backups of reverted files."),
4247
Option('forget-merges',
4248
'Remove pending merge marker, without changing any files.'),
2277
4250
takes_args = ['file*']
2278
aliases = ['merge-revert']
2280
def run(self, revision=None, no_backup=False, file_list=None):
2281
from bzrlib.commands import parse_spec
2282
if file_list is not None:
2283
if len(file_list) == 0:
2284
raise BzrCommandError("No files specified")
2288
tree, file_list = tree_files(file_list)
2289
if revision is None:
2290
# FIXME should be tree.last_revision
2291
rev_id = tree.last_revision()
2292
elif len(revision) != 1:
2293
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
2295
rev_id = revision[0].in_history(tree.branch).rev_id
2296
pb = ui.ui_factory.nested_progress_bar()
2298
tree.revert(file_list,
2299
tree.branch.repository.revision_tree(rev_id),
4252
def run(self, revision=None, no_backup=False, file_list=None,
4253
forget_merges=None):
4254
tree, file_list = WorkingTree.open_containing_paths(file_list)
4255
self.add_cleanup(tree.lock_tree_write().unlock)
4257
tree.set_parent_ids(tree.get_parent_ids()[:1])
4259
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
4262
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4263
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4264
tree.revert(file_list, rev_tree, not no_backup, None,
4265
report_changes=True)
2305
4268
class cmd_assert_fail(Command):
2306
"""Test reporting of assertion failures"""
4269
__doc__ = """Test reporting of assertion failures"""
4270
# intended just for use in testing
2309
assert False, "always fails"
4275
raise AssertionError("always fails")
2312
4278
class cmd_help(Command):
2313
"""Show help on a command or other topic.
4279
__doc__ = """Show help on a command or other topic.
2315
For a list of all available commands, say 'bzr help commands'."""
2316
takes_options = [Option('long', 'show help on all commands')]
4282
_see_also = ['topics']
4284
Option('long', 'Show help on all commands.'),
2317
4286
takes_args = ['topic?']
2318
4287
aliases = ['?', '--help', '-?', '-h']
2320
4289
@display_command
2321
4290
def run(self, topic=None, long=False):
2323
4292
if topic is None and long:
2324
4293
topic = "commands"
4294
bzrlib.help.help(topic)
2328
4297
class cmd_shell_complete(Command):
2329
"""Show appropriate completions for context.
4298
__doc__ = """Show appropriate completions for context.
2331
For a list of all available commands, say 'bzr shell-complete'."""
4300
For a list of all available commands, say 'bzr shell-complete'.
2332
4302
takes_args = ['context?']
2333
4303
aliases = ['s-c']
2336
4306
@display_command
2337
4307
def run(self, context=None):
2338
4308
import shellcomplete
2339
4309
shellcomplete.shellcomplete(context)
2342
class cmd_fetch(Command):
2343
"""Copy in history from another branch but don't merge it.
2345
This is an internal method used for pull and merge."""
2347
takes_args = ['from_branch', 'to_branch']
2348
def run(self, from_branch, to_branch):
2349
from bzrlib.fetch import Fetcher
2350
from_b = Branch.open(from_branch)
2351
to_b = Branch.open(to_branch)
2352
Fetcher(to_b, from_b)
2355
4312
class cmd_missing(Command):
2356
"""Show unmerged/unpulled revisions between two branches.
2358
OTHER_BRANCH may be local or remote."""
4313
__doc__ = """Show unmerged/unpulled revisions between two branches.
4315
OTHER_BRANCH may be local or remote.
4317
To filter on a range of revisions, you can use the command -r begin..end
4318
-r revision requests a specific revision, -r ..end or -r begin.. are
4322
1 - some missing revisions
4323
0 - no missing revisions
4327
Determine the missing revisions between this and the branch at the
4328
remembered pull location::
4332
Determine the missing revisions between this and another branch::
4334
bzr missing http://server/branch
4336
Determine the missing revisions up to a specific revision on the other
4339
bzr missing -r ..-10
4341
Determine the missing revisions up to a specific revision on this
4344
bzr missing --my-revision ..-10
4347
_see_also = ['merge', 'pull']
2359
4348
takes_args = ['other_branch?']
2360
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2362
'Display changes in the local branch only'),
2363
Option('theirs-only',
2364
'Display changes in the remote branch only'),
4351
Option('reverse', 'Reverse the order of revisions.'),
4353
'Display changes in the local branch only.'),
4354
Option('this' , 'Same as --mine-only.'),
4355
Option('theirs-only',
4356
'Display changes in the remote branch only.'),
4357
Option('other', 'Same as --theirs-only.'),
4361
custom_help('revision',
4362
help='Filter on other branch revisions (inclusive). '
4363
'See "help revisionspec" for details.'),
4364
Option('my-revision',
4365
type=_parse_revision_str,
4366
help='Filter on local branch revisions (inclusive). '
4367
'See "help revisionspec" for details.'),
4368
Option('include-merges',
4369
'Show all revisions in addition to the mainline ones.'),
2372
4371
encoding_type = 'replace'
2374
4373
@display_command
2375
4374
def run(self, other_branch=None, reverse=False, mine_only=False,
2376
theirs_only=False, log_format=None, long=False, short=False, line=False,
2377
show_ids=False, verbose=False):
2378
from bzrlib.missing import find_unmerged, iter_log_data
2379
from bzrlib.log import log_formatter
2380
local_branch = Branch.open_containing(u".")[0]
4376
log_format=None, long=False, short=False, line=False,
4377
show_ids=False, verbose=False, this=False, other=False,
4378
include_merges=False, revision=None, my_revision=None,
4380
from bzrlib.missing import find_unmerged, iter_log_revisions
4389
# TODO: We should probably check that we don't have mine-only and
4390
# theirs-only set, but it gets complicated because we also have
4391
# this and other which could be used.
4398
local_branch = Branch.open_containing(directory)[0]
4399
self.add_cleanup(local_branch.lock_read().unlock)
2381
4401
parent = local_branch.get_parent()
2382
4402
if other_branch is None:
2383
4403
other_branch = parent
2384
4404
if other_branch is None:
2385
raise BzrCommandError("No missing location known or specified.")
2386
print "Using last location: " + local_branch.get_parent()
4405
raise errors.BzrCommandError("No peer location known"
4407
display_url = urlutils.unescape_for_display(parent,
4409
message("Using saved parent location: "
4410
+ display_url + "\n")
2387
4412
remote_branch = Branch.open(other_branch)
2388
4413
if remote_branch.base == local_branch.base:
2389
4414
remote_branch = local_branch
2390
local_branch.lock_read()
2392
remote_branch.lock_read()
2394
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2395
if (log_format == None):
2396
default = local_branch.get_config().log_format()
2397
log_format = get_log_format(long=long, short=short,
2398
line=line, default=default)
2399
lf = log_formatter(log_format,
2402
show_timezone='original')
2403
if reverse is False:
2404
local_extra.reverse()
2405
remote_extra.reverse()
2406
if local_extra and not theirs_only:
2407
print "You have %d extra revision(s):" % len(local_extra)
2408
for data in iter_log_data(local_extra, local_branch.repository,
2411
printed_local = True
2413
printed_local = False
2414
if remote_extra and not mine_only:
2415
if printed_local is True:
2417
print "You are missing %d revision(s):" % len(remote_extra)
2418
for data in iter_log_data(remote_extra, remote_branch.repository,
2421
if not remote_extra and not local_extra:
2423
print "Branches are up to date."
2427
remote_branch.unlock()
2429
local_branch.unlock()
4416
self.add_cleanup(remote_branch.lock_read().unlock)
4418
local_revid_range = _revision_range_to_revid_range(
4419
_get_revision_range(my_revision, local_branch,
4422
remote_revid_range = _revision_range_to_revid_range(
4423
_get_revision_range(revision,
4424
remote_branch, self.name()))
4426
local_extra, remote_extra = find_unmerged(
4427
local_branch, remote_branch, restrict,
4428
backward=not reverse,
4429
include_merges=include_merges,
4430
local_revid_range=local_revid_range,
4431
remote_revid_range=remote_revid_range)
4433
if log_format is None:
4434
registry = log.log_formatter_registry
4435
log_format = registry.get_default(local_branch)
4436
lf = log_format(to_file=self.outf,
4438
show_timezone='original')
4441
if local_extra and not theirs_only:
4442
message("You have %d extra revision(s):\n" %
4444
for revision in iter_log_revisions(local_extra,
4445
local_branch.repository,
4447
lf.log_revision(revision)
4448
printed_local = True
4451
printed_local = False
4453
if remote_extra and not mine_only:
4454
if printed_local is True:
4456
message("You are missing %d revision(s):\n" %
4458
for revision in iter_log_revisions(remote_extra,
4459
remote_branch.repository,
4461
lf.log_revision(revision)
4464
if mine_only and not local_extra:
4465
# We checked local, and found nothing extra
4466
message('This branch is up to date.\n')
4467
elif theirs_only and not remote_extra:
4468
# We checked remote, and found nothing extra
4469
message('Other branch is up to date.\n')
4470
elif not (mine_only or theirs_only or local_extra or
4472
# We checked both branches, and neither one had extra
4474
message("Branches are up to date.\n")
2430
4476
if not status_code and parent is None and other_branch is not None:
2431
local_branch.lock_write()
2433
# handle race conditions - a parent might be set while we run.
2434
if local_branch.get_parent() is None:
2435
local_branch.set_parent(remote_branch.base)
2437
local_branch.unlock()
4477
self.add_cleanup(local_branch.lock_write().unlock)
4478
# handle race conditions - a parent might be set while we run.
4479
if local_branch.get_parent() is None:
4480
local_branch.set_parent(remote_branch.base)
2438
4481
return status_code
4484
class cmd_pack(Command):
4485
__doc__ = """Compress the data within a repository.
4487
This operation compresses the data within a bazaar repository. As
4488
bazaar supports automatic packing of repository, this operation is
4489
normally not required to be done manually.
4491
During the pack operation, bazaar takes a backup of existing repository
4492
data, i.e. pack files. This backup is eventually removed by bazaar
4493
automatically when it is safe to do so. To save disk space by removing
4494
the backed up pack files, the --clean-obsolete-packs option may be
4497
Warning: If you use --clean-obsolete-packs and your machine crashes
4498
during or immediately after repacking, you may be left with a state
4499
where the deletion has been written to disk but the new packs have not
4500
been. In this case the repository may be unusable.
4503
_see_also = ['repositories']
4504
takes_args = ['branch_or_repo?']
4506
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4509
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4510
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4512
branch = dir.open_branch()
4513
repository = branch.repository
4514
except errors.NotBranchError:
4515
repository = dir.open_repository()
4516
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
2441
4519
class cmd_plugins(Command):
4520
__doc__ = """List the installed plugins.
4522
This command displays the list of installed plugins including
4523
version of plugin and a short description of each.
4525
--verbose shows the path where each plugin is located.
4527
A plugin is an external component for Bazaar that extends the
4528
revision control system, by adding or replacing code in Bazaar.
4529
Plugins can do a variety of things, including overriding commands,
4530
adding new commands, providing additional network transports and
4531
customizing log output.
4533
See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4534
for further information on plugins including where to find them and how to
4535
install them. Instructions are also provided there on how to write new
4536
plugins using the Python programming language.
4538
takes_options = ['verbose']
2444
4540
@display_command
4541
def run(self, verbose=False):
2446
4542
import bzrlib.plugin
2447
4543
from inspect import getdoc
2448
for name, plugin in bzrlib.plugin.all_plugins().items():
2449
if hasattr(plugin, '__path__'):
2450
print plugin.__path__[0]
2451
elif hasattr(plugin, '__file__'):
2452
print plugin.__file__
4545
for name, plugin in bzrlib.plugin.plugins().items():
4546
version = plugin.__version__
4547
if version == 'unknown':
4549
name_ver = '%s %s' % (name, version)
4550
d = getdoc(plugin.module)
2458
print '\t', d.split('\n')[0]
4552
doc = d.split('\n')[0]
4554
doc = '(no description)'
4555
result.append((name_ver, doc, plugin.path()))
4556
for name_ver, doc, path in sorted(result):
4557
self.outf.write("%s\n" % name_ver)
4558
self.outf.write(" %s\n" % doc)
4560
self.outf.write(" %s\n" % path)
4561
self.outf.write("\n")
2461
4564
class cmd_testament(Command):
2462
"""Show testament (signing-form) of a revision."""
2463
takes_options = ['revision', 'long',
2464
Option('strict', help='Produce a strict-format'
4565
__doc__ = """Show testament (signing-form) of a revision."""
4568
Option('long', help='Produce long-format testament.'),
4570
help='Produce a strict-format testament.')]
2466
4571
takes_args = ['branch?']
2467
4572
@display_command
2468
4573
def run(self, branch=u'.', revision=None, long=False, strict=False):
2642
4813
b = control.open_branch()
4815
if tree is not None:
4816
self.add_cleanup(tree.lock_write().unlock)
4818
self.add_cleanup(b.lock_write().unlock)
4819
return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4821
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4822
from bzrlib.log import log_formatter, show_log
4823
from bzrlib.uncommit import uncommit
4825
last_revno, last_rev_id = b.last_revision_info()
2644
4828
if revision is None:
2646
rev_id = b.last_revision()
4830
rev_id = last_rev_id
2648
revno, rev_id = revision[0].in_history(b)
2650
print 'No revisions to uncommit.'
2652
for r in range(revno, b.revno()+1):
2653
rev_id = b.get_rev_id(r)
2654
lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
2655
lf.show(r, b.repository.get_revision(rev_id), None)
4832
# 'bzr uncommit -r 10' actually means uncommit
4833
# so that the final tree is at revno 10.
4834
# but bzrlib.uncommit.uncommit() actually uncommits
4835
# the revisions that are supplied.
4836
# So we need to offset it by one
4837
revno = revision[0].in_history(b).revno + 1
4838
if revno <= last_revno:
4839
rev_id = b.get_rev_id(revno)
4841
if rev_id is None or _mod_revision.is_null(rev_id):
4842
self.outf.write('No revisions to uncommit.\n')
4845
lf = log_formatter('short',
4847
show_timezone='original')
4852
direction='forward',
4853
start_revision=revno,
4854
end_revision=last_revno)
2658
print 'Dry-run, pretending to remove the above revisions.'
2660
val = raw_input('Press <enter> to continue')
4857
self.outf.write('Dry-run, pretending to remove'
4858
' the above revisions.\n')
2662
print 'The above revision(s) will be removed.'
2664
val = raw_input('Are you sure [y/N]? ')
2665
if val.lower() not in ('y', 'yes'):
4860
self.outf.write('The above revision(s) will be removed.\n')
4863
if not ui.ui_factory.confirm_action(
4864
'Uncommit these revisions',
4865
'bzrlib.builtins.uncommit',
4867
self.outf.write('Canceled\n')
4870
mutter('Uncommitting from {%s} to {%s}',
4871
last_rev_id, rev_id)
2669
4872
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4873
revno=revno, local=local)
4874
self.outf.write('You can restore the old tip by running:\n'
4875
' bzr pull . -r revid:%s\n' % last_rev_id)
2673
4878
class cmd_break_lock(Command):
2674
"""Break a dead lock on a repository, branch or working directory.
4879
__doc__ = """Break a dead lock.
4881
This command breaks a lock on a repository, branch, working directory or
2676
4884
CAUTION: Locks should only be broken when you are sure that the process
2677
4885
holding the lock has been stopped.
2679
You can get information on what locks are open via the 'bzr info' command.
4887
You can get information on what locks are open via the 'bzr info
4888
[location]' command.
4892
bzr break-lock bzr+ssh://example.com/bzr/foo
4893
bzr break-lock --conf ~/.bazaar
2684
4896
takes_args = ['location?']
4899
help='LOCATION is the directory where the config lock is.'),
4901
help='Do not ask for confirmation before breaking the lock.'),
2686
def run(self, location=None, show=False):
4904
def run(self, location=None, config=False, force=False):
2687
4905
if location is None:
2688
4906
location = u'.'
2689
control, relpath = bzrdir.BzrDir.open_containing(location)
2691
control.break_lock()
2692
except NotImplementedError:
2697
# command-line interpretation helper for merge-related commands
2698
def merge(other_revision, base_revision,
2699
check_clean=True, ignore_zero=False,
2700
this_dir=None, backup_files=False, merge_type=Merge3Merger,
2701
file_list=None, show_base=False, reprocess=False,
2702
pb=DummyProgress()):
2703
"""Merge changes into a tree.
2706
list(path, revno) Base for three-way merge.
2707
If [None, None] then a base will be automatically determined.
2709
list(path, revno) Other revision for three-way merge.
2711
Directory to merge changes into; '.' by default.
2713
If true, this_dir must have no uncommitted changes before the
2715
ignore_zero - If true, suppress the "zero conflicts" message when
2716
there are no conflicts; should be set when doing something we expect
2717
to complete perfectly.
2718
file_list - If supplied, merge only changes to selected files.
2720
All available ancestors of other_revision and base_revision are
2721
automatically pulled into the branch.
2723
The revno may be -1 to indicate the last revision on the branch, which is
2726
This function is intended for use from the command line; programmatic
2727
clients might prefer to call merge.merge_inner(), which has less magic
2730
from bzrlib.merge import Merger
2731
if this_dir is None:
2733
this_tree = WorkingTree.open_containing(this_dir)[0]
2734
if show_base and not merge_type is Merge3Merger:
2735
raise BzrCommandError("Show-base is not supported for this merge"
2736
" type. %s" % merge_type)
2737
if reprocess and not merge_type.supports_reprocess:
2738
raise BzrCommandError("Conflict reduction is not supported for merge"
2739
" type %s." % merge_type)
2740
if reprocess and show_base:
2741
raise BzrCommandError("Cannot do conflict reduction and show base.")
2743
merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2744
merger.pp = ProgressPhase("Merge phase", 5, pb)
2745
merger.pp.next_phase()
2746
merger.check_basis(check_clean)
2747
merger.set_other(other_revision)
2748
merger.pp.next_phase()
2749
merger.set_base(base_revision)
2750
if merger.base_rev_id == merger.other_rev_id:
2751
note('Nothing to do.')
2753
merger.backup_files = backup_files
2754
merger.merge_type = merge_type
2755
merger.set_interesting_files(file_list)
2756
merger.show_base = show_base
2757
merger.reprocess = reprocess
2758
conflicts = merger.do_merge()
2759
if file_list is None:
2760
merger.set_pending()
2766
# these get imported and then picked up by the scan for cmd_*
2767
# TODO: Some more consistent way to split command definitions across files;
2768
# we do need to load at least some information about them to know of
2769
# aliases. ideally we would avoid loading the implementation until the
2770
# details were needed.
2771
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2772
from bzrlib.bundle.commands import cmd_bundle_revisions
2773
from bzrlib.sign_my_commits import cmd_sign_my_commits
2774
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
2775
cmd_weave_plan_merge, cmd_weave_merge_text
4908
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
4910
{'bzrlib.lockdir.break': True})
4912
conf = _mod_config.LockableConfig(file_name=location)
4915
control, relpath = bzrdir.BzrDir.open_containing(location)
4917
control.break_lock()
4918
except NotImplementedError:
4922
class cmd_wait_until_signalled(Command):
4923
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4925
This just prints a line to signal when it is ready, then blocks on stdin.
4931
sys.stdout.write("running\n")
4933
sys.stdin.readline()
4936
class cmd_serve(Command):
4937
__doc__ = """Run the bzr server."""
4939
aliases = ['server']
4943
help='Serve on stdin/out for use from inetd or sshd.'),
4944
RegistryOption('protocol',
4945
help="Protocol to serve.",
4946
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4947
value_switches=True),
4949
help='Listen for connections on nominated port of the form '
4950
'[hostname:]portnumber. Passing 0 as the port number will '
4951
'result in a dynamically allocated port. The default port '
4952
'depends on the protocol.',
4954
custom_help('directory',
4955
help='Serve contents of this directory.'),
4956
Option('allow-writes',
4957
help='By default the server is a readonly server. Supplying '
4958
'--allow-writes enables write access to the contents of '
4959
'the served directory and below. Note that ``bzr serve`` '
4960
'does not perform authentication, so unless some form of '
4961
'external authentication is arranged supplying this '
4962
'option leads to global uncontrolled write access to your '
4967
def get_host_and_port(self, port):
4968
"""Return the host and port to run the smart server on.
4970
If 'port' is None, None will be returned for the host and port.
4972
If 'port' has a colon in it, the string before the colon will be
4973
interpreted as the host.
4975
:param port: A string of the port to run the server on.
4976
:return: A tuple of (host, port), where 'host' is a host name or IP,
4977
and port is an integer TCP/IP port.
4980
if port is not None:
4982
host, port = port.split(':')
4986
def run(self, port=None, inet=False, directory=None, allow_writes=False,
4988
from bzrlib import transport
4989
if directory is None:
4990
directory = os.getcwd()
4991
if protocol is None:
4992
protocol = transport.transport_server_registry.get()
4993
host, port = self.get_host_and_port(port)
4994
url = urlutils.local_path_to_url(directory)
4995
if not allow_writes:
4996
url = 'readonly+' + url
4997
t = transport.get_transport(url)
4998
protocol(t, host, port, inet)
5001
class cmd_join(Command):
5002
__doc__ = """Combine a tree into its containing tree.
5004
This command requires the target tree to be in a rich-root format.
5006
The TREE argument should be an independent tree, inside another tree, but
5007
not part of it. (Such trees can be produced by "bzr split", but also by
5008
running "bzr branch" with the target inside a tree.)
5010
The result is a combined tree, with the subtree no longer an independent
5011
part. This is marked as a merge of the subtree into the containing tree,
5012
and all history is preserved.
5015
_see_also = ['split']
5016
takes_args = ['tree']
5018
Option('reference', help='Join by reference.', hidden=True),
5021
def run(self, tree, reference=False):
5022
sub_tree = WorkingTree.open(tree)
5023
parent_dir = osutils.dirname(sub_tree.basedir)
5024
containing_tree = WorkingTree.open_containing(parent_dir)[0]
5025
repo = containing_tree.branch.repository
5026
if not repo.supports_rich_root():
5027
raise errors.BzrCommandError(
5028
"Can't join trees because %s doesn't support rich root data.\n"
5029
"You can use bzr upgrade on the repository."
5033
containing_tree.add_reference(sub_tree)
5034
except errors.BadReferenceTarget, e:
5035
# XXX: Would be better to just raise a nicely printable
5036
# exception from the real origin. Also below. mbp 20070306
5037
raise errors.BzrCommandError("Cannot join %s. %s" %
5041
containing_tree.subsume(sub_tree)
5042
except errors.BadSubsumeSource, e:
5043
raise errors.BzrCommandError("Cannot join %s. %s" %
5047
class cmd_split(Command):
5048
__doc__ = """Split a subdirectory of a tree into a separate tree.
5050
This command will produce a target tree in a format that supports
5051
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
5052
converted into earlier formats like 'dirstate-tags'.
5054
The TREE argument should be a subdirectory of a working tree. That
5055
subdirectory will be converted into an independent tree, with its own
5056
branch. Commits in the top-level tree will not apply to the new subtree.
5059
_see_also = ['join']
5060
takes_args = ['tree']
5062
def run(self, tree):
5063
containing_tree, subdir = WorkingTree.open_containing(tree)
5064
sub_id = containing_tree.path2id(subdir)
5066
raise errors.NotVersionedError(subdir)
5068
containing_tree.extract(sub_id)
5069
except errors.RootNotRich:
5070
raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
5073
class cmd_merge_directive(Command):
5074
__doc__ = """Generate a merge directive for auto-merge tools.
5076
A directive requests a merge to be performed, and also provides all the
5077
information necessary to do so. This means it must either include a
5078
revision bundle, or the location of a branch containing the desired
5081
A submit branch (the location to merge into) must be supplied the first
5082
time the command is issued. After it has been supplied once, it will
5083
be remembered as the default.
5085
A public branch is optional if a revision bundle is supplied, but required
5086
if --diff or --plain is specified. It will be remembered as the default
5087
after the first use.
5090
takes_args = ['submit_branch?', 'public_branch?']
5094
_see_also = ['send']
5098
RegistryOption.from_kwargs('patch-type',
5099
'The type of patch to include in the directive.',
5101
value_switches=True,
5103
bundle='Bazaar revision bundle (default).',
5104
diff='Normal unified diff.',
5105
plain='No patch, just directive.'),
5106
Option('sign', help='GPG-sign the directive.'), 'revision',
5107
Option('mail-to', type=str,
5108
help='Instead of printing the directive, email to this address.'),
5109
Option('message', type=str, short_name='m',
5110
help='Message to use when committing this merge.')
5113
encoding_type = 'exact'
5115
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5116
sign=False, revision=None, mail_to=None, message=None,
5118
from bzrlib.revision import ensure_null, NULL_REVISION
5119
include_patch, include_bundle = {
5120
'plain': (False, False),
5121
'diff': (True, False),
5122
'bundle': (True, True),
5124
branch = Branch.open(directory)
5125
stored_submit_branch = branch.get_submit_branch()
5126
if submit_branch is None:
5127
submit_branch = stored_submit_branch
5129
if stored_submit_branch is None:
5130
branch.set_submit_branch(submit_branch)
5131
if submit_branch is None:
5132
submit_branch = branch.get_parent()
5133
if submit_branch is None:
5134
raise errors.BzrCommandError('No submit branch specified or known')
5136
stored_public_branch = branch.get_public_branch()
5137
if public_branch is None:
5138
public_branch = stored_public_branch
5139
elif stored_public_branch is None:
5140
branch.set_public_branch(public_branch)
5141
if not include_bundle and public_branch is None:
5142
raise errors.BzrCommandError('No public branch specified or'
5144
base_revision_id = None
5145
if revision is not None:
5146
if len(revision) > 2:
5147
raise errors.BzrCommandError('bzr merge-directive takes '
5148
'at most two one revision identifiers')
5149
revision_id = revision[-1].as_revision_id(branch)
5150
if len(revision) == 2:
5151
base_revision_id = revision[0].as_revision_id(branch)
5153
revision_id = branch.last_revision()
5154
revision_id = ensure_null(revision_id)
5155
if revision_id == NULL_REVISION:
5156
raise errors.BzrCommandError('No revisions to bundle.')
5157
directive = merge_directive.MergeDirective2.from_objects(
5158
branch.repository, revision_id, time.time(),
5159
osutils.local_time_offset(), submit_branch,
5160
public_branch=public_branch, include_patch=include_patch,
5161
include_bundle=include_bundle, message=message,
5162
base_revision_id=base_revision_id)
5165
self.outf.write(directive.to_signed(branch))
5167
self.outf.writelines(directive.to_lines())
5169
message = directive.to_email(mail_to, branch, sign)
5170
s = SMTPConnection(branch.get_config())
5171
s.send_email(message)
5174
class cmd_send(Command):
5175
__doc__ = """Mail or create a merge-directive for submitting changes.
5177
A merge directive provides many things needed for requesting merges:
5179
* A machine-readable description of the merge to perform
5181
* An optional patch that is a preview of the changes requested
5183
* An optional bundle of revision data, so that the changes can be applied
5184
directly from the merge directive, without retrieving data from a
5187
`bzr send` creates a compact data set that, when applied using bzr
5188
merge, has the same effect as merging from the source branch.
5190
By default the merge directive is self-contained and can be applied to any
5191
branch containing submit_branch in its ancestory without needing access to
5194
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5195
revisions, but only a structured request to merge from the
5196
public_location. In that case the public_branch is needed and it must be
5197
up-to-date and accessible to the recipient. The public_branch is always
5198
included if known, so that people can check it later.
5200
The submit branch defaults to the parent of the source branch, but can be
5201
overridden. Both submit branch and public branch will be remembered in
5202
branch.conf the first time they are used for a particular branch. The
5203
source branch defaults to that containing the working directory, but can
5204
be changed using --from.
5206
In order to calculate those changes, bzr must analyse the submit branch.
5207
Therefore it is most efficient for the submit branch to be a local mirror.
5208
If a public location is known for the submit_branch, that location is used
5209
in the merge directive.
5211
The default behaviour is to send the merge directive by mail, unless -o is
5212
given, in which case it is sent to a file.
5214
Mail is sent using your preferred mail program. This should be transparent
5215
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
5216
If the preferred client can't be found (or used), your editor will be used.
5218
To use a specific mail program, set the mail_client configuration option.
5219
(For Thunderbird 1.5, this works around some bugs.) Supported values for
5220
specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5221
Mail.app), "mutt", and "thunderbird"; generic options are "default",
5222
"editor", "emacsclient", "mapi", and "xdg-email". Plugins may also add
5225
If mail is being sent, a to address is required. This can be supplied
5226
either on the commandline, by setting the submit_to configuration
5227
option in the branch itself or the child_submit_to configuration option
5228
in the submit branch.
5230
Two formats are currently supported: "4" uses revision bundle format 4 and
5231
merge directive format 2. It is significantly faster and smaller than
5232
older formats. It is compatible with Bazaar 0.19 and later. It is the
5233
default. "0.9" uses revision bundle format 0.9 and merge directive
5234
format 1. It is compatible with Bazaar 0.12 - 0.18.
5236
The merge directives created by bzr send may be applied using bzr merge or
5237
bzr pull by specifying a file containing a merge directive as the location.
5239
bzr send makes extensive use of public locations to map local locations into
5240
URLs that can be used by other people. See `bzr help configuration` to
5241
set them, and use `bzr info` to display them.
5244
encoding_type = 'exact'
5246
_see_also = ['merge', 'pull']
5248
takes_args = ['submit_branch?', 'public_branch?']
5252
help='Do not include a bundle in the merge directive.'),
5253
Option('no-patch', help='Do not include a preview patch in the merge'
5256
help='Remember submit and public branch.'),
5258
help='Branch to generate the submission from, '
5259
'rather than the one containing the working directory.',
5262
Option('output', short_name='o',
5263
help='Write merge directive to this file or directory; '
5264
'use - for stdout.',
5267
help='Refuse to send if there are uncommitted changes in'
5268
' the working tree, --no-strict disables the check.'),
5269
Option('mail-to', help='Mail the request to this address.',
5273
Option('body', help='Body for the email.', type=unicode),
5274
RegistryOption('format',
5275
help='Use the specified output format.',
5276
lazy_registry=('bzrlib.send', 'format_registry')),
5279
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5280
no_patch=False, revision=None, remember=False, output=None,
5281
format=None, mail_to=None, message=None, body=None,
5282
strict=None, **kwargs):
5283
from bzrlib.send import send
5284
return send(submit_branch, revision, public_branch, remember,
5285
format, no_bundle, no_patch, output,
5286
kwargs.get('from', '.'), mail_to, message, body,
5291
class cmd_bundle_revisions(cmd_send):
5292
__doc__ = """Create a merge-directive for submitting changes.
5294
A merge directive provides many things needed for requesting merges:
5296
* A machine-readable description of the merge to perform
5298
* An optional patch that is a preview of the changes requested
5300
* An optional bundle of revision data, so that the changes can be applied
5301
directly from the merge directive, without retrieving data from a
5304
If --no-bundle is specified, then public_branch is needed (and must be
5305
up-to-date), so that the receiver can perform the merge using the
5306
public_branch. The public_branch is always included if known, so that
5307
people can check it later.
5309
The submit branch defaults to the parent, but can be overridden. Both
5310
submit branch and public branch will be remembered if supplied.
5312
If a public_branch is known for the submit_branch, that public submit
5313
branch is used in the merge instructions. This means that a local mirror
5314
can be used as your actual submit branch, once you have set public_branch
5317
Two formats are currently supported: "4" uses revision bundle format 4 and
5318
merge directive format 2. It is significantly faster and smaller than
5319
older formats. It is compatible with Bazaar 0.19 and later. It is the
5320
default. "0.9" uses revision bundle format 0.9 and merge directive
5321
format 1. It is compatible with Bazaar 0.12 - 0.18.
5326
help='Do not include a bundle in the merge directive.'),
5327
Option('no-patch', help='Do not include a preview patch in the merge'
5330
help='Remember submit and public branch.'),
5332
help='Branch to generate the submission from, '
5333
'rather than the one containing the working directory.',
5336
Option('output', short_name='o', help='Write directive to this file.',
5339
help='Refuse to bundle revisions if there are uncommitted'
5340
' changes in the working tree, --no-strict disables the check.'),
5342
RegistryOption('format',
5343
help='Use the specified output format.',
5344
lazy_registry=('bzrlib.send', 'format_registry')),
5346
aliases = ['bundle']
5348
_see_also = ['send', 'merge']
5352
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5353
no_patch=False, revision=None, remember=False, output=None,
5354
format=None, strict=None, **kwargs):
5357
from bzrlib.send import send
5358
return send(submit_branch, revision, public_branch, remember,
5359
format, no_bundle, no_patch, output,
5360
kwargs.get('from', '.'), None, None, None,
5361
self.outf, strict=strict)
5364
class cmd_tag(Command):
5365
__doc__ = """Create, remove or modify a tag naming a revision.
5367
Tags give human-meaningful names to revisions. Commands that take a -r
5368
(--revision) option can be given -rtag:X, where X is any previously
5371
Tags are stored in the branch. Tags are copied from one branch to another
5372
along when you branch, push, pull or merge.
5374
It is an error to give a tag name that already exists unless you pass
5375
--force, in which case the tag is moved to point to the new revision.
5377
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5378
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5380
If no tag name is specified it will be determined through the
5381
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5382
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5386
_see_also = ['commit', 'tags']
5387
takes_args = ['tag_name?']
5390
help='Delete this tag rather than placing it.',
5392
custom_help('directory',
5393
help='Branch in which to place the tag.'),
5395
help='Replace existing tags.',
5400
def run(self, tag_name=None,
5406
branch, relpath = Branch.open_containing(directory)
5407
self.add_cleanup(branch.lock_write().unlock)
5409
if tag_name is None:
5410
raise errors.BzrCommandError("No tag specified to delete.")
5411
branch.tags.delete_tag(tag_name)
5412
note('Deleted tag %s.' % tag_name)
5415
if len(revision) != 1:
5416
raise errors.BzrCommandError(
5417
"Tags can only be placed on a single revision, "
5419
revision_id = revision[0].as_revision_id(branch)
5421
revision_id = branch.last_revision()
5422
if tag_name is None:
5423
tag_name = branch.automatic_tag_name(revision_id)
5424
if tag_name is None:
5425
raise errors.BzrCommandError(
5426
"Please specify a tag name.")
5427
if (not force) and branch.tags.has_tag(tag_name):
5428
raise errors.TagAlreadyExists(tag_name)
5429
branch.tags.set_tag(tag_name, revision_id)
5430
note('Created tag %s.' % tag_name)
5433
class cmd_tags(Command):
5434
__doc__ = """List tags.
5436
This command shows a table of tag names and the revisions they reference.
5441
custom_help('directory',
5442
help='Branch whose tags should be displayed.'),
5443
RegistryOption.from_kwargs('sort',
5444
'Sort tags by different criteria.', title='Sorting',
5445
natural='Sort numeric substrings as numbers:'
5446
' suitable for version numbers. (default)',
5447
alpha='Sort tags lexicographically.',
5448
time='Sort tags chronologically.',
5461
branch, relpath = Branch.open_containing(directory)
5463
tags = branch.tags.get_tag_dict().items()
5467
self.add_cleanup(branch.lock_read().unlock)
5469
graph = branch.repository.get_graph()
5470
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5471
revid1, revid2 = rev1.rev_id, rev2.rev_id
5472
# only show revisions between revid1 and revid2 (inclusive)
5473
tags = [(tag, revid) for tag, revid in tags if
5474
graph.is_between(revid, revid1, revid2)]
5475
if sort == 'natural':
5476
def natural_sort_key(tag):
5477
return [f(s) for f,s in
5478
zip(itertools.cycle((unicode.lower,int)),
5479
re.split('([0-9]+)', tag[0]))]
5480
tags.sort(key=natural_sort_key)
5481
elif sort == 'alpha':
5483
elif sort == 'time':
5485
for tag, revid in tags:
5487
revobj = branch.repository.get_revision(revid)
5488
except errors.NoSuchRevision:
5489
timestamp = sys.maxint # place them at the end
5491
timestamp = revobj.timestamp
5492
timestamps[revid] = timestamp
5493
tags.sort(key=lambda x: timestamps[x[1]])
5495
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5496
for index, (tag, revid) in enumerate(tags):
5498
revno = branch.revision_id_to_dotted_revno(revid)
5499
if isinstance(revno, tuple):
5500
revno = '.'.join(map(str, revno))
5501
except errors.NoSuchRevision:
5502
# Bad tag data/merges can lead to tagged revisions
5503
# which are not in this branch. Fail gracefully ...
5505
tags[index] = (tag, revno)
5507
for tag, revspec in tags:
5508
self.outf.write('%-20s %s\n' % (tag, revspec))
5511
class cmd_reconfigure(Command):
5512
__doc__ = """Reconfigure the type of a bzr directory.
5514
A target configuration must be specified.
5516
For checkouts, the bind-to location will be auto-detected if not specified.
5517
The order of preference is
5518
1. For a lightweight checkout, the current bound location.
5519
2. For branches that used to be checkouts, the previously-bound location.
5520
3. The push location.
5521
4. The parent location.
5522
If none of these is available, --bind-to must be specified.
5525
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5526
takes_args = ['location?']
5528
RegistryOption.from_kwargs(
5530
title='Target type',
5531
help='The type to reconfigure the directory to.',
5532
value_switches=True, enum_switch=False,
5533
branch='Reconfigure to be an unbound branch with no working tree.',
5534
tree='Reconfigure to be an unbound branch with a working tree.',
5535
checkout='Reconfigure to be a bound branch with a working tree.',
5536
lightweight_checkout='Reconfigure to be a lightweight'
5537
' checkout (with no local history).',
5538
standalone='Reconfigure to be a standalone branch '
5539
'(i.e. stop using shared repository).',
5540
use_shared='Reconfigure to use a shared repository.',
5541
with_trees='Reconfigure repository to create '
5542
'working trees on branches by default.',
5543
with_no_trees='Reconfigure repository to not create '
5544
'working trees on branches by default.'
5546
Option('bind-to', help='Branch to bind checkout to.', type=str),
5548
help='Perform reconfiguration even if local changes'
5550
Option('stacked-on',
5551
help='Reconfigure a branch to be stacked on another branch.',
5555
help='Reconfigure a branch to be unstacked. This '
5556
'may require copying substantial data into it.',
5560
def run(self, location=None, target_type=None, bind_to=None, force=False,
5563
directory = bzrdir.BzrDir.open(location)
5564
if stacked_on and unstacked:
5565
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5566
elif stacked_on is not None:
5567
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5569
reconfigure.ReconfigureUnstacked().apply(directory)
5570
# At the moment you can use --stacked-on and a different
5571
# reconfiguration shape at the same time; there seems no good reason
5573
if target_type is None:
5574
if stacked_on or unstacked:
5577
raise errors.BzrCommandError('No target configuration '
5579
elif target_type == 'branch':
5580
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5581
elif target_type == 'tree':
5582
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5583
elif target_type == 'checkout':
5584
reconfiguration = reconfigure.Reconfigure.to_checkout(
5586
elif target_type == 'lightweight-checkout':
5587
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5589
elif target_type == 'use-shared':
5590
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5591
elif target_type == 'standalone':
5592
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5593
elif target_type == 'with-trees':
5594
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5596
elif target_type == 'with-no-trees':
5597
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5599
reconfiguration.apply(force)
5602
class cmd_switch(Command):
5603
__doc__ = """Set the branch of a checkout and update.
5605
For lightweight checkouts, this changes the branch being referenced.
5606
For heavyweight checkouts, this checks that there are no local commits
5607
versus the current bound branch, then it makes the local branch a mirror
5608
of the new location and binds to it.
5610
In both cases, the working tree is updated and uncommitted changes
5611
are merged. The user can commit or revert these as they desire.
5613
Pending merges need to be committed or reverted before using switch.
5615
The path to the branch to switch to can be specified relative to the parent
5616
directory of the current branch. For example, if you are currently in a
5617
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5620
Bound branches use the nickname of its master branch unless it is set
5621
locally, in which case switching will update the local nickname to be
5625
takes_args = ['to_location?']
5626
takes_options = ['directory',
5628
help='Switch even if local commits will be lost.'),
5630
Option('create-branch', short_name='b',
5631
help='Create the target branch from this one before'
5632
' switching to it.'),
5635
def run(self, to_location=None, force=False, create_branch=False,
5636
revision=None, directory=u'.'):
5637
from bzrlib import switch
5638
tree_location = directory
5639
revision = _get_one_revision('switch', revision)
5640
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5641
if to_location is None:
5642
if revision is None:
5643
raise errors.BzrCommandError('You must supply either a'
5644
' revision or a location')
5645
to_location = tree_location
5647
branch = control_dir.open_branch()
5648
had_explicit_nick = branch.get_config().has_explicit_nickname()
5649
except errors.NotBranchError:
5651
had_explicit_nick = False
5654
raise errors.BzrCommandError('cannot create branch without'
5656
to_location = directory_service.directories.dereference(
5658
if '/' not in to_location and '\\' not in to_location:
5659
# This path is meant to be relative to the existing branch
5660
this_url = self._get_branch_location(control_dir)
5661
to_location = urlutils.join(this_url, '..', to_location)
5662
to_branch = branch.bzrdir.sprout(to_location,
5663
possible_transports=[branch.bzrdir.root_transport],
5664
source_branch=branch).open_branch()
5667
to_branch = Branch.open(to_location)
5668
except errors.NotBranchError:
5669
this_url = self._get_branch_location(control_dir)
5670
to_branch = Branch.open(
5671
urlutils.join(this_url, '..', to_location))
5672
if revision is not None:
5673
revision = revision.as_revision_id(to_branch)
5674
switch.switch(control_dir, to_branch, force, revision_id=revision)
5675
if had_explicit_nick:
5676
branch = control_dir.open_branch() #get the new branch!
5677
branch.nick = to_branch.nick
5678
note('Switched to branch: %s',
5679
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5681
def _get_branch_location(self, control_dir):
5682
"""Return location of branch for this control dir."""
5684
this_branch = control_dir.open_branch()
5685
# This may be a heavy checkout, where we want the master branch
5686
master_location = this_branch.get_bound_location()
5687
if master_location is not None:
5688
return master_location
5689
# If not, use a local sibling
5690
return this_branch.base
5691
except errors.NotBranchError:
5692
format = control_dir.find_branch_format()
5693
if getattr(format, 'get_reference', None) is not None:
5694
return format.get_reference(control_dir)
5696
return control_dir.root_transport.base
5699
class cmd_view(Command):
5700
__doc__ = """Manage filtered views.
5702
Views provide a mask over the tree so that users can focus on
5703
a subset of a tree when doing their work. After creating a view,
5704
commands that support a list of files - status, diff, commit, etc -
5705
effectively have that list of files implicitly given each time.
5706
An explicit list of files can still be given but those files
5707
must be within the current view.
5709
In most cases, a view has a short life-span: it is created to make
5710
a selected change and is deleted once that change is committed.
5711
At other times, you may wish to create one or more named views
5712
and switch between them.
5714
To disable the current view without deleting it, you can switch to
5715
the pseudo view called ``off``. This can be useful when you need
5716
to see the whole tree for an operation or two (e.g. merge) but
5717
want to switch back to your view after that.
5720
To define the current view::
5722
bzr view file1 dir1 ...
5724
To list the current view::
5728
To delete the current view::
5732
To disable the current view without deleting it::
5734
bzr view --switch off
5736
To define a named view and switch to it::
5738
bzr view --name view-name file1 dir1 ...
5740
To list a named view::
5742
bzr view --name view-name
5744
To delete a named view::
5746
bzr view --name view-name --delete
5748
To switch to a named view::
5750
bzr view --switch view-name
5752
To list all views defined::
5756
To delete all views::
5758
bzr view --delete --all
5762
takes_args = ['file*']
5765
help='Apply list or delete action to all views.',
5768
help='Delete the view.',
5771
help='Name of the view to define, list or delete.',
5775
help='Name of the view to switch to.',
5780
def run(self, file_list,
5786
tree, file_list = WorkingTree.open_containing_paths(file_list,
5788
current_view, view_dict = tree.views.get_view_info()
5793
raise errors.BzrCommandError(
5794
"Both --delete and a file list specified")
5796
raise errors.BzrCommandError(
5797
"Both --delete and --switch specified")
5799
tree.views.set_view_info(None, {})
5800
self.outf.write("Deleted all views.\n")
5802
raise errors.BzrCommandError("No current view to delete")
5804
tree.views.delete_view(name)
5805
self.outf.write("Deleted '%s' view.\n" % name)
5808
raise errors.BzrCommandError(
5809
"Both --switch and a file list specified")
5811
raise errors.BzrCommandError(
5812
"Both --switch and --all specified")
5813
elif switch == 'off':
5814
if current_view is None:
5815
raise errors.BzrCommandError("No current view to disable")
5816
tree.views.set_view_info(None, view_dict)
5817
self.outf.write("Disabled '%s' view.\n" % (current_view))
5819
tree.views.set_view_info(switch, view_dict)
5820
view_str = views.view_display_str(tree.views.lookup_view())
5821
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5824
self.outf.write('Views defined:\n')
5825
for view in sorted(view_dict):
5826
if view == current_view:
5830
view_str = views.view_display_str(view_dict[view])
5831
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5833
self.outf.write('No views defined.\n')
5836
# No name given and no current view set
5839
raise errors.BzrCommandError(
5840
"Cannot change the 'off' pseudo view")
5841
tree.views.set_view(name, sorted(file_list))
5842
view_str = views.view_display_str(tree.views.lookup_view())
5843
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5847
# No name given and no current view set
5848
self.outf.write('No current view.\n')
5850
view_str = views.view_display_str(tree.views.lookup_view(name))
5851
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5854
class cmd_hooks(Command):
5855
__doc__ = """Show hooks."""
5860
for hook_key in sorted(hooks.known_hooks.keys()):
5861
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5862
self.outf.write("%s:\n" % type(some_hooks).__name__)
5863
for hook_name, hook_point in sorted(some_hooks.items()):
5864
self.outf.write(" %s:\n" % (hook_name,))
5865
found_hooks = list(hook_point)
5867
for hook in found_hooks:
5868
self.outf.write(" %s\n" %
5869
(some_hooks.get_hook_name(hook),))
5871
self.outf.write(" <no hooks installed>\n")
5874
class cmd_remove_branch(Command):
5875
__doc__ = """Remove a branch.
5877
This will remove the branch from the specified location but
5878
will keep any working tree or repository in place.
5882
Remove the branch at repo/trunk::
5884
bzr remove-branch repo/trunk
5888
takes_args = ["location?"]
5890
aliases = ["rmbranch"]
5892
def run(self, location=None):
5893
if location is None:
5895
branch = Branch.open_containing(location)[0]
5896
branch.bzrdir.destroy_branch()
5899
class cmd_shelve(Command):
5900
__doc__ = """Temporarily set aside some changes from the current tree.
5902
Shelve allows you to temporarily put changes you've made "on the shelf",
5903
ie. out of the way, until a later time when you can bring them back from
5904
the shelf with the 'unshelve' command. The changes are stored alongside
5905
your working tree, and so they aren't propagated along with your branch nor
5906
will they survive its deletion.
5908
If shelve --list is specified, previously-shelved changes are listed.
5910
Shelve is intended to help separate several sets of changes that have
5911
been inappropriately mingled. If you just want to get rid of all changes
5912
and you don't need to restore them later, use revert. If you want to
5913
shelve all text changes at once, use shelve --all.
5915
If filenames are specified, only the changes to those files will be
5916
shelved. Other files will be left untouched.
5918
If a revision is specified, changes since that revision will be shelved.
5920
You can put multiple items on the shelf, and by default, 'unshelve' will
5921
restore the most recently shelved changes.
5923
For complicated changes, it is possible to edit the changes in a separate
5924
editor program to decide what the file remaining in the working copy
5925
should look like. To do this, add the configuration option
5927
change_editor = PROGRAM @new_path @old_path
5929
where @new_path is replaced with the path of the new version of the
5930
file and @old_path is replaced with the path of the old version of
5931
the file. The PROGRAM should save the new file with the desired
5932
contents of the file in the working tree.
5936
takes_args = ['file*']
5941
Option('all', help='Shelve all changes.'),
5943
RegistryOption('writer', 'Method to use for writing diffs.',
5944
bzrlib.option.diff_writer_registry,
5945
value_switches=True, enum_switch=False),
5947
Option('list', help='List shelved changes.'),
5949
help='Destroy removed changes instead of shelving them.'),
5951
_see_also = ['unshelve', 'configuration']
5953
def run(self, revision=None, all=False, file_list=None, message=None,
5954
writer=None, list=False, destroy=False, directory=u'.'):
5956
return self.run_for_list()
5957
from bzrlib.shelf_ui import Shelver
5959
writer = bzrlib.option.diff_writer_registry.get()
5961
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5962
file_list, message, destroy=destroy, directory=directory)
5967
except errors.UserAbort:
5970
def run_for_list(self):
5971
tree = WorkingTree.open_containing('.')[0]
5972
self.add_cleanup(tree.lock_read().unlock)
5973
manager = tree.get_shelf_manager()
5974
shelves = manager.active_shelves()
5975
if len(shelves) == 0:
5976
note('No shelved changes.')
5978
for shelf_id in reversed(shelves):
5979
message = manager.get_metadata(shelf_id).get('message')
5981
message = '<no message>'
5982
self.outf.write('%3d: %s\n' % (shelf_id, message))
5986
class cmd_unshelve(Command):
5987
__doc__ = """Restore shelved changes.
5989
By default, the most recently shelved changes are restored. However if you
5990
specify a shelf by id those changes will be restored instead. This works
5991
best when the changes don't depend on each other.
5994
takes_args = ['shelf_id?']
5997
RegistryOption.from_kwargs(
5998
'action', help="The action to perform.",
5999
enum_switch=False, value_switches=True,
6000
apply="Apply changes and remove from the shelf.",
6001
dry_run="Show changes, but do not apply or remove them.",
6002
preview="Instead of unshelving the changes, show the diff that "
6003
"would result from unshelving.",
6004
delete_only="Delete changes without applying them.",
6005
keep="Apply changes but don't delete them.",
6008
_see_also = ['shelve']
6010
def run(self, shelf_id=None, action='apply', directory=u'.'):
6011
from bzrlib.shelf_ui import Unshelver
6012
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6016
unshelver.tree.unlock()
6019
class cmd_clean_tree(Command):
6020
__doc__ = """Remove unwanted files from working tree.
6022
By default, only unknown files, not ignored files, are deleted. Versioned
6023
files are never deleted.
6025
Another class is 'detritus', which includes files emitted by bzr during
6026
normal operations and selftests. (The value of these files decreases with
6029
If no options are specified, unknown files are deleted. Otherwise, option
6030
flags are respected, and may be combined.
6032
To check what clean-tree will do, use --dry-run.
6034
takes_options = ['directory',
6035
Option('ignored', help='Delete all ignored files.'),
6036
Option('detritus', help='Delete conflict files, merge'
6037
' backups, and failed selftest dirs.'),
6039
help='Delete files unknown to bzr (default).'),
6040
Option('dry-run', help='Show files to delete instead of'
6042
Option('force', help='Do not prompt before deleting.')]
6043
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6044
force=False, directory=u'.'):
6045
from bzrlib.clean_tree import clean_tree
6046
if not (unknown or ignored or detritus):
6050
clean_tree(directory, unknown=unknown, ignored=ignored,
6051
detritus=detritus, dry_run=dry_run, no_prompt=force)
6054
class cmd_reference(Command):
6055
__doc__ = """list, view and set branch locations for nested trees.
6057
If no arguments are provided, lists the branch locations for nested trees.
6058
If one argument is provided, display the branch location for that tree.
6059
If two arguments are provided, set the branch location for that tree.
6064
takes_args = ['path?', 'location?']
6066
def run(self, path=None, location=None):
6068
if path is not None:
6070
tree, branch, relpath =(
6071
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6072
if path is not None:
6075
tree = branch.basis_tree()
6077
info = branch._get_all_reference_info().iteritems()
6078
self._display_reference_info(tree, branch, info)
6080
file_id = tree.path2id(path)
6082
raise errors.NotVersionedError(path)
6083
if location is None:
6084
info = [(file_id, branch.get_reference_info(file_id))]
6085
self._display_reference_info(tree, branch, info)
6087
branch.set_reference_info(file_id, path, location)
6089
def _display_reference_info(self, tree, branch, info):
6091
for file_id, (path, location) in info:
6093
path = tree.id2path(file_id)
6094
except errors.NoSuchId:
6096
ref_list.append((path, location))
6097
for path, location in sorted(ref_list):
6098
self.outf.write('%s %s\n' % (path, location))
6101
def _register_lazy_builtins():
6102
# register lazy builtins from other modules; called at startup and should
6103
# be only called once.
6104
for (name, aliases, module_name) in [
6105
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6106
('cmd_config', [], 'bzrlib.config'),
6107
('cmd_dpush', [], 'bzrlib.foreign'),
6108
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6109
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6110
('cmd_conflicts', [], 'bzrlib.conflicts'),
6111
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6112
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6114
builtin_command_registry.register_lazy(name, aliases, module_name)