143
233
Not versioned and not matching an ignore pattern.
145
To see ignored files use 'bzr ignored'. For details in the
235
Additionally for directories, symlinks and files with a changed
236
executable bit, Bazaar indicates their type using a trailing
237
character: '/', '@' or '*' respectively. These decorations can be
238
disabled using the '--no-classify' option.
240
To see ignored files use 'bzr ignored'. For details on the
146
241
changes to file texts, use 'bzr diff'.
148
--short gives a status flags for each item, similar to the SVN's status
151
Column 1: versioning / renames
157
P Entry for a pending merge (not a file)
166
* The execute bit was changed
243
Note that --short or -S gives status flags for each item, similar
244
to Subversion's status command. To get output similar to svn -q,
168
247
If no arguments are specified, the status of the entire working
169
248
directory is shown. Otherwise, only the status of the specified
170
249
files or directories is reported. If a directory is given, status
171
250
is reported for everything inside that directory.
173
If a revision argument is given, the status is calculated against
174
that revision, or between two revisions if two are provided.
252
Before merges are committed, the pending merge tip revisions are
253
shown. To see all pending merge revisions, use the -v option.
254
To skip the display of pending merge information altogether, use
255
the no-pending option or specify a file/directory.
257
To compare the working directory to a specific revision, pass a
258
single revision to the revision argument.
260
To see which files have changed in a specific revision, or between
261
two revisions, pass a revision range to the revision argument.
262
This will produce the same results as calling 'bzr diff --summarize'.
177
265
# TODO: --no-recurse, --recurse options
179
267
takes_args = ['file*']
180
takes_options = ['show-ids', 'revision', 'short']
268
takes_options = ['show-ids', 'revision', 'change', 'verbose',
269
Option('short', help='Use short status indicators.',
271
Option('versioned', help='Only show versioned files.',
273
Option('no-pending', help='Don\'t show pending merges.',
275
Option('no-classify',
276
help='Do not mark object type using indicator.',
181
279
aliases = ['st', 'stat']
183
281
encoding_type = 'replace'
282
_see_also = ['diff', 'revert', 'status-flags']
186
def run(self, show_ids=False, file_list=None, revision=None, short=False):
285
def run(self, show_ids=False, file_list=None, revision=None, short=False,
286
versioned=False, no_pending=False, verbose=False,
187
288
from bzrlib.status import show_tree_status
189
tree, file_list = tree_files(file_list)
290
if revision and len(revision) > 2:
291
raise errors.BzrCommandError('bzr status --revision takes exactly'
292
' one or two revision specifiers')
294
tree, relfile_list = WorkingTree.open_containing_paths(file_list)
295
# Avoid asking for specific files when that is not needed.
296
if relfile_list == ['']:
298
# Don't disable pending merges for full trees other than '.'.
299
if file_list == ['.']:
301
# A specific path within a tree was given.
302
elif relfile_list is not None:
191
304
show_tree_status(tree, show_ids=show_ids,
192
specific_files=file_list, revision=revision,
305
specific_files=relfile_list, revision=revision,
306
to_file=self.outf, short=short, versioned=versioned,
307
show_pending=(not no_pending), verbose=verbose,
308
classify=not no_classify)
197
311
class cmd_cat_revision(Command):
198
"""Write out metadata for a revision.
312
__doc__ = """Write out metadata for a revision.
200
314
The revision to print can either be specified by a specific
201
315
revision identifier, or you can use --revision.
205
319
takes_args = ['revision_id?']
206
takes_options = ['revision']
320
takes_options = ['directory', 'revision']
207
321
# cat-revision is more for frontends so should be exact
208
322
encoding = 'strict'
324
def print_revision(self, revisions, revid):
325
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
326
record = stream.next()
327
if record.storage_kind == 'absent':
328
raise errors.NoSuchRevision(revisions, revid)
329
revtext = record.get_bytes_as('fulltext')
330
self.outf.write(revtext.decode('utf-8'))
211
def run(self, revision_id=None, revision=None):
333
def run(self, revision_id=None, revision=None, directory=u'.'):
213
334
if revision_id is not None and revision is not None:
214
335
raise errors.BzrCommandError('You can only supply one of'
215
336
' revision_id or --revision')
216
337
if revision_id is None and revision is None:
217
338
raise errors.BzrCommandError('You must supply either'
218
339
' --revision or a revision_id')
219
b = WorkingTree.open_containing(u'.')[0].branch
221
# TODO: jam 20060112 should cat-revision always output utf-8?
222
if revision_id is not None:
223
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
224
elif revision is not None:
227
raise errors.BzrCommandError('You cannot specify a NULL'
229
revno, rev_id = rev.in_history(b)
230
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
341
b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
343
revisions = b.repository.revisions
344
if revisions is None:
345
raise errors.BzrCommandError('Repository %r does not support '
346
'access to raw revision texts')
348
b.repository.lock_read()
350
# TODO: jam 20060112 should cat-revision always output utf-8?
351
if revision_id is not None:
352
revision_id = osutils.safe_revision_id(revision_id, warn=False)
354
self.print_revision(revisions, revision_id)
355
except errors.NoSuchRevision:
356
msg = "The repository %s contains no revision %s." % (
357
b.repository.base, revision_id)
358
raise errors.BzrCommandError(msg)
359
elif revision is not None:
362
raise errors.BzrCommandError(
363
'You cannot specify a NULL revision.')
364
rev_id = rev.as_revision_id(b)
365
self.print_revision(revisions, rev_id)
367
b.repository.unlock()
370
class cmd_dump_btree(Command):
371
__doc__ = """Dump the contents of a btree index file to stdout.
373
PATH is a btree index file, it can be any URL. This includes things like
374
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
376
By default, the tuples stored in the index file will be displayed. With
377
--raw, we will uncompress the pages, but otherwise display the raw bytes
381
# TODO: Do we want to dump the internal nodes as well?
382
# TODO: It would be nice to be able to dump the un-parsed information,
383
# rather than only going through iter_all_entries. However, this is
384
# good enough for a start
386
encoding_type = 'exact'
387
takes_args = ['path']
388
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
389
' rather than the parsed tuples.'),
392
def run(self, path, raw=False):
393
dirname, basename = osutils.split(path)
394
t = transport.get_transport(dirname)
396
self._dump_raw_bytes(t, basename)
398
self._dump_entries(t, basename)
400
def _get_index_and_bytes(self, trans, basename):
401
"""Create a BTreeGraphIndex and raw bytes."""
402
bt = btree_index.BTreeGraphIndex(trans, basename, None)
403
bytes = trans.get_bytes(basename)
404
bt._file = cStringIO.StringIO(bytes)
405
bt._size = len(bytes)
408
def _dump_raw_bytes(self, trans, basename):
411
# We need to parse at least the root node.
412
# This is because the first page of every row starts with an
413
# uncompressed header.
414
bt, bytes = self._get_index_and_bytes(trans, basename)
415
for page_idx, page_start in enumerate(xrange(0, len(bytes),
416
btree_index._PAGE_SIZE)):
417
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
418
page_bytes = bytes[page_start:page_end]
420
self.outf.write('Root node:\n')
421
header_end, data = bt._parse_header_from_bytes(page_bytes)
422
self.outf.write(page_bytes[:header_end])
424
self.outf.write('\nPage %d\n' % (page_idx,))
425
if len(page_bytes) == 0:
426
self.outf.write('(empty)\n');
428
decomp_bytes = zlib.decompress(page_bytes)
429
self.outf.write(decomp_bytes)
430
self.outf.write('\n')
432
def _dump_entries(self, trans, basename):
434
st = trans.stat(basename)
435
except errors.TransportNotPossible:
436
# We can't stat, so we'll fake it because we have to do the 'get()'
438
bt, _ = self._get_index_and_bytes(trans, basename)
440
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
441
for node in bt.iter_all_entries():
442
# Node is made up of:
443
# (index, key, value, [references])
447
refs_as_tuples = None
449
refs_as_tuples = static_tuple.as_tuples(refs)
450
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
451
self.outf.write('%s\n' % (as_tuple,))
233
454
class cmd_remove_tree(Command):
234
"""Remove the working tree from a given branch/checkout.
455
__doc__ = """Remove the working tree from a given branch/checkout.
236
457
Since a lightweight checkout is little more than a working tree
237
458
this will refuse to run against one.
240
takes_args = ['location?']
242
def run(self, location='.'):
243
d = bzrdir.BzrDir.open(location)
460
To re-create the working tree, use "bzr checkout".
462
_see_also = ['checkout', 'working-trees']
463
takes_args = ['location*']
466
help='Remove the working tree even if it has '
467
'uncommitted or shelved changes.'),
470
def run(self, location_list, force=False):
471
if not location_list:
474
for location in location_list:
475
d = bzrdir.BzrDir.open(location)
478
working = d.open_workingtree()
479
except errors.NoWorkingTree:
480
raise errors.BzrCommandError("No working tree to remove")
481
except errors.NotLocalUrl:
482
raise errors.BzrCommandError("You cannot remove the working tree"
485
if (working.has_changes()):
486
raise errors.UncommittedChanges(working)
487
if working.get_shelf_manager().last_shelf() is not None:
488
raise errors.ShelvedChanges(working)
490
if working.user_url != working.branch.user_url:
491
raise errors.BzrCommandError("You cannot remove the working tree"
492
" from a lightweight checkout")
494
d.destroy_workingtree()
497
class cmd_repair_workingtree(Command):
498
__doc__ = """Reset the working tree state file.
500
This is not meant to be used normally, but more as a way to recover from
501
filesystem corruption, etc. This rebuilds the working inventory back to a
502
'known good' state. Any new modifications (adding a file, renaming, etc)
503
will be lost, though modified files will still be detected as such.
505
Most users will want something more like "bzr revert" or "bzr update"
506
unless the state file has become corrupted.
508
By default this attempts to recover the current state by looking at the
509
headers of the state file. If the state file is too corrupted to even do
510
that, you can supply --revision to force the state of the tree.
513
takes_options = ['revision', 'directory',
515
help='Reset the tree even if it doesn\'t appear to be'
520
def run(self, revision=None, directory='.', force=False):
521
tree, _ = WorkingTree.open_containing(directory)
522
self.add_cleanup(tree.lock_tree_write().unlock)
526
except errors.BzrError:
527
pass # There seems to be a real error here, so we'll reset
530
raise errors.BzrCommandError(
531
'The tree does not appear to be corrupt. You probably'
532
' want "bzr revert" instead. Use "--force" if you are'
533
' sure you want to reset the working tree.')
537
revision_ids = [r.as_revision_id(tree.branch) for r in revision]
246
working = d.open_workingtree()
247
except errors.NoWorkingTree:
248
raise errors.BzrCommandError("No working tree to remove")
249
except errors.NotLocalUrl:
250
raise errors.BzrCommandError("You cannot remove the working tree of a "
253
working_path = working.bzrdir.root_transport.base
254
branch_path = working.branch.bzrdir.root_transport.base
255
if working_path != branch_path:
256
raise errors.BzrCommandError("You cannot remove the working tree from "
257
"a lightweight checkout")
259
d.destroy_workingtree()
539
tree.reset_state(revision_ids)
540
except errors.BzrError, e:
541
if revision_ids is None:
542
extra = (', the header appears corrupt, try passing -r -1'
543
' to set the state to the last commit')
546
raise errors.BzrCommandError('failed to reset the tree state'
262
550
class cmd_revno(Command):
263
"""Show current revision number.
551
__doc__ = """Show current revision number.
265
553
This is equal to the number of revisions on this branch.
268
557
takes_args = ['location?']
559
Option('tree', help='Show revno of working tree'),
271
def run(self, location=u'.'):
272
self.outf.write(str(Branch.open_containing(location)[0].revno()))
273
self.outf.write('\n')
563
def run(self, tree=False, location=u'.'):
566
wt = WorkingTree.open_containing(location)[0]
567
self.add_cleanup(wt.lock_read().unlock)
568
except (errors.NoWorkingTree, errors.NotLocalUrl):
569
raise errors.NoWorkingTree(location)
570
revid = wt.last_revision()
572
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
573
except errors.NoSuchRevision:
575
revno = ".".join(str(n) for n in revno_t)
577
b = Branch.open_containing(location)[0]
578
self.add_cleanup(b.lock_read().unlock)
581
self.outf.write(str(revno) + '\n')
276
584
class cmd_revision_info(Command):
277
"""Show revision number and revision id for a given revision identifier.
585
__doc__ = """Show revision number and revision id for a given revision identifier.
280
588
takes_args = ['revision_info*']
281
takes_options = ['revision']
591
custom_help('directory',
592
help='Branch to examine, '
593
'rather than the one containing the working directory.'),
594
Option('tree', help='Show revno of working tree'),
284
def run(self, revision=None, revision_info_list=[]):
598
def run(self, revision=None, directory=u'.', tree=False,
599
revision_info_list=[]):
602
wt = WorkingTree.open_containing(directory)[0]
604
self.add_cleanup(wt.lock_read().unlock)
605
except (errors.NoWorkingTree, errors.NotLocalUrl):
607
b = Branch.open_containing(directory)[0]
608
self.add_cleanup(b.lock_read().unlock)
287
610
if revision is not None:
288
revs.extend(revision)
611
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
289
612
if revision_info_list is not None:
290
for rev in revision_info_list:
291
revs.append(RevisionSpec.from_string(rev))
293
raise errors.BzrCommandError('You must supply a revision identifier')
295
b = WorkingTree.open_containing(u'.')[0].branch
298
revinfo = rev.in_history(b)
299
if revinfo.revno is None:
300
print ' %s' % revinfo.rev_id
613
for rev_str in revision_info_list:
614
rev_spec = RevisionSpec.from_string(rev_str)
615
revision_ids.append(rev_spec.as_revision_id(b))
616
# No arguments supplied, default to the last revision
617
if len(revision_ids) == 0:
620
raise errors.NoWorkingTree(directory)
621
revision_ids.append(wt.last_revision())
302
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
623
revision_ids.append(b.last_revision())
627
for revision_id in revision_ids:
629
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
630
revno = '.'.join(str(i) for i in dotted_revno)
631
except errors.NoSuchRevision:
633
maxlen = max(maxlen, len(revno))
634
revinfos.append([revno, revision_id])
638
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
305
641
class cmd_add(Command):
306
"""Add specified files or directories.
642
__doc__ = """Add specified files or directories.
308
644
In non-recursive mode, all the named items are added, regardless
309
645
of whether they were previously ignored. A warning is given if
490
844
takes_args = ['names*']
491
takes_options = [Option("after", help="move only the bzr identifier"
492
" of the file (file has already been moved). Use this flag if"
493
" bzr is not able to detect this itself.")]
845
takes_options = [Option("after", help="Move only the bzr identifier"
846
" of the file, because the file has already been moved."),
847
Option('auto', help='Automatically guess renames.'),
848
Option('dry-run', help='Avoid making changes when guessing renames.'),
494
850
aliases = ['move', 'rename']
495
851
encoding_type = 'replace'
497
def run(self, names_list, after=False):
853
def run(self, names_list, after=False, auto=False, dry_run=False):
855
return self.run_auto(names_list, after, dry_run)
857
raise errors.BzrCommandError('--dry-run requires --auto.')
498
858
if names_list is None:
501
860
if len(names_list) < 2:
502
861
raise errors.BzrCommandError("missing file argument")
503
tree, rel_names = tree_files(names_list)
505
if os.path.isdir(names_list[-1]):
862
tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
863
self.add_cleanup(tree.lock_tree_write().unlock)
864
self._run(tree, names_list, rel_names, after)
866
def run_auto(self, names_list, after, dry_run):
867
if names_list is not None and len(names_list) > 1:
868
raise errors.BzrCommandError('Only one path may be specified to'
871
raise errors.BzrCommandError('--after cannot be specified with'
873
work_tree, file_list = WorkingTree.open_containing_paths(
874
names_list, default_directory='.')
875
self.add_cleanup(work_tree.lock_tree_write().unlock)
876
rename_map.RenameMap.guess_renames(work_tree, dry_run)
878
def _run(self, tree, names_list, rel_names, after):
879
into_existing = osutils.isdir(names_list[-1])
880
if into_existing and len(names_list) == 2:
882
# a. case-insensitive filesystem and change case of dir
883
# b. move directory after the fact (if the source used to be
884
# a directory, but now doesn't exist in the working tree
885
# and the target is an existing directory, just rename it)
886
if (not tree.case_sensitive
887
and rel_names[0].lower() == rel_names[1].lower()):
888
into_existing = False
891
# 'fix' the case of a potential 'from'
892
from_id = tree.path2id(
893
tree.get_canonical_inventory_path(rel_names[0]))
894
if (not osutils.lexists(names_list[0]) and
895
from_id and inv.get_file_kind(from_id) == "directory"):
896
into_existing = False
506
899
# move into existing directory
507
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
508
self.outf.write("%s => %s\n" % pair)
900
# All entries reference existing inventory items, so fix them up
901
# for cicp file-systems.
902
rel_names = tree.get_canonical_inventory_paths(rel_names)
903
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
905
self.outf.write("%s => %s\n" % (src, dest))
510
907
if len(names_list) != 2:
511
908
raise errors.BzrCommandError('to mv multiple files the'
512
909
' destination must be a versioned'
514
tree.rename_one(rel_names[0], rel_names[1], after=after)
515
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
912
# for cicp file-systems: the src references an existing inventory
914
src = tree.get_canonical_inventory_path(rel_names[0])
915
# Find the canonical version of the destination: In all cases, the
916
# parent of the target must be in the inventory, so we fetch the
917
# canonical version from there (we do not always *use* the
918
# canonicalized tail portion - we may be attempting to rename the
920
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
921
dest_parent = osutils.dirname(canon_dest)
922
spec_tail = osutils.basename(rel_names[1])
923
# For a CICP file-system, we need to avoid creating 2 inventory
924
# entries that differ only by case. So regardless of the case
925
# we *want* to use (ie, specified by the user or the file-system),
926
# we must always choose to use the case of any existing inventory
927
# items. The only exception to this is when we are attempting a
928
# case-only rename (ie, canonical versions of src and dest are
930
dest_id = tree.path2id(canon_dest)
931
if dest_id is None or tree.path2id(src) == dest_id:
932
# No existing item we care about, so work out what case we
933
# are actually going to use.
935
# If 'after' is specified, the tail must refer to a file on disk.
937
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
939
# pathjoin with an empty tail adds a slash, which breaks
941
dest_parent_fq = tree.basedir
943
dest_tail = osutils.canonical_relpath(
945
osutils.pathjoin(dest_parent_fq, spec_tail))
947
# not 'after', so case as specified is used
948
dest_tail = spec_tail
950
# Use the existing item so 'mv' fails with AlreadyVersioned.
951
dest_tail = os.path.basename(canon_dest)
952
dest = osutils.pathjoin(dest_parent, dest_tail)
953
mutter("attempting to move %s => %s", src, dest)
954
tree.rename_one(src, dest, after=after)
956
self.outf.write("%s => %s\n" % (src, dest))
518
959
class cmd_pull(Command):
519
"""Turn this branch into a mirror of another branch.
960
__doc__ = """Turn this branch into a mirror of another branch.
521
This command only works on branches that have not diverged. Branches are
522
considered diverged if the destination branch's most recent commit is one
523
that has not been merged (directly or indirectly) into the parent.
962
By default, this command only works on branches that have not diverged.
963
Branches are considered diverged if the destination branch's most recent
964
commit is one that has not been merged (directly or indirectly) into the
525
967
If branches have diverged, you can use 'bzr merge' to integrate the changes
526
968
from one into the other. Once one branch has merged, the other should
527
969
be able to pull it again.
529
If you want to forget your local changes and just update your branch to
530
match the remote one, use pull --overwrite.
532
If there is no default location set, the first pull will set it. After
533
that, you can omit the location to use the default. To change the
534
default, use --remember. The value will only be saved if the remote
535
location can be accessed.
971
If you want to replace your local changes and just want your branch to
972
match the remote one, use pull --overwrite. This will work even if the two
973
branches have diverged.
975
If there is no default location set, the first pull will set it (use
976
--no-remember to avoid settting it). After that, you can omit the
977
location to use the default. To change the default, use --remember. The
978
value will only be saved if the remote location can be accessed.
980
Note: The location can be specified either in the form of a branch,
981
or in the form of a path to a file containing a merge directive generated
538
takes_options = ['remember', 'overwrite', 'revision', 'verbose',
540
help='branch to pull into, '
541
'rather than the one containing the working directory',
985
_see_also = ['push', 'update', 'status-flags', 'send']
986
takes_options = ['remember', 'overwrite', 'revision',
987
custom_help('verbose',
988
help='Show logs of pulled revisions.'),
989
custom_help('directory',
990
help='Branch to pull into, '
991
'rather than the one containing the working directory.'),
993
help="Perform a local pull in a bound "
994
"branch. Local pulls are not applied to "
998
help="Show base revision text in conflicts.")
546
1000
takes_args = ['location?']
547
1001
encoding_type = 'replace'
549
def run(self, location=None, remember=False, overwrite=False,
1003
def run(self, location=None, remember=None, overwrite=False,
550
1004
revision=None, verbose=False,
1005
directory=None, local=False,
552
1007
# FIXME: too much stuff is in the command class
553
1010
if directory is None:
554
1011
directory = u'.'
556
1013
tree_to = WorkingTree.open_containing(directory)[0]
557
1014
branch_to = tree_to.branch
1015
self.add_cleanup(tree_to.lock_write().unlock)
558
1016
except errors.NoWorkingTree:
560
1018
branch_to = Branch.open_containing(directory)[0]
1019
self.add_cleanup(branch_to.lock_write().unlock)
1021
if tree_to is None and show_base:
1022
raise errors.BzrCommandError("Need working tree for --show-base.")
1024
if local and not branch_to.get_bound_location():
1025
raise errors.LocalRequiresBoundBranch()
1027
possible_transports = []
563
1028
if location is not None:
565
reader = bundle.read_bundle_from_url(location)
1030
mergeable = bundle.read_mergeable_from_url(location,
1031
possible_transports=possible_transports)
566
1032
except errors.NotABundle:
567
pass # Continue on considering this url a Branch
569
1035
stored_loc = branch_to.get_parent()
570
1036
if location is None:
628
1105
If branches have diverged, you can use 'bzr push --overwrite' to replace
629
1106
the other branch completely, discarding its unmerged changes.
631
1108
If you want to ensure you have the different changes in the other branch,
632
1109
do a merge (see bzr help merge) from the other branch, and commit that.
633
1110
After that you will be able to do a push without '--overwrite'.
635
If there is no default push location set, the first push will set it.
636
After that, you can omit the location to use the default. To change the
637
default, use --remember. The value will only be saved if the remote
638
location can be accessed.
1112
If there is no default push location set, the first push will set it (use
1113
--no-remember to avoid settting it). After that, you can omit the
1114
location to use the default. To change the default, use --remember. The
1115
value will only be saved if the remote location can be accessed.
641
takes_options = ['remember', 'overwrite', 'verbose',
1118
_see_also = ['pull', 'update', 'working-trees']
1119
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
642
1120
Option('create-prefix',
643
1121
help='Create the path leading up to the branch '
644
'if it does not already exist'),
646
help='branch to push from, '
647
'rather than the one containing the working directory',
1122
'if it does not already exist.'),
1123
custom_help('directory',
1124
help='Branch to push from, '
1125
'rather than the one containing the working directory.'),
651
1126
Option('use-existing-dir',
652
1127
help='By default push will fail if the target'
653
1128
' directory exists, but does not already'
654
' have a control directory. This flag will'
1129
' have a control directory. This flag will'
655
1130
' allow push to proceed.'),
1132
help='Create a stacked branch that references the public location '
1133
'of the parent branch.'),
1134
Option('stacked-on',
1135
help='Create a stacked branch that refers to another branch '
1136
'for the commit history. Only the work not present in the '
1137
'referenced branch is included in the branch created.',
1140
help='Refuse to push if there are uncommitted changes in'
1141
' the working tree, --no-strict disables the check.'),
1143
help="Don't populate the working tree, even for protocols"
1144
" that support it."),
657
1146
takes_args = ['location?']
658
1147
encoding_type = 'replace'
660
def run(self, location=None, remember=False, overwrite=False,
661
create_prefix=False, verbose=False,
662
use_existing_dir=False,
664
# FIXME: Way too big! Put this into a function called from the
1149
def run(self, location=None, remember=None, overwrite=False,
1150
create_prefix=False, verbose=False, revision=None,
1151
use_existing_dir=False, directory=None, stacked_on=None,
1152
stacked=False, strict=None, no_tree=False):
1153
from bzrlib.push import _show_push_branch
666
1155
if directory is None:
668
br_from = Branch.open_containing(directory)[0]
669
stored_loc = br_from.get_push_location()
1157
# Get the source branch
1159
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1160
# Get the tip's revision_id
1161
revision = _get_one_revision('push', revision)
1162
if revision is not None:
1163
revision_id = revision.in_history(br_from).rev_id
1166
if tree is not None and revision_id is None:
1167
tree.check_changed_or_out_of_date(
1168
strict, 'push_strict',
1169
more_error='Use --no-strict to force the push.',
1170
more_warning='Uncommitted changes will not be pushed.')
1171
# Get the stacked_on branch, if any
1172
if stacked_on is not None:
1173
stacked_on = urlutils.normalize_url(stacked_on)
1175
parent_url = br_from.get_parent()
1177
parent = Branch.open(parent_url)
1178
stacked_on = parent.get_public_branch()
1180
# I considered excluding non-http url's here, thus forcing
1181
# 'public' branches only, but that only works for some
1182
# users, so it's best to just depend on the user spotting an
1183
# error by the feedback given to them. RBC 20080227.
1184
stacked_on = parent_url
1186
raise errors.BzrCommandError(
1187
"Could not determine branch to refer to.")
1189
# Get the destination location
670
1190
if location is None:
1191
stored_loc = br_from.get_push_location()
671
1192
if stored_loc is None:
672
raise errors.BzrCommandError("No push location known or specified.")
1193
raise errors.BzrCommandError(
1194
"No push location known or specified.")
674
1196
display_url = urlutils.unescape_for_display(stored_loc,
675
1197
self.outf.encoding)
676
self.outf.write("Using saved location: %s\n" % display_url)
1198
note("Using saved push location: %s" % display_url)
677
1199
location = stored_loc
679
to_transport = transport.get_transport(location)
680
location_url = to_transport.base
685
br_to = repository_to = dir_to = None
687
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
688
except errors.NotBranchError:
689
pass # Didn't find anything
691
# If we can open a branch, use its direct repository, otherwise see
692
# if there is a repository without a branch.
694
br_to = dir_to.open_branch()
695
except errors.NotBranchError:
696
# Didn't find a branch, can we find a repository?
698
repository_to = dir_to.find_repository()
699
except errors.NoRepositoryPresent:
702
# Found a branch, so we must have found a repository
703
repository_to = br_to.repository
707
# XXX: Refactor the create_prefix/no_create_prefix code into a
708
# common helper function
710
to_transport.mkdir('.')
711
except errors.FileExists:
712
if not use_existing_dir:
713
raise errors.BzrCommandError("Target directory %s"
714
" already exists, but does not have a valid .bzr"
715
" directory. Supply --use-existing-dir to push"
716
" there anyway." % location)
717
except errors.NoSuchFile:
718
if not create_prefix:
719
raise errors.BzrCommandError("Parent directory of %s"
721
"\nYou may supply --create-prefix to create all"
722
" leading parent directories."
725
cur_transport = to_transport
726
needed = [cur_transport]
727
# Recurse upwards until we can create a directory successfully
729
new_transport = cur_transport.clone('..')
730
if new_transport.base == cur_transport.base:
731
raise errors.BzrCommandError("Failed to create path"
735
new_transport.mkdir('.')
736
except errors.NoSuchFile:
737
needed.append(new_transport)
738
cur_transport = new_transport
742
# Now we only need to create child directories
744
cur_transport = needed.pop()
745
cur_transport.mkdir('.')
747
# Now the target directory exists, but doesn't have a .bzr
748
# directory. So we need to create it, along with any work to create
749
# all of the dependent branches, etc.
750
dir_to = br_from.bzrdir.clone(location_url,
751
revision_id=br_from.last_revision())
752
br_to = dir_to.open_branch()
753
count = br_to.last_revision_info()[0]
754
# We successfully created the target, remember it
755
if br_from.get_push_location() is None or remember:
756
br_from.set_push_location(br_to.base)
757
elif repository_to is None:
758
# we have a bzrdir but no branch or repository
759
# XXX: Figure out what to do other than complain.
760
raise errors.BzrCommandError("At %s you have a valid .bzr control"
761
" directory, but not a branch or repository. This is an"
762
" unsupported configuration. Please move the target directory"
763
" out of the way and try again."
766
# We have a repository but no branch, copy the revisions, and then
768
last_revision_id = br_from.last_revision()
769
repository_to.fetch(br_from.repository,
770
revision_id=last_revision_id)
771
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
772
count = len(br_to.revision_history())
773
if br_from.get_push_location() is None or remember:
774
br_from.set_push_location(br_to.base)
775
else: # We have a valid to branch
776
# We were able to connect to the remote location, so remember it
777
# we don't need to successfully push because of possible divergence.
778
if br_from.get_push_location() is None or remember:
779
br_from.set_push_location(br_to.base)
780
old_rh = br_to.revision_history()
783
tree_to = dir_to.open_workingtree()
784
except errors.NotLocalUrl:
785
warning('This transport does not update the working '
786
'tree of: %s' % (br_to.base,))
787
count = br_from.push(br_to, overwrite)
788
except errors.NoWorkingTree:
789
count = br_from.push(br_to, overwrite)
793
count = br_from.push(tree_to.branch, overwrite)
797
except errors.DivergedBranches:
798
raise errors.BzrCommandError('These branches have diverged.'
799
' Try using "merge" and then "push".')
800
note('%d revision(s) pushed.' % (count,))
803
new_rh = br_to.revision_history()
806
from bzrlib.log import show_changed_revisions
807
show_changed_revisions(br_to, old_rh, new_rh,
1201
_show_push_branch(br_from, revision_id, location, self.outf,
1202
verbose=verbose, overwrite=overwrite, remember=remember,
1203
stacked_on=stacked_on, create_prefix=create_prefix,
1204
use_existing_dir=use_existing_dir, no_tree=no_tree)
811
1207
class cmd_branch(Command):
812
"""Create a new copy of a branch.
1208
__doc__ = """Create a new branch that is a copy of an existing branch.
814
1210
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
815
1211
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1212
If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
1213
is derived from the FROM_LOCATION by stripping a leading scheme or drive
1214
identifier, if any. For example, "branch lp:foo-bar" will attempt to
817
1217
To retrieve the branch as of a particular revision, supply the --revision
818
1218
parameter, as in "branch foo/bar -r 5".
820
--basis is to speed up branching from remote branches. When specified, it
821
copies all the file-contents, inventory and revision data from the basis
822
branch before copying anything from the remote branch.
1220
The synonyms 'clone' and 'get' for this command are deprecated.
1223
_see_also = ['checkout']
824
1224
takes_args = ['from_location', 'to_location?']
825
takes_options = ['revision', 'basis']
1225
takes_options = ['revision',
1226
Option('hardlink', help='Hard-link working tree files where possible.'),
1227
Option('files-from', type=str,
1228
help="Get file contents from this tree."),
1230
help="Create a branch without a working-tree."),
1232
help="Switch the checkout in the current directory "
1233
"to the new branch."),
1235
help='Create a stacked branch referring to the source branch. '
1236
'The new branch will depend on the availability of the source '
1237
'branch for all operations.'),
1238
Option('standalone',
1239
help='Do not use a shared repository, even if available.'),
1240
Option('use-existing-dir',
1241
help='By default branch will fail if the target'
1242
' directory exists, but does not already'
1243
' have a control directory. This flag will'
1244
' allow branch to proceed.'),
1246
help="Bind new branch to from location."),
826
1248
aliases = ['get', 'clone']
828
def run(self, from_location, to_location=None, revision=None, basis=None):
831
elif len(revision) > 1:
832
raise errors.BzrCommandError(
833
'bzr branch --revision takes exactly 1 revision value')
835
br_from = Branch.open(from_location)
838
if basis is not None:
839
basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
842
if len(revision) == 1 and revision[0] is not None:
843
revision_id = revision[0].in_history(br_from)[1]
845
# FIXME - wt.last_revision, fallback to branch, fall back to
846
# None or perhaps NULL_REVISION to mean copy nothing
848
revision_id = br_from.last_revision()
849
if to_location is None:
850
to_location = os.path.basename(from_location.rstrip("/\\"))
853
name = os.path.basename(to_location) + '\n'
855
to_transport = transport.get_transport(to_location)
857
to_transport.mkdir('.')
858
except errors.FileExists:
859
raise errors.BzrCommandError('Target directory "%s" already'
860
' exists.' % to_location)
861
except errors.NoSuchFile:
862
raise errors.BzrCommandError('Parent of "%s" does not exist.'
865
# preserve whatever source format we have.
866
dir = br_from.bzrdir.sprout(to_transport.base,
867
revision_id, basis_dir)
868
branch = dir.open_branch()
869
except errors.NoSuchRevision:
870
to_transport.delete_tree('.')
871
msg = "The branch %s has no revision %s." % (from_location, revision[0])
872
raise errors.BzrCommandError(msg)
873
except errors.UnlistableBranch:
874
osutils.rmtree(to_location)
875
msg = "The branch %s cannot be used as a --basis" % (basis,)
876
raise errors.BzrCommandError(msg)
878
branch.control_files.put_utf8('branch-name', name)
1250
def run(self, from_location, to_location=None, revision=None,
1251
hardlink=False, stacked=False, standalone=False, no_tree=False,
1252
use_existing_dir=False, switch=False, bind=False,
1254
from bzrlib import switch as _mod_switch
1255
from bzrlib.tag import _merge_tags_if_possible
1256
if self.invoked_as in ['get', 'clone']:
1257
ui.ui_factory.show_user_warning(
1258
'deprecated_command',
1259
deprecated_name=self.invoked_as,
1260
recommended_name='branch',
1261
deprecated_in_version='2.4')
1262
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1264
if not (hardlink or files_from):
1265
# accelerator_tree is usually slower because you have to read N
1266
# files (no readahead, lots of seeks, etc), but allow the user to
1267
# explicitly request it
1268
accelerator_tree = None
1269
if files_from is not None and files_from != from_location:
1270
accelerator_tree = WorkingTree.open(files_from)
1271
revision = _get_one_revision('branch', revision)
1272
self.add_cleanup(br_from.lock_read().unlock)
1273
if revision is not None:
1274
revision_id = revision.as_revision_id(br_from)
1276
# FIXME - wt.last_revision, fallback to branch, fall back to
1277
# None or perhaps NULL_REVISION to mean copy nothing
1279
revision_id = br_from.last_revision()
1280
if to_location is None:
1281
to_location = urlutils.derive_to_location(from_location)
1282
to_transport = transport.get_transport(to_location)
1284
to_transport.mkdir('.')
1285
except errors.FileExists:
1286
if not use_existing_dir:
1287
raise errors.BzrCommandError('Target directory "%s" '
1288
'already exists.' % to_location)
1291
bzrdir.BzrDir.open_from_transport(to_transport)
1292
except errors.NotBranchError:
1295
raise errors.AlreadyBranchError(to_location)
1296
except errors.NoSuchFile:
1297
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1300
# preserve whatever source format we have.
1301
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1302
possible_transports=[to_transport],
1303
accelerator_tree=accelerator_tree,
1304
hardlink=hardlink, stacked=stacked,
1305
force_new_repo=standalone,
1306
create_tree_if_local=not no_tree,
1307
source_branch=br_from)
1308
branch = dir.open_branch()
1309
except errors.NoSuchRevision:
1310
to_transport.delete_tree('.')
1311
msg = "The branch %s has no revision %s." % (from_location,
1313
raise errors.BzrCommandError(msg)
1314
_merge_tags_if_possible(br_from, branch)
1315
# If the source branch is stacked, the new branch may
1316
# be stacked whether we asked for that explicitly or not.
1317
# We therefore need a try/except here and not just 'if stacked:'
1319
note('Created new stacked branch referring to %s.' %
1320
branch.get_stacked_on_url())
1321
except (errors.NotStacked, errors.UnstackableBranchFormat,
1322
errors.UnstackableRepositoryFormat), e:
879
1323
note('Branched %d revision(s).' % branch.revno())
1325
# Bind to the parent
1326
parent_branch = Branch.open(from_location)
1327
branch.bind(parent_branch)
1328
note('New branch bound to %s' % from_location)
1330
# Switch to the new branch
1331
wt, _ = WorkingTree.open_containing('.')
1332
_mod_switch.switch(wt.bzrdir, branch)
1333
note('Switched to branch: %s',
1334
urlutils.unescape_for_display(branch.base, 'utf-8'))
1337
class cmd_branches(Command):
1338
__doc__ = """List the branches available at the current location.
1340
This command will print the names of all the branches at the current location.
1343
takes_args = ['location?']
1345
def run(self, location="."):
1346
dir = bzrdir.BzrDir.open_containing(location)[0]
1347
for branch in dir.list_branches():
1348
if branch.name is None:
1349
self.outf.write(" (default)\n")
1351
self.outf.write(" %s\n" % branch.name.encode(self.outf.encoding))
884
1354
class cmd_checkout(Command):
885
"""Create a new checkout of an existing branch.
1355
__doc__ = """Create a new checkout of an existing branch.
887
1357
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
888
1358
the branch found in '.'. This is useful if you have removed the working tree
889
1359
or if it was never created - i.e. if you pushed the branch to its current
890
1360
location using SFTP.
892
1362
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
893
1363
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1364
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1365
is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1366
identifier, if any. For example, "checkout lp:foo-bar" will attempt to
895
1369
To retrieve the branch as of a particular revision, supply the --revision
896
1370
parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
897
1371
out of date [so you cannot commit] but it may be useful (i.e. to examine old
900
--basis is to speed up checking out from remote branches. When specified, it
901
uses the inventory and file contents from the basis branch in preference to the
902
branch being checked out.
904
See "help checkouts" for more information on checkouts.
1375
_see_also = ['checkouts', 'branch']
906
1376
takes_args = ['branch_location?', 'to_location?']
907
takes_options = ['revision', # , 'basis']
1377
takes_options = ['revision',
908
1378
Option('lightweight',
909
help="perform a lightweight checkout. Lightweight "
1379
help="Perform a lightweight checkout. Lightweight "
910
1380
"checkouts depend on access to the branch for "
911
"every operation. Normal checkouts can perform "
1381
"every operation. Normal checkouts can perform "
912
1382
"common operations like diff and status without "
913
1383
"such access, and also support local commits."
1385
Option('files-from', type=str,
1386
help="Get file contents from this tree."),
1388
help='Hard-link working tree files where possible.'
916
1391
aliases = ['co']
918
def run(self, branch_location=None, to_location=None, revision=None, basis=None,
922
elif len(revision) > 1:
923
raise errors.BzrCommandError(
924
'bzr checkout --revision takes exactly 1 revision value')
1393
def run(self, branch_location=None, to_location=None, revision=None,
1394
lightweight=False, files_from=None, hardlink=False):
925
1395
if branch_location is None:
926
1396
branch_location = osutils.getcwd()
927
1397
to_location = branch_location
928
source = Branch.open(branch_location)
929
if len(revision) == 1 and revision[0] is not None:
930
revision_id = revision[0].in_history(source)[1]
1398
accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1400
if not (hardlink or files_from):
1401
# accelerator_tree is usually slower because you have to read N
1402
# files (no readahead, lots of seeks, etc), but allow the user to
1403
# explicitly request it
1404
accelerator_tree = None
1405
revision = _get_one_revision('checkout', revision)
1406
if files_from is not None and files_from != branch_location:
1407
accelerator_tree = WorkingTree.open(files_from)
1408
if revision is not None:
1409
revision_id = revision.as_revision_id(source)
932
1411
revision_id = None
933
1412
if to_location is None:
934
to_location = os.path.basename(branch_location.rstrip("/\\"))
935
# if the source and to_location are the same,
1413
to_location = urlutils.derive_to_location(branch_location)
1414
# if the source and to_location are the same,
936
1415
# and there is no working tree,
937
1416
# then reconstitute a branch
938
1417
if (osutils.abspath(to_location) ==
941
1420
source.bzrdir.open_workingtree()
942
1421
except errors.NoWorkingTree:
943
source.bzrdir.create_workingtree()
1422
source.bzrdir.create_workingtree(revision_id)
946
os.mkdir(to_location)
948
if e.errno == errno.EEXIST:
949
raise errors.BzrCommandError('Target directory "%s" already'
950
' exists.' % to_location)
951
if e.errno == errno.ENOENT:
952
raise errors.BzrCommandError('Parent of "%s" does not exist.'
956
source.create_checkout(to_location, revision_id, lightweight)
1424
source.create_checkout(to_location, revision_id, lightweight,
1425
accelerator_tree, hardlink)
959
1428
class cmd_renames(Command):
960
"""Show list of renamed files.
1429
__doc__ = """Show list of renamed files.
962
1431
# TODO: Option to show renames between two historical versions.
964
1433
# TODO: Only show renames under dir, rather than in the whole branch.
1434
_see_also = ['status']
965
1435
takes_args = ['dir?']
967
1437
@display_command
968
1438
def run(self, dir=u'.'):
969
1439
tree = WorkingTree.open_containing(dir)[0]
970
old_inv = tree.basis_tree().inventory
971
new_inv = tree.read_working_inventory()
972
renames = list(_mod_tree.find_renames(old_inv, new_inv))
1440
self.add_cleanup(tree.lock_read().unlock)
1441
new_inv = tree.inventory
1442
old_tree = tree.basis_tree()
1443
self.add_cleanup(old_tree.lock_read().unlock)
1444
old_inv = old_tree.inventory
1446
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1447
for f, paths, c, v, p, n, k, e in iterator:
1448
if paths[0] == paths[1]:
1452
renames.append(paths)
974
1454
for old_name, new_name in renames:
975
1455
self.outf.write("%s => %s\n" % (old_name, new_name))
978
1458
class cmd_update(Command):
979
"""Update a tree to have the latest code committed to its branch.
1459
__doc__ = """Update a tree to have the latest code committed to its branch.
981
1461
This will perform a merge into the working tree, and may generate
982
conflicts. If you have any local changes, you will still
1462
conflicts. If you have any local changes, you will still
983
1463
need to commit them after the update for the update to be complete.
985
If you want to discard your local changes, you can just do a
1465
If you want to discard your local changes, you can just do a
986
1466
'bzr revert' instead of 'bzr commit' after the update.
1468
If you want to restore a file that has been removed locally, use
1469
'bzr revert' instead of 'bzr update'.
1471
If the tree's branch is bound to a master branch, it will also update
1472
the branch from the master.
1475
_see_also = ['pull', 'working-trees', 'status-flags']
988
1476
takes_args = ['dir?']
1477
takes_options = ['revision',
1479
help="Show base revision text in conflicts."),
989
1481
aliases = ['up']
991
def run(self, dir='.'):
1483
def run(self, dir='.', revision=None, show_base=None):
1484
if revision is not None and len(revision) != 1:
1485
raise errors.BzrCommandError(
1486
"bzr update --revision takes exactly one revision")
992
1487
tree = WorkingTree.open_containing(dir)[0]
993
master = tree.branch.get_master_branch()
1488
branch = tree.branch
1489
possible_transports = []
1490
master = branch.get_master_branch(
1491
possible_transports=possible_transports)
994
1492
if master is not None:
1493
branch_location = master.base
995
1494
tree.lock_write()
1496
branch_location = tree.branch.base
997
1497
tree.lock_tree_write()
1498
self.add_cleanup(tree.unlock)
1499
# get rid of the final '/' and be ready for display
1500
branch_location = urlutils.unescape_for_display(
1501
branch_location.rstrip('/'),
1503
existing_pending_merges = tree.get_parent_ids()[1:]
1507
# may need to fetch data into a heavyweight checkout
1508
# XXX: this may take some time, maybe we should display a
1510
old_tip = branch.update(possible_transports)
1511
if revision is not None:
1512
revision_id = revision[0].as_revision_id(branch)
1514
revision_id = branch.last_revision()
1515
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1516
revno = branch.revision_id_to_dotted_revno(revision_id)
1517
note("Tree is up to date at revision %s of branch %s" %
1518
('.'.join(map(str, revno)), branch_location))
1520
view_info = _get_view_info_for_change_reporter(tree)
1521
change_reporter = delta._ChangeReporter(
1522
unversioned_filter=tree.is_ignored,
1523
view_info=view_info)
999
existing_pending_merges = tree.get_parent_ids()[1:]
1000
last_rev = tree.last_revision()
1001
if last_rev == tree.branch.last_revision():
1002
# may be up to date, check master too.
1003
master = tree.branch.get_master_branch()
1004
if master is None or last_rev == master.last_revision():
1005
revno = tree.branch.revision_id_to_revno(last_rev)
1006
note("Tree is up to date at revision %d." % (revno,))
1008
conflicts = tree.update()
1009
revno = tree.branch.revision_id_to_revno(tree.last_revision())
1010
note('Updated to revision %d.' % (revno,))
1011
if tree.get_parent_ids()[1:] != existing_pending_merges:
1012
note('Your local commits will now show as pending merges with '
1013
"'bzr status', and can be committed with 'bzr commit'.")
1525
conflicts = tree.update(
1527
possible_transports=possible_transports,
1528
revision=revision_id,
1530
show_base=show_base)
1531
except errors.NoSuchRevision, e:
1532
raise errors.BzrCommandError(
1533
"branch has no revision %s\n"
1534
"bzr update --revision only works"
1535
" for a revision in the branch history"
1537
revno = tree.branch.revision_id_to_dotted_revno(
1538
_mod_revision.ensure_null(tree.last_revision()))
1539
note('Updated to revision %s of branch %s' %
1540
('.'.join(map(str, revno)), branch_location))
1541
parent_ids = tree.get_parent_ids()
1542
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1543
note('Your local commits will now show as pending merges with '
1544
"'bzr status', and can be committed with 'bzr commit'.")
1022
1551
class cmd_info(Command):
1023
"""Show information about a working tree, branch or repository.
1552
__doc__ = """Show information about a working tree, branch or repository.
1025
1554
This command will show all known locations and formats associated to the
1026
tree, branch or repository. Statistical information is included with
1555
tree, branch or repository.
1557
In verbose mode, statistical information is included with each report.
1558
To see extended statistic information, use a verbosity level of 2 or
1559
higher by specifying the verbose option multiple times, e.g. -vv.
1029
1561
Branches and working trees will also report any missing revisions.
1565
Display information on the format and related locations:
1569
Display the above together with extended format information and
1570
basic statistics (like the number of files in the working tree and
1571
number of revisions in the branch and repository):
1575
Display the above together with number of committers to the branch:
1579
_see_also = ['revno', 'working-trees', 'repositories']
1031
1580
takes_args = ['location?']
1032
1581
takes_options = ['verbose']
1582
encoding_type = 'replace'
1034
1584
@display_command
1035
1585
def run(self, location=None, verbose=False):
1587
noise_level = get_verbosity_level()
1036
1590
from bzrlib.info import show_bzrdir_info
1037
1591
show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1592
verbose=noise_level, outfile=self.outf)
1041
1595
class cmd_remove(Command):
1042
"""Make a file unversioned.
1044
This makes bzr stop tracking changes to a versioned file. It does
1045
not delete the working copy.
1047
You can specify one or more files, and/or --new. If you specify --new,
1048
only 'added' files will be removed. If you specify both, then new files
1049
in the specified directories will be removed. If the directories are
1050
also new, they will also be removed.
1596
__doc__ = """Remove files or directories.
1598
This makes Bazaar stop tracking changes to the specified files. Bazaar will
1599
delete them if they can easily be recovered using revert otherwise they
1600
will be backed up (adding an extention of the form .~#~). If no options or
1601
parameters are given Bazaar will scan for files that are being tracked by
1602
Bazaar but missing in your tree and stop tracking them for you.
1052
1604
takes_args = ['file*']
1053
takes_options = ['verbose', Option('new', help='remove newly-added files')]
1605
takes_options = ['verbose',
1606
Option('new', help='Only remove files that have never been committed.'),
1607
RegistryOption.from_kwargs('file-deletion-strategy',
1608
'The file deletion mode to be used.',
1609
title='Deletion Strategy', value_switches=True, enum_switch=False,
1610
safe='Backup changed files (default).',
1611
keep='Delete from bzr but leave the working copy.',
1612
no_backup='Don\'t backup changed files.',
1613
force='Delete all the specified files, even if they can not be '
1614
'recovered and even if they are non-empty directories. '
1615
'(deprecated, use no-backup)')]
1616
aliases = ['rm', 'del']
1055
1617
encoding_type = 'replace'
1057
def run(self, file_list, verbose=False, new=False):
1058
tree, file_list = tree_files(file_list)
1060
if file_list is None:
1061
raise errors.BzrCommandError('Specify one or more files to'
1062
' remove, or use --new.')
1619
def run(self, file_list, verbose=False, new=False,
1620
file_deletion_strategy='safe'):
1621
if file_deletion_strategy == 'force':
1622
note("(The --force option is deprecated, rather use --no-backup "
1624
file_deletion_strategy = 'no-backup'
1626
tree, file_list = WorkingTree.open_containing_paths(file_list)
1628
if file_list is not None:
1629
file_list = [f for f in file_list]
1631
self.add_cleanup(tree.lock_write().unlock)
1632
# Heuristics should probably all move into tree.remove_smart or
1064
1635
added = tree.changes_from(tree.basis_tree(),
1065
1636
specific_files=file_list).added
1066
1637
file_list = sorted([f[0] for f in added], reverse=True)
1067
1638
if len(file_list) == 0:
1068
1639
raise errors.BzrCommandError('No matching files.')
1069
tree.remove(file_list, verbose=verbose, to_file=self.outf)
1640
elif file_list is None:
1641
# missing files show up in iter_changes(basis) as
1642
# versioned-with-no-kind.
1644
for change in tree.iter_changes(tree.basis_tree()):
1645
# Find paths in the working tree that have no kind:
1646
if change[1][1] is not None and change[6][1] is None:
1647
missing.append(change[1][1])
1648
file_list = sorted(missing, reverse=True)
1649
file_deletion_strategy = 'keep'
1650
tree.remove(file_list, verbose=verbose, to_file=self.outf,
1651
keep_files=file_deletion_strategy=='keep',
1652
force=(file_deletion_strategy=='no-backup'))
1072
1655
class cmd_file_id(Command):
1073
"""Print file_id of a particular file or directory.
1656
__doc__ = """Print file_id of a particular file or directory.
1075
1658
The file_id is assigned when the file is first added and remains the
1076
1659
same through all revisions where the file exists, even when it is
1482
2206
self.outf.write(tree.basedir + '\n')
2209
def _parse_limit(limitstring):
2211
return int(limitstring)
2213
msg = "The limit argument must be an integer."
2214
raise errors.BzrCommandError(msg)
2217
def _parse_levels(s):
2221
msg = "The levels argument must be an integer."
2222
raise errors.BzrCommandError(msg)
1485
2225
class cmd_log(Command):
1486
"""Show log of a branch, file, or directory.
1488
By default show the log of the branch containing the working directory.
1490
To request a range of logs, you can use the command -r begin..end
1491
-r revision requests a specific revision, -r ..end or -r begin.. are
1497
bzr log -r -10.. http://server/branch
2226
__doc__ = """Show historical log for a branch or subset of a branch.
2228
log is bzr's default tool for exploring the history of a branch.
2229
The branch to use is taken from the first parameter. If no parameters
2230
are given, the branch containing the working directory is logged.
2231
Here are some simple examples::
2233
bzr log log the current branch
2234
bzr log foo.py log a file in its branch
2235
bzr log http://server/branch log a branch on a server
2237
The filtering, ordering and information shown for each revision can
2238
be controlled as explained below. By default, all revisions are
2239
shown sorted (topologically) so that newer revisions appear before
2240
older ones and descendants always appear before ancestors. If displayed,
2241
merged revisions are shown indented under the revision in which they
2246
The log format controls how information about each revision is
2247
displayed. The standard log formats are called ``long``, ``short``
2248
and ``line``. The default is long. See ``bzr help log-formats``
2249
for more details on log formats.
2251
The following options can be used to control what information is
2254
-l N display a maximum of N revisions
2255
-n N display N levels of revisions (0 for all, 1 for collapsed)
2256
-v display a status summary (delta) for each revision
2257
-p display a diff (patch) for each revision
2258
--show-ids display revision-ids (and file-ids), not just revnos
2260
Note that the default number of levels to display is a function of the
2261
log format. If the -n option is not used, the standard log formats show
2262
just the top level (mainline).
2264
Status summaries are shown using status flags like A, M, etc. To see
2265
the changes explained using words like ``added`` and ``modified``
2266
instead, use the -vv option.
2270
To display revisions from oldest to newest, use the --forward option.
2271
In most cases, using this option will have little impact on the total
2272
time taken to produce a log, though --forward does not incrementally
2273
display revisions like --reverse does when it can.
2275
:Revision filtering:
2277
The -r option can be used to specify what revision or range of revisions
2278
to filter against. The various forms are shown below::
2280
-rX display revision X
2281
-rX.. display revision X and later
2282
-r..Y display up to and including revision Y
2283
-rX..Y display from X to Y inclusive
2285
See ``bzr help revisionspec`` for details on how to specify X and Y.
2286
Some common examples are given below::
2288
-r-1 show just the tip
2289
-r-10.. show the last 10 mainline revisions
2290
-rsubmit:.. show what's new on this branch
2291
-rancestor:path.. show changes since the common ancestor of this
2292
branch and the one at location path
2293
-rdate:yesterday.. show changes since yesterday
2295
When logging a range of revisions using -rX..Y, log starts at
2296
revision Y and searches back in history through the primary
2297
("left-hand") parents until it finds X. When logging just the
2298
top level (using -n1), an error is reported if X is not found
2299
along the way. If multi-level logging is used (-n0), X may be
2300
a nested merge revision and the log will be truncated accordingly.
2304
If parameters are given and the first one is not a branch, the log
2305
will be filtered to show only those revisions that changed the
2306
nominated files or directories.
2308
Filenames are interpreted within their historical context. To log a
2309
deleted file, specify a revision range so that the file existed at
2310
the end or start of the range.
2312
Historical context is also important when interpreting pathnames of
2313
renamed files/directories. Consider the following example:
2315
* revision 1: add tutorial.txt
2316
* revision 2: modify tutorial.txt
2317
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2321
* ``bzr log guide.txt`` will log the file added in revision 1
2323
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2325
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2326
the original file in revision 2.
2328
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2329
was no file called guide.txt in revision 2.
2331
Renames are always followed by log. By design, there is no need to
2332
explicitly ask for this (and no way to stop logging a file back
2333
until it was last renamed).
2337
The --match option can be used for finding revisions that match a
2338
regular expression in a commit message, committer, author or bug.
2339
Specifying the option several times will match any of the supplied
2340
expressions. --match-author, --match-bugs, --match-committer and
2341
--match-message can be used to only match a specific field.
2345
GUI tools and IDEs are often better at exploring history than command
2346
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2347
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2348
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2349
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2351
You may find it useful to add the aliases below to ``bazaar.conf``::
2355
top = log -l10 --line
2358
``bzr tip`` will then show the latest revision while ``bzr top``
2359
will show the last 10 mainline revisions. To see the details of a
2360
particular revision X, ``bzr show -rX``.
2362
If you are interested in looking deeper into a particular merge X,
2363
use ``bzr log -n0 -rX``.
2365
``bzr log -v`` on a branch with lots of history is currently
2366
very slow. A fix for this issue is currently under development.
2367
With or without that fix, it is recommended that a revision range
2368
be given when using the -v option.
2370
bzr has a generic full-text matching plugin, bzr-search, that can be
2371
used to find revisions matching user names, commit messages, etc.
2372
Among other features, this plugin can find all revisions containing
2373
a list of words but not others.
2375
When exploring non-mainline history on large projects with deep
2376
history, the performance of log can be greatly improved by installing
2377
the historycache plugin. This plugin buffers historical information
2378
trading disk space for faster speed.
1500
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1502
takes_args = ['location?']
1503
takes_options = [Option('forward',
1504
help='show from oldest to newest'),
1508
help='show files changed in each revision'),
1509
'show-ids', 'revision',
1513
help='show revisions whose message matches this regexp',
2380
takes_args = ['file*']
2381
_see_also = ['log-formats', 'revisionspec']
2384
help='Show from oldest to newest.'),
2386
custom_help('verbose',
2387
help='Show files changed in each revision.'),
2391
type=bzrlib.option._parse_revision_str,
2393
help='Show just the specified revision.'
2394
' See also "help revisionspec".'),
2396
RegistryOption('authors',
2397
'What names to list as authors - first, all or committer.',
2399
lazy_registry=('bzrlib.log', 'author_list_registry'),
2403
help='Number of levels to display - 0 for all, 1 for flat.',
2405
type=_parse_levels),
2407
help='Show revisions whose message matches this '
2408
'regular expression.',
2413
help='Limit the output to the first N revisions.',
2418
help='Show changes made in each revision as a patch.'),
2419
Option('include-merges',
2420
help='Show merged revisions like --levels 0 does.'),
2421
Option('exclude-common-ancestry',
2422
help='Display only the revisions that are not part'
2423
' of both ancestries (require -rX..Y)'
2425
Option('signatures',
2426
help='Show digital signature validity'),
2429
help='Show revisions whose properties match this '
2432
ListOption('match-message',
2433
help='Show revisions whose message matches this '
2436
ListOption('match-committer',
2437
help='Show revisions whose committer matches this '
2440
ListOption('match-author',
2441
help='Show revisions whose authors match this '
2444
ListOption('match-bugs',
2445
help='Show revisions whose bugs match this '
1516
2449
encoding_type = 'replace'
1518
2451
@display_command
1519
def run(self, location=None, timezone='original',
2452
def run(self, file_list=None, timezone='original',
1521
2454
show_ids=False,
1524
2458
log_format=None,
1526
from bzrlib.log import show_log
1527
assert message is None or isinstance(message, basestring), \
1528
"invalid message argument %r" % message
2463
include_merges=False,
2465
exclude_common_ancestry=False,
2469
match_committer=None,
2473
from bzrlib.log import (
2475
make_log_request_dict,
2476
_get_info_for_log_files,
1529
2478
direction = (forward and 'forward') or 'reverse'
1534
# find the file id to log:
1536
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1540
tree = b.basis_tree()
1541
inv = tree.inventory
1542
file_id = inv.path2id(fp)
2479
if (exclude_common_ancestry
2480
and (revision is None or len(revision) != 2)):
2481
raise errors.BzrCommandError(
2482
'--exclude-common-ancestry requires -r with two revisions')
2487
raise errors.BzrCommandError(
2488
'--levels and --include-merges are mutually exclusive')
2490
if change is not None:
2492
raise errors.RangeInChangeOption()
2493
if revision is not None:
2494
raise errors.BzrCommandError(
2495
'--revision and --change are mutually exclusive')
2500
filter_by_dir = False
2502
# find the file ids to log and check for directory filtering
2503
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2504
revision, file_list, self.add_cleanup)
2505
for relpath, file_id, kind in file_info_list:
1543
2506
if file_id is None:
1544
2507
raise errors.BzrCommandError(
1545
"Path does not have any revision history: %s" %
2508
"Path unknown at end or start of revision range: %s" %
2510
# If the relpath is the top of the tree, we log everything
2515
file_ids.append(file_id)
2516
filter_by_dir = filter_by_dir or (
2517
kind in ['directory', 'tree-reference'])
1549
# FIXME ? log the current subdir only RBC 20060203
2520
# FIXME ? log the current subdir only RBC 20060203
1550
2521
if revision is not None \
1551
2522
and len(revision) > 0 and revision[0].get_branch():
1552
2523
location = revision[0].get_branch()
1675
2726
if path is None:
1680
2730
raise errors.BzrCommandError('cannot specify both --from-root'
1684
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2733
tree, branch, relpath = \
2734
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2736
# Calculate the prefix to use
1690
if revision is not None:
1691
tree = branch.repository.revision_tree(
1692
revision[0].in_history(branch).rev_id)
1694
tree = branch.basis_tree()
1698
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1699
if fp.startswith(relpath):
1700
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1701
if non_recursive and '/' in fp:
1703
if not all and not selection[fc]:
1705
if kind is not None and fkind != kind:
1708
kindch = entry.kind_character()
1709
outstring = '%-8s %s%s' % (fc, fp, kindch)
1710
if show_ids and fid is not None:
1711
outstring = "%-50s %s" % (outstring, fid)
1712
self.outf.write(outstring + '\n')
1714
self.outf.write(fp + '\0')
1717
self.outf.write(fid)
1718
self.outf.write('\0')
1726
self.outf.write('%-50s %s\n' % (fp, my_id))
1728
self.outf.write(fp + '\n')
2740
prefix = relpath + '/'
2741
elif fs_path != '.' and not fs_path.endswith('/'):
2742
prefix = fs_path + '/'
2744
if revision is not None or tree is None:
2745
tree = _get_one_revision_tree('ls', revision, branch=branch)
2748
if isinstance(tree, WorkingTree) and tree.supports_views():
2749
view_files = tree.views.lookup_view()
2752
view_str = views.view_display_str(view_files)
2753
note("Ignoring files outside view. View is %s" % view_str)
2755
self.add_cleanup(tree.lock_read().unlock)
2756
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2757
from_dir=relpath, recursive=recursive):
2758
# Apply additional masking
2759
if not all and not selection[fc]:
2761
if kind is not None and fkind != kind:
2766
fullpath = osutils.pathjoin(relpath, fp)
2769
views.check_path_in_view(tree, fullpath)
2770
except errors.FileOutsideView:
2775
fp = osutils.pathjoin(prefix, fp)
2776
kindch = entry.kind_character()
2777
outstring = fp + kindch
2778
ui.ui_factory.clear_term()
2780
outstring = '%-8s %s' % (fc, outstring)
2781
if show_ids and fid is not None:
2782
outstring = "%-50s %s" % (outstring, fid)
2783
self.outf.write(outstring + '\n')
2785
self.outf.write(fp + '\0')
2788
self.outf.write(fid)
2789
self.outf.write('\0')
2797
self.outf.write('%-50s %s\n' % (outstring, my_id))
2799
self.outf.write(outstring + '\n')
1733
2802
class cmd_unknowns(Command):
1734
"""List unknown files.
1736
See also: "bzr ls --unknown".
2803
__doc__ = """List unknown files.
2808
takes_options = ['directory']
1741
2810
@display_command
1743
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2811
def run(self, directory=u'.'):
2812
for f in WorkingTree.open_containing(directory)[0].unknowns():
1744
2813
self.outf.write(osutils.quotefn(f) + '\n')
1747
2816
class cmd_ignore(Command):
1748
"""Ignore specified files or patterns.
2817
__doc__ = """Ignore specified files or patterns.
2819
See ``bzr help patterns`` for details on the syntax of patterns.
2821
If a .bzrignore file does not exist, the ignore command
2822
will create one and add the specified files or patterns to the newly
2823
created file. The ignore command will also automatically add the
2824
.bzrignore file to be versioned. Creating a .bzrignore file without
2825
the use of the ignore command will require an explicit add command.
1750
2827
To remove patterns from the ignore list, edit the .bzrignore file.
1752
Trailing slashes on patterns are ignored.
1753
If the pattern contains a slash or is a regular expression, it is compared
1754
to the whole path from the branch root. Otherwise, it is compared to only
1755
the last component of the path. To match a file only in the root
1756
directory, prepend './'.
1758
Ignore patterns specifying absolute paths are not allowed.
1760
Ignore patterns may include globbing wildcards such as:
1761
? - Matches any single character except '/'
1762
* - Matches 0 or more characters except '/'
1763
/**/ - Matches 0 or more directories in a path
1764
[a-z] - Matches a single character from within a group of characters
1766
Ignore patterns may also be Python regular expressions.
1767
Regular expression ignore patterns are identified by a 'RE:' prefix
1768
followed by the regular expression. Regular expression ignore patterns
1769
may not include named or numbered groups.
1771
Note: ignore patterns containing shell wildcards must be quoted from
1775
bzr ignore ./Makefile
1776
bzr ignore '*.class'
1777
bzr ignore 'lib/**/*.o'
1778
bzr ignore 'RE:lib/.*\.o'
2828
After adding, editing or deleting that file either indirectly by
2829
using this command or directly by using an editor, be sure to commit
2832
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2833
the global ignore file can be found in the application data directory as
2834
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2835
Global ignores are not touched by this command. The global ignore file
2836
can be edited directly using an editor.
2838
Patterns prefixed with '!' are exceptions to ignore patterns and take
2839
precedence over regular ignores. Such exceptions are used to specify
2840
files that should be versioned which would otherwise be ignored.
2842
Patterns prefixed with '!!' act as regular ignore patterns, but have
2843
precedence over the '!' exception patterns.
2847
* Ignore patterns containing shell wildcards must be quoted from
2850
* Ignore patterns starting with "#" act as comments in the ignore file.
2851
To ignore patterns that begin with that character, use the "RE:" prefix.
2854
Ignore the top level Makefile::
2856
bzr ignore ./Makefile
2858
Ignore .class files in all directories...::
2860
bzr ignore "*.class"
2862
...but do not ignore "special.class"::
2864
bzr ignore "!special.class"
2866
Ignore files whose name begins with the "#" character::
2870
Ignore .o files under the lib directory::
2872
bzr ignore "lib/**/*.o"
2874
Ignore .o files under the lib directory::
2876
bzr ignore "RE:lib/.*\.o"
2878
Ignore everything but the "debian" toplevel directory::
2880
bzr ignore "RE:(?!debian/).*"
2882
Ignore everything except the "local" toplevel directory,
2883
but always ignore autosave files ending in ~, even under local/::
2886
bzr ignore "!./local"
2890
_see_also = ['status', 'ignored', 'patterns']
1780
2891
takes_args = ['name_pattern*']
1782
Option('old-default-rules',
1783
help='Out the ignore rules bzr < 0.9 always used.')
1786
def run(self, name_pattern_list=None, old_default_rules=None):
1787
from bzrlib.atomicfile import AtomicFile
1788
if old_default_rules is not None:
1789
# dump the rules and exit
1790
for pattern in ignores.OLD_DEFAULTS:
2892
takes_options = ['directory',
2893
Option('default-rules',
2894
help='Display the default ignore rules that bzr uses.')
2897
def run(self, name_pattern_list=None, default_rules=None,
2899
from bzrlib import ignores
2900
if default_rules is not None:
2901
# dump the default rules and exit
2902
for pattern in ignores.USER_DEFAULTS:
2903
self.outf.write("%s\n" % pattern)
1793
2905
if not name_pattern_list:
1794
2906
raise errors.BzrCommandError("ignore requires at least one "
1795
"NAME_PATTERN or --old-default-rules")
2907
"NAME_PATTERN or --default-rules.")
2908
name_pattern_list = [globbing.normalize_pattern(p)
2909
for p in name_pattern_list]
2911
for p in name_pattern_list:
2912
if not globbing.Globster.is_pattern_valid(p):
2913
bad_patterns += ('\n %s' % p)
2915
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2916
ui.ui_factory.show_error(msg)
2917
raise errors.InvalidPattern('')
1796
2918
for name_pattern in name_pattern_list:
1797
if name_pattern[0] == '/':
2919
if (name_pattern[0] == '/' or
2920
(len(name_pattern) > 1 and name_pattern[1] == ':')):
1798
2921
raise errors.BzrCommandError(
1799
2922
"NAME_PATTERN should not be an absolute path")
1800
tree, relpath = WorkingTree.open_containing(u'.')
1801
ifn = tree.abspath('.bzrignore')
1802
if os.path.exists(ifn):
1805
igns = f.read().decode('utf-8')
1811
# TODO: If the file already uses crlf-style termination, maybe
1812
# we should use that for the newly added lines?
1814
if igns and igns[-1] != '\n':
1816
for name_pattern in name_pattern_list:
1817
igns += name_pattern.rstrip('/') + '\n'
1819
f = AtomicFile(ifn, 'wb')
1821
f.write(igns.encode('utf-8'))
1826
inv = tree.inventory
1827
if inv.path2id('.bzrignore'):
1828
mutter('.bzrignore is already versioned')
1830
mutter('need to make new .bzrignore file versioned')
1831
tree.add(['.bzrignore'])
2923
tree, relpath = WorkingTree.open_containing(directory)
2924
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2925
ignored = globbing.Globster(name_pattern_list)
2927
self.add_cleanup(tree.lock_read().unlock)
2928
for entry in tree.list_files():
2932
if ignored.match(filename):
2933
matches.append(filename)
2934
if len(matches) > 0:
2935
self.outf.write("Warning: the following files are version controlled and"
2936
" match your ignore pattern:\n%s"
2937
"\nThese files will continue to be version controlled"
2938
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1834
2941
class cmd_ignored(Command):
1835
"""List ignored files and the patterns that matched them.
1837
See also: bzr ignore"""
2942
__doc__ = """List ignored files and the patterns that matched them.
2944
List all the ignored files and the ignore pattern that caused the file to
2947
Alternatively, to list just the files::
2952
encoding_type = 'replace'
2953
_see_also = ['ignore', 'ls']
2954
takes_options = ['directory']
1838
2956
@display_command
1840
tree = WorkingTree.open_containing(u'.')[0]
1843
for path, file_class, kind, file_id, entry in tree.list_files():
1844
if file_class != 'I':
1846
## XXX: Slightly inefficient since this was already calculated
1847
pat = tree.is_ignored(path)
1848
print '%-50s %s' % (path, pat)
2957
def run(self, directory=u'.'):
2958
tree = WorkingTree.open_containing(directory)[0]
2959
self.add_cleanup(tree.lock_read().unlock)
2960
for path, file_class, kind, file_id, entry in tree.list_files():
2961
if file_class != 'I':
2963
## XXX: Slightly inefficient since this was already calculated
2964
pat = tree.is_ignored(path)
2965
self.outf.write('%-50s %s\n' % (path, pat))
1853
2968
class cmd_lookup_revision(Command):
1854
"""Lookup the revision-id from a revision-number
2969
__doc__ = """Lookup the revision-id from a revision-number
1857
2972
bzr lookup-revision 33
1860
2975
takes_args = ['revno']
2976
takes_options = ['directory']
1862
2978
@display_command
1863
def run(self, revno):
2979
def run(self, revno, directory=u'.'):
1865
2981
revno = int(revno)
1866
2982
except ValueError:
1867
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
1869
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2983
raise errors.BzrCommandError("not a valid revision-number: %r"
2985
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2986
self.outf.write("%s\n" % revid)
1872
2989
class cmd_export(Command):
1873
"""Export past revision to destination directory.
2990
__doc__ = """Export current or past revision to a destination directory or archive.
1875
2992
If no revision is specified this exports the last committed revision.
1878
2995
given, try to find the format with the extension. If no extension
1879
2996
is found exports to a directory (equivalent to --format=dir).
1881
Root may be the top directory for tar, tgz and tbz2 formats. If none
1882
is given, the top directory will be the root name of the file.
1884
If branch is omitted then the branch containing the CWD will be used.
1886
Note: export of tree with non-ascii filenames to zip is not supported.
1888
Supported formats Autodetected by extension
1889
----------------- -------------------------
2998
If root is supplied, it will be used as the root directory inside
2999
container formats (tar, zip, etc). If it is not supplied it will default
3000
to the exported filename. The root option has no effect for 'dir' format.
3002
If branch is omitted then the branch containing the current working
3003
directory will be used.
3005
Note: Export of tree with non-ASCII filenames to zip is not supported.
3007
================= =========================
3008
Supported formats Autodetected by extension
3009
================= =========================
1892
3012
tbz2 .tar.bz2, .tbz2
1893
3013
tgz .tar.gz, .tgz
3015
================= =========================
1896
takes_args = ['dest', 'branch?']
1897
takes_options = ['revision', 'format', 'root']
1898
def run(self, dest, branch=None, revision=None, format=None, root=None):
3018
takes_args = ['dest', 'branch_or_subdir?']
3019
takes_options = ['directory',
3021
help="Type of file to export to.",
3024
Option('filters', help='Apply content filters to export the '
3025
'convenient form.'),
3028
help="Name of the root directory inside the exported file."),
3029
Option('per-file-timestamps',
3030
help='Set modification time of files to that of the last '
3031
'revision in which it was changed.'),
3033
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
3034
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
1899
3035
from bzrlib.export import export
1902
tree = WorkingTree.open_containing(u'.')[0]
3037
if branch_or_subdir is None:
3038
tree = WorkingTree.open_containing(directory)[0]
1903
3039
b = tree.branch
1905
b = Branch.open(branch)
1907
if revision is None:
1908
# should be tree.last_revision FIXME
1909
rev_id = b.last_revision()
1911
if len(revision) != 1:
1912
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
1913
rev_id = revision[0].in_history(b).rev_id
1914
t = b.repository.revision_tree(rev_id)
3042
b, subdir = Branch.open_containing(branch_or_subdir)
3045
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
1916
export(t, dest, format, root)
3047
export(rev_tree, dest, format, root, subdir, filtered=filters,
3048
per_file_timestamps=per_file_timestamps)
1917
3049
except errors.NoSuchExportFormat, e:
1918
3050
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1921
3053
class cmd_cat(Command):
1922
"""Write a file's text from a previous revision."""
1924
takes_options = ['revision', 'name-from-revision']
3054
__doc__ = """Write the contents of a file as of a given revision to standard output.
3056
If no revision is nominated, the last revision is used.
3058
Note: Take care to redirect standard output when using this command on a
3063
takes_options = ['directory',
3064
Option('name-from-revision', help='The path name in the old tree.'),
3065
Option('filters', help='Apply content filters to display the '
3066
'convenience form.'),
1925
3069
takes_args = ['filename']
1926
3070
encoding_type = 'exact'
1928
3072
@display_command
1929
def run(self, filename, revision=None, name_from_revision=False):
3073
def run(self, filename, revision=None, name_from_revision=False,
3074
filters=False, directory=None):
1930
3075
if revision is not None and len(revision) != 1:
1931
3076
raise errors.BzrCommandError("bzr cat --revision takes exactly"
1936
tree, relpath = WorkingTree.open_containing(filename)
1938
except (errors.NotBranchError, errors.NotLocalUrl):
1941
if revision is not None and revision[0].get_branch() is not None:
1942
b = Branch.open(revision[0].get_branch())
3077
" one revision specifier")
3078
tree, branch, relpath = \
3079
_open_directory_or_containing_tree_or_branch(filename, directory)
3080
self.add_cleanup(branch.lock_read().unlock)
3081
return self._run(tree, branch, relpath, filename, revision,
3082
name_from_revision, filters)
3084
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
1943
3086
if tree is None:
1944
b, relpath = Branch.open_containing(filename)
1945
3087
tree = b.basis_tree()
1946
if revision is None:
1947
revision_id = b.last_revision()
1949
revision_id = revision[0].in_history(b).rev_id
3088
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
3089
self.add_cleanup(rev_tree.lock_read().unlock)
1951
cur_file_id = tree.path2id(relpath)
1952
rev_tree = b.repository.revision_tree(revision_id)
1953
3091
old_file_id = rev_tree.path2id(relpath)
3093
# TODO: Split out this code to something that generically finds the
3094
# best id for a path across one or more trees; it's like
3095
# find_ids_across_trees but restricted to find just one. -- mbp
1955
3097
if name_from_revision:
3098
# Try in revision if requested
1956
3099
if old_file_id is None:
1957
raise errors.BzrCommandError("%r is not present in revision %s"
1958
% (filename, revision_id))
1960
rev_tree.print_file(old_file_id)
1961
elif cur_file_id is not None:
1962
rev_tree.print_file(cur_file_id)
1963
elif old_file_id is not None:
1964
rev_tree.print_file(old_file_id)
1966
raise errors.BzrCommandError("%r is not present in revision %s" %
1967
(filename, revision_id))
3100
raise errors.BzrCommandError(
3101
"%r is not present in revision %s" % (
3102
filename, rev_tree.get_revision_id()))
3104
actual_file_id = old_file_id
3106
cur_file_id = tree.path2id(relpath)
3107
if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3108
actual_file_id = cur_file_id
3109
elif old_file_id is not None:
3110
actual_file_id = old_file_id
3112
raise errors.BzrCommandError(
3113
"%r is not present in revision %s" % (
3114
filename, rev_tree.get_revision_id()))
3116
from bzrlib.filter_tree import ContentFilterTree
3117
filter_tree = ContentFilterTree(rev_tree,
3118
rev_tree._content_filter_stack)
3119
content = filter_tree.get_file_text(actual_file_id)
3121
content = rev_tree.get_file_text(actual_file_id)
3123
self.outf.write(content)
1970
3126
class cmd_local_time_offset(Command):
1971
"""Show the offset in seconds from GMT to local time."""
3127
__doc__ = """Show the offset in seconds from GMT to local time."""
1973
3129
@display_command
1975
print osutils.local_time_offset()
3131
self.outf.write("%s\n" % osutils.local_time_offset())
1979
3135
class cmd_commit(Command):
1980
"""Commit changes into a new revision.
1982
If no arguments are given, the entire tree is committed.
1984
If selected files are specified, only changes to those files are
1985
committed. If a directory is specified then the directory and everything
1986
within it is committed.
1988
A selected-file commit may fail in some cases where the committed
1989
tree would be invalid, such as trying to commit a file in a
1990
newly-added directory that is not itself committed.
3136
__doc__ = """Commit changes into a new revision.
3138
An explanatory message needs to be given for each commit. This is
3139
often done by using the --message option (getting the message from the
3140
command line) or by using the --file option (getting the message from
3141
a file). If neither of these options is given, an editor is opened for
3142
the user to enter the message. To see the changed files in the
3143
boilerplate text loaded into the editor, use the --show-diff option.
3145
By default, the entire tree is committed and the person doing the
3146
commit is assumed to be the author. These defaults can be overridden
3151
If selected files are specified, only changes to those files are
3152
committed. If a directory is specified then the directory and
3153
everything within it is committed.
3155
When excludes are given, they take precedence over selected files.
3156
For example, to commit only changes within foo, but not changes
3159
bzr commit foo -x foo/bar
3161
A selective commit after a merge is not yet supported.
3165
If the author of the change is not the same person as the committer,
3166
you can specify the author's name using the --author option. The
3167
name should be in the same format as a committer-id, e.g.
3168
"John Doe <jdoe@example.com>". If there is more than one author of
3169
the change you can specify the option multiple times, once for each
3174
A common mistake is to forget to add a new file or directory before
3175
running the commit command. The --strict option checks for unknown
3176
files and aborts the commit if any are found. More advanced pre-commit
3177
checks can be implemented by defining hooks. See ``bzr help hooks``
3182
If you accidentially commit the wrong changes or make a spelling
3183
mistake in the commit message say, you can use the uncommit command
3184
to undo it. See ``bzr help uncommit`` for details.
3186
Hooks can also be configured to run after a commit. This allows you
3187
to trigger updates to external systems like bug trackers. The --fixes
3188
option can be used to record the association between a revision and
3189
one or more bugs. See ``bzr help bugs`` for details.
1992
# TODO: Run hooks on tree to-be-committed, and after commit.
1994
# TODO: Strict commit that fails if there are deleted files.
1995
# (what does "deleted files" mean ??)
1997
# TODO: Give better message for -s, --summary, used by tla people
1999
# XXX: verbose currently does nothing
3192
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
2001
3193
takes_args = ['selected*']
2002
takes_options = ['message', 'verbose',
2004
help='commit even if nothing has changed'),
2005
Option('file', type=str,
2008
help='file containing commit message'),
2010
help="refuse to commit if there are unknown "
2011
"files in the working tree."),
2013
help="perform a local only commit in a bound "
2014
"branch. Such commits are not pushed to "
2015
"the master branch until a normal commit "
3195
ListOption('exclude', type=str, short_name='x',
3196
help="Do not consider changes made to a given path."),
3197
Option('message', type=unicode,
3199
help="Description of the new revision."),
3202
help='Commit even if nothing has changed.'),
3203
Option('file', type=str,
3206
help='Take commit message from this file.'),
3208
help="Refuse to commit if there are unknown "
3209
"files in the working tree."),
3210
Option('commit-time', type=str,
3211
help="Manually set a commit time using commit date "
3212
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3213
ListOption('fixes', type=str,
3214
help="Mark a bug as being fixed by this revision "
3215
"(see \"bzr help bugs\")."),
3216
ListOption('author', type=unicode,
3217
help="Set the author's name, if it's different "
3218
"from the committer."),
3220
help="Perform a local commit in a bound "
3221
"branch. Local commits are not pushed to "
3222
"the master branch until a normal commit "
3225
Option('show-diff', short_name='p',
3226
help='When no message is supplied, show the diff along'
3227
' with the status summary in the message editor.'),
3229
help='When committing to a foreign version control '
3230
'system do not push data that can not be natively '
2019
3233
aliases = ['ci', 'checkin']
2021
def run(self, message=None, file=None, verbose=True, selected_list=None,
2022
unchanged=False, strict=False, local=False):
2023
from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2024
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2026
from bzrlib.msgeditor import edit_commit_message, \
2027
make_commit_message_template
2029
# TODO: Need a blackbox test for invoking the external editor; may be
2030
# slightly problematic to run this cross-platform.
2032
# TODO: do more checks that the commit will succeed before
2033
# spending the user's valuable time typing a commit message.
2034
tree, selected_list = tree_files(selected_list)
3235
def _iter_bug_fix_urls(self, fixes, branch):
3236
# Configure the properties for bug fixing attributes.
3237
for fixed_bug in fixes:
3238
tokens = fixed_bug.split(':')
3239
if len(tokens) != 2:
3240
raise errors.BzrCommandError(
3241
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3242
"See \"bzr help bugs\" for more information on this "
3243
"feature.\nCommit refused." % fixed_bug)
3244
tag, bug_id = tokens
3246
yield bugtracker.get_bug_url(tag, branch, bug_id)
3247
except errors.UnknownBugTrackerAbbreviation:
3248
raise errors.BzrCommandError(
3249
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3250
except errors.MalformedBugIdentifier, e:
3251
raise errors.BzrCommandError(
3252
"%s\nCommit refused." % (str(e),))
3254
def run(self, message=None, file=None, verbose=False, selected_list=None,
3255
unchanged=False, strict=False, local=False, fixes=None,
3256
author=None, show_diff=False, exclude=None, commit_time=None,
3258
from bzrlib.errors import (
3263
from bzrlib.msgeditor import (
3264
edit_commit_message_encoded,
3265
generate_commit_message_template,
3266
make_commit_message_template_encoded,
3270
commit_stamp = offset = None
3271
if commit_time is not None:
3273
commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3274
except ValueError, e:
3275
raise errors.BzrCommandError(
3276
"Could not parse --commit-time: " + str(e))
3280
tree, selected_list = WorkingTree.open_containing_paths(selected_list)
2035
3281
if selected_list == ['']:
2036
3282
# workaround - commit of root of tree should be exactly the same
2037
3283
# as just default commit in that tree, and succeed even though
2038
3284
# selected-file merge commit is not done yet
2039
3285
selected_list = []
3289
bug_property = bugtracker.encode_fixes_bug_urls(
3290
self._iter_bug_fix_urls(fixes, tree.branch))
3292
properties['bugs'] = bug_property
2041
3294
if local and not tree.branch.get_bound_location():
2042
3295
raise errors.LocalRequiresBoundBranch()
3297
if message is not None:
3299
file_exists = osutils.lexists(message)
3300
except UnicodeError:
3301
# The commit message contains unicode characters that can't be
3302
# represented in the filesystem encoding, so that can't be a
3307
'The commit message is a file name: "%(f)s".\n'
3308
'(use --file "%(f)s" to take commit message from that file)'
3310
ui.ui_factory.show_warning(warning_msg)
3312
message = message.replace('\r\n', '\n')
3313
message = message.replace('\r', '\n')
3315
raise errors.BzrCommandError(
3316
"please specify either --message or --file")
2044
3318
def get_message(commit_obj):
2045
3319
"""Callback to get commit message"""
2046
my_message = message
2047
if my_message is None and not file:
2048
template = make_commit_message_template(tree, selected_list)
2049
my_message = edit_commit_message(template)
3323
my_message = f.read().decode(osutils.get_user_encoding())
3326
elif message is not None:
3327
my_message = message
3329
# No message supplied: make one up.
3330
# text is the status of the tree
3331
text = make_commit_message_template_encoded(tree,
3332
selected_list, diff=show_diff,
3333
output_encoding=osutils.get_user_encoding())
3334
# start_message is the template generated from hooks
3335
# XXX: Warning - looks like hooks return unicode,
3336
# make_commit_message_template_encoded returns user encoding.
3337
# We probably want to be using edit_commit_message instead to
3339
my_message = set_commit_message(commit_obj)
3340
if my_message is None:
3341
start_message = generate_commit_message_template(commit_obj)
3342
my_message = edit_commit_message_encoded(text,
3343
start_message=start_message)
2050
3344
if my_message is None:
2051
3345
raise errors.BzrCommandError("please specify a commit"
2052
3346
" message with either --message or --file")
2053
elif my_message and file:
2054
raise errors.BzrCommandError(
2055
"please specify either --message or --file")
2057
my_message = codecs.open(file, 'rt',
2058
bzrlib.user_encoding).read()
2059
if my_message == "":
2060
raise errors.BzrCommandError("empty commit message specified")
3347
if my_message == "":
3348
raise errors.BzrCommandError("Empty commit message specified."
3349
" Please specify a commit message with either"
3350
" --message or --file or leave a blank message"
3351
" with --message \"\".")
2061
3352
return my_message
2064
reporter = ReportCommitToLog()
2066
reporter = NullCommitReporter()
3354
# The API permits a commit with a filter of [] to mean 'select nothing'
3355
# but the command line should not do that.
3356
if not selected_list:
3357
selected_list = None
2069
3359
tree.commit(message_callback=get_message,
2070
3360
specific_files=selected_list,
2071
3361
allow_pointless=unchanged, strict=strict, local=local,
3362
reporter=None, verbose=verbose, revprops=properties,
3363
authors=author, timestamp=commit_stamp,
3365
exclude=tree.safe_relpath_files(exclude),
2073
3367
except PointlessCommit:
2074
# FIXME: This should really happen before the file is read in;
2075
# perhaps prepare the commit; get the message; then actually commit
2076
raise errors.BzrCommandError("no changes to commit."
2077
" use --unchanged to commit anyhow")
3368
raise errors.BzrCommandError("No changes to commit."
3369
" Please 'bzr add' the files you want to commit, or use"
3370
" --unchanged to force an empty commit.")
2078
3371
except ConflictsInTree:
2079
3372
raise errors.BzrCommandError('Conflicts detected in working '
2080
3373
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
2247
3738
takes_args = ['testspecs*']
2248
3739
takes_options = ['verbose',
2249
Option('one', help='stop when one test fails'),
2250
Option('keep-output',
2251
help='keep output directories when tests fail'),
3741
help='Stop when one test fails.',
2253
3745
help='Use a different transport by default '
2254
3746
'throughout the test suite.',
2255
3747
type=get_transport_type),
2256
Option('benchmark', help='run the bzr bencharks.'),
3749
help='Run the benchmarks rather than selftests.',
2257
3751
Option('lsprof-timed',
2258
help='generate lsprof output for benchmarked'
3752
help='Generate lsprof output for benchmarked'
2259
3753
' sections of code.'),
2260
Option('cache-dir', type=str,
2261
help='a directory to cache intermediate'
2262
' benchmark steps'),
2263
Option('clean-output',
2264
help='clean temporary tests directories'
2265
' without running tests'),
3754
Option('lsprof-tests',
3755
help='Generate lsprof output for each test.'),
2266
3756
Option('first',
2267
help='run all tests, but run specified tests first',
3757
help='Run all tests, but run specified tests first.',
3761
help='List the tests instead of running them.'),
3762
RegistryOption('parallel',
3763
help="Run the test suite in parallel.",
3764
lazy_registry=('bzrlib.tests', 'parallel_registry'),
3765
value_switches=False,
3767
Option('randomize', type=str, argname="SEED",
3768
help='Randomize the order of tests using the given'
3769
' seed or "now" for the current time.'),
3770
ListOption('exclude', type=str, argname="PATTERN",
3772
help='Exclude tests that match this regular'
3775
help='Output test progress via subunit.'),
3776
Option('strict', help='Fail on missing dependencies or '
3778
Option('load-list', type=str, argname='TESTLISTFILE',
3779
help='Load a test id list from a text file.'),
3780
ListOption('debugflag', type=str, short_name='E',
3781
help='Turn on a selftest debug flag.'),
3782
ListOption('starting-with', type=str, argname='TESTID',
3783
param_name='starting_with', short_name='s',
3785
'Load only the tests starting with TESTID.'),
2270
3787
encoding_type = 'replace'
2272
def run(self, testspecs_list=None, verbose=None, one=False,
2273
keep_output=False, transport=None, benchmark=None,
2274
lsprof_timed=None, cache_dir=None, clean_output=False,
2277
from bzrlib.tests import selftest
2278
import bzrlib.benchmarks as benchmarks
2279
from bzrlib.benchmarks import tree_creator
2282
from bzrlib.tests import clean_selftest_output
2283
clean_selftest_output()
2286
if cache_dir is not None:
2287
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2288
print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
2289
print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
3790
Command.__init__(self)
3791
self.additional_selftest_args = {}
3793
def run(self, testspecs_list=None, verbose=False, one=False,
3794
transport=None, benchmark=None,
3796
first=False, list_only=False,
3797
randomize=None, exclude=None, strict=False,
3798
load_list=None, debugflag=None, starting_with=None, subunit=False,
3799
parallel=None, lsprof_tests=False):
3800
from bzrlib import tests
2291
3802
if testspecs_list is not None:
2292
3803
pattern = '|'.join(testspecs_list)
3808
from bzrlib.tests import SubUnitBzrRunner
3810
raise errors.BzrCommandError("subunit not available. subunit "
3811
"needs to be installed to use --subunit.")
3812
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3813
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3814
# stdout, which would corrupt the subunit stream.
3815
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3816
# following code can be deleted when it's sufficiently deployed
3817
# -- vila/mgz 20100514
3818
if (sys.platform == "win32"
3819
and getattr(sys.stdout, 'fileno', None) is not None):
3821
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3823
self.additional_selftest_args.setdefault(
3824
'suite_decorators', []).append(parallel)
2296
test_suite_factory = benchmarks.test_suite
2299
# TODO: should possibly lock the history file...
2300
benchfile = open(".perf_history", "at", buffering=1)
3826
raise errors.BzrCommandError(
3827
"--benchmark is no longer supported from bzr 2.2; "
3828
"use bzr-usertest instead")
3829
test_suite_factory = None
3831
exclude_pattern = None
2302
test_suite_factory = None
3833
exclude_pattern = '(' + '|'.join(exclude) + ')'
3834
selftest_kwargs = {"verbose": verbose,
3836
"stop_on_failure": one,
3837
"transport": transport,
3838
"test_suite_factory": test_suite_factory,
3839
"lsprof_timed": lsprof_timed,
3840
"lsprof_tests": lsprof_tests,
3841
"matching_tests_first": first,
3842
"list_only": list_only,
3843
"random_seed": randomize,
3844
"exclude_pattern": exclude_pattern,
3846
"load_list": load_list,
3847
"debug_flags": debugflag,
3848
"starting_with": starting_with
3850
selftest_kwargs.update(self.additional_selftest_args)
3852
# Make deprecation warnings visible, unless -Werror is set
3853
cleanup = symbol_versioning.activate_deprecation_warnings(
2307
result = selftest(verbose=verbose,
2309
stop_on_failure=one,
2310
keep_output=keep_output,
2311
transport=transport,
2312
test_suite_factory=test_suite_factory,
2313
lsprof_timed=lsprof_timed,
2314
bench_history=benchfile,
2315
matching_tests_first=first,
3856
result = tests.selftest(**selftest_kwargs)
2318
if benchfile is not None:
2321
info('tests passed')
2323
info('tests failed')
2324
3859
return int(not result)
2327
3862
class cmd_version(Command):
2328
"""Show version of bzr."""
3863
__doc__ = """Show version of bzr."""
3865
encoding_type = 'replace'
3867
Option("short", help="Print just the version number."),
2330
3870
@display_command
3871
def run(self, short=False):
2332
3872
from bzrlib.version import show_version
3874
self.outf.write(bzrlib.version_string + '\n')
3876
show_version(to_file=self.outf)
2336
3879
class cmd_rocks(Command):
2337
"""Statement of optimism."""
3880
__doc__ = """Statement of optimism."""
2341
3884
@display_command
2343
print "it sure does!"
3886
self.outf.write("It sure does!\n")
2346
3889
class cmd_find_merge_base(Command):
2347
"""Find and print a base revision for merging two branches."""
3890
__doc__ = """Find and print a base revision for merging two branches."""
2348
3891
# TODO: Options to specify revisions on either side, as if
2349
3892
# merging only part of the history.
2350
3893
takes_args = ['branch', 'other']
2353
3896
@display_command
2354
3897
def run(self, branch, other):
2355
from bzrlib.revision import MultipleRevisionSources
3898
from bzrlib.revision import ensure_null
2357
3900
branch1 = Branch.open_containing(branch)[0]
2358
3901
branch2 = Branch.open_containing(other)[0]
2360
last1 = branch1.last_revision()
2361
last2 = branch2.last_revision()
2363
source = MultipleRevisionSources(branch1.repository,
2366
base_rev_id = common_ancestor(last1, last2, source)
2368
print 'merge base is revision %s' % base_rev_id
3902
self.add_cleanup(branch1.lock_read().unlock)
3903
self.add_cleanup(branch2.lock_read().unlock)
3904
last1 = ensure_null(branch1.last_revision())
3905
last2 = ensure_null(branch2.last_revision())
3907
graph = branch1.repository.get_graph(branch2.repository)
3908
base_rev_id = graph.find_unique_lca(last1, last2)
3910
self.outf.write('merge base is revision %s\n' % base_rev_id)
2371
3913
class cmd_merge(Command):
2372
"""Perform a three-way merge.
2374
The branch is the branch you will merge from. By default, it will merge
2375
the latest revision. If you specify a revision, that revision will be
2376
merged. If you specify two revisions, the first will be used as a BASE,
2377
and the second one as OTHER. Revision numbers are always relative to the
2380
By default, bzr will try to merge in all new work from the other
2381
branch, automatically determining an appropriate base. If this
2382
fails, you may need to give an explicit base.
3914
__doc__ = """Perform a three-way merge.
3916
The source of the merge can be specified either in the form of a branch,
3917
or in the form of a path to a file containing a merge directive generated
3918
with bzr send. If neither is specified, the default is the upstream branch
3919
or the branch most recently merged using --remember. The source of the
3920
merge may also be specified in the form of a path to a file in another
3921
branch: in this case, only the modifications to that file are merged into
3922
the current working tree.
3924
When merging from a branch, by default bzr will try to merge in all new
3925
work from the other branch, automatically determining an appropriate base
3926
revision. If this fails, you may need to give an explicit base.
3928
To pick a different ending revision, pass "--revision OTHER". bzr will
3929
try to merge in all new work up to and including revision OTHER.
3931
If you specify two values, "--revision BASE..OTHER", only revisions BASE
3932
through OTHER, excluding BASE but including OTHER, will be merged. If this
3933
causes some revisions to be skipped, i.e. if the destination branch does
3934
not already contain revision BASE, such a merge is commonly referred to as
3935
a "cherrypick". Unlike a normal merge, Bazaar does not currently track
3936
cherrypicks. The changes look like a normal commit, and the history of the
3937
changes from the other branch is not stored in the commit.
3939
Revision numbers are always relative to the source branch.
2384
3941
Merge will do its best to combine the changes in two branches, but there
2385
3942
are some kinds of problems only a human can fix. When it encounters those,
2386
3943
it will mark a conflict. A conflict means that you need to fix something,
2389
3946
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
2391
If there is no default branch set, the first merge will set it. After
2392
that, you can omit the branch to use the default. To change the
2393
default, use --remember. The value will only be saved if the remote
2394
location can be accessed.
3948
If there is no default branch set, the first merge will set it (use
3949
--no-remember to avoid settting it). After that, you can omit the branch
3950
to use the default. To change the default, use --remember. The value will
3951
only be saved if the remote location can be accessed.
2396
3953
The results of the merge are placed into the destination working
2397
3954
directory, where they can be reviewed (with bzr diff), tested, and then
2398
3955
committed to record the result of the merge.
2402
To merge the latest revision from bzr.dev
2403
bzr merge ../bzr.dev
2405
To merge changes up to and including revision 82 from bzr.dev
2406
bzr merge -r 82 ../bzr.dev
2408
To merge the changes introduced by 82, without previous changes:
2409
bzr merge -r 81..82 ../bzr.dev
2411
3957
merge refuses to run if there are any uncommitted changes, unless
2414
The following merge types are available:
3958
--force is given. If --force is given, then the changes from the source
3959
will be merged with the current working tree, including any uncommitted
3960
changes in the tree. The --force option can also be used to create a
3961
merge revision which has more than two parents.
3963
If one would like to merge changes from the working tree of the other
3964
branch without merging any committed revisions, the --uncommitted option
3967
To select only some changes to merge, use "merge -i", which will prompt
3968
you to apply each diff hunk and file change, similar to "shelve".
3971
To merge all new revisions from bzr.dev::
3973
bzr merge ../bzr.dev
3975
To merge changes up to and including revision 82 from bzr.dev::
3977
bzr merge -r 82 ../bzr.dev
3979
To merge the changes introduced by 82, without previous changes::
3981
bzr merge -r 81..82 ../bzr.dev
3983
To apply a merge directive contained in /tmp/merge::
3985
bzr merge /tmp/merge
3987
To create a merge revision with three parents from two branches
3988
feature1a and feature1b:
3990
bzr merge ../feature1a
3991
bzr merge ../feature1b --force
3992
bzr commit -m 'revision with three parents'
2416
takes_args = ['branch?']
2417
takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
3995
encoding_type = 'exact'
3996
_see_also = ['update', 'remerge', 'status-flags', 'send']
3997
takes_args = ['location?']
4002
help='Merge even if the destination tree has uncommitted changes.'),
2418
4006
Option('show-base', help="Show base revision text in "
2420
4008
Option('uncommitted', help='Apply uncommitted changes'
2421
' from a working copy, instead of branch changes'),
4009
' from a working copy, instead of branch changes.'),
2422
4010
Option('pull', help='If the destination is already'
2423
4011
' completely merged into the source, pull from the'
2424
' source rather than merging. When this happens,'
4012
' source rather than merging. When this happens,'
2425
4013
' you do not need to commit the result.'),
2427
help='branch to merge into, '
2428
'rather than the one containing the working directory',
4014
custom_help('directory',
4015
help='Branch to merge into, '
4016
'rather than the one containing the working directory.'),
4017
Option('preview', help='Instead of merging, show a diff of the'
4019
Option('interactive', help='Select changes interactively.',
2434
def run(self, branch=None, revision=None, force=False, merge_type=None,
2435
show_base=False, reprocess=False, remember=False,
4023
def run(self, location=None, revision=None, force=False,
4024
merge_type=None, show_base=False, reprocess=None, remember=None,
2436
4025
uncommitted=False, pull=False,
2437
4026
directory=None,
2439
4030
if merge_type is None:
2440
4031
merge_type = _mod_merge.Merge3Merger
2442
4033
if directory is None: directory = u'.'
4034
possible_transports = []
4036
allow_pending = True
4037
verified = 'inapplicable'
2443
4039
tree = WorkingTree.open_containing(directory)[0]
2444
change_reporter = delta.ChangeReporter(tree.inventory)
2446
if branch is not None:
4040
if tree.branch.revno() == 0:
4041
raise errors.BzrCommandError('Merging into empty branches not currently supported, '
4042
'https://bugs.launchpad.net/bzr/+bug/308562')
4045
basis_tree = tree.revision_tree(tree.last_revision())
4046
except errors.NoSuchRevision:
4047
basis_tree = tree.basis_tree()
4049
# die as quickly as possible if there are uncommitted changes
4051
if tree.has_changes():
4052
raise errors.UncommittedChanges(tree)
4054
view_info = _get_view_info_for_change_reporter(tree)
4055
change_reporter = delta._ChangeReporter(
4056
unversioned_filter=tree.is_ignored, view_info=view_info)
4057
pb = ui.ui_factory.nested_progress_bar()
4058
self.add_cleanup(pb.finished)
4059
self.add_cleanup(tree.lock_write().unlock)
4060
if location is not None:
2448
reader = bundle.read_bundle_from_url(branch)
4062
mergeable = bundle.read_mergeable_from_url(location,
4063
possible_transports=possible_transports)
2449
4064
except errors.NotABundle:
2450
pass # Continue on considering this url a Branch
2452
conflicts = merge_bundle(reader, tree, not force, merge_type,
2453
reprocess, show_base, change_reporter)
2459
if revision is None \
2460
or len(revision) < 1 or revision[0].needs_branch():
2461
branch = self._get_remembered_parent(tree, branch, 'Merging from')
2463
if revision is None or len(revision) < 1:
2466
other = [branch, None]
2469
other = [branch, -1]
2470
other_branch, path = Branch.open_containing(branch)
4068
raise errors.BzrCommandError('Cannot use --uncommitted'
4069
' with bundles or merge directives.')
4071
if revision is not None:
4072
raise errors.BzrCommandError(
4073
'Cannot use -r with merge directives or bundles')
4074
merger, verified = _mod_merge.Merger.from_mergeable(tree,
4077
if merger is None and uncommitted:
4078
if revision is not None and len(revision) > 0:
2473
4079
raise errors.BzrCommandError('Cannot use --uncommitted and'
2474
' --revision at the same time.')
2475
branch = revision[0].get_branch() or branch
2476
if len(revision) == 1:
2478
other_branch, path = Branch.open_containing(branch)
2479
revno = revision[0].in_history(other_branch).revno
2480
other = [branch, revno]
2482
assert len(revision) == 2
2483
if None in revision:
2484
raise errors.BzrCommandError(
2485
"Merge doesn't permit empty revision specifier.")
2486
base_branch, path = Branch.open_containing(branch)
2487
branch1 = revision[1].get_branch() or branch
2488
other_branch, path1 = Branch.open_containing(branch1)
2489
if revision[0].get_branch() is not None:
2490
# then path was obtained from it, and is None.
2493
base = [branch, revision[0].in_history(base_branch).revno]
2494
other = [branch1, revision[1].in_history(other_branch).revno]
2496
if tree.branch.get_parent() is None or remember:
2497
tree.branch.set_parent(other_branch.base)
2500
interesting_files = [path]
2502
interesting_files = None
2503
pb = ui.ui_factory.nested_progress_bar()
4080
' --revision at the same time.')
4081
merger = self.get_merger_from_uncommitted(tree, location, None)
4082
allow_pending = False
4085
merger, allow_pending = self._get_merger_from_branch(tree,
4086
location, revision, remember, possible_transports, None)
4088
merger.merge_type = merge_type
4089
merger.reprocess = reprocess
4090
merger.show_base = show_base
4091
self.sanity_check_merger(merger)
4092
if (merger.base_rev_id == merger.other_rev_id and
4093
merger.other_rev_id is not None):
4094
# check if location is a nonexistent file (and not a branch) to
4095
# disambiguate the 'Nothing to do'
4096
if merger.interesting_files:
4097
if not merger.other_tree.has_filename(
4098
merger.interesting_files[0]):
4099
note("merger: " + str(merger))
4100
raise errors.PathsDoNotExist([location])
4101
note('Nothing to do.')
4103
if pull and not preview:
4104
if merger.interesting_files is not None:
4105
raise errors.BzrCommandError('Cannot pull individual files')
4106
if (merger.base_rev_id == tree.last_revision()):
4107
result = tree.pull(merger.other_branch, False,
4108
merger.other_rev_id)
4109
result.report(self.outf)
4111
if merger.this_basis is None:
4112
raise errors.BzrCommandError(
4113
"This branch has no commits."
4114
" (perhaps you would prefer 'bzr pull')")
4116
return self._do_preview(merger)
4118
return self._do_interactive(merger)
4120
return self._do_merge(merger, change_reporter, allow_pending,
4123
def _get_preview(self, merger):
4124
tree_merger = merger.make_merger()
4125
tt = tree_merger.make_preview_transform()
4126
self.add_cleanup(tt.finalize)
4127
result_tree = tt.get_preview_tree()
4130
def _do_preview(self, merger):
4131
from bzrlib.diff import show_diff_trees
4132
result_tree = self._get_preview(merger)
4133
path_encoding = osutils.get_diff_header_encoding()
4134
show_diff_trees(merger.this_tree, result_tree, self.outf,
4135
old_label='', new_label='',
4136
path_encoding=path_encoding)
4138
def _do_merge(self, merger, change_reporter, allow_pending, verified):
4139
merger.change_reporter = change_reporter
4140
conflict_count = merger.do_merge()
4142
merger.set_pending()
4143
if verified == 'failed':
4144
warning('Preview patch does not match changes')
4145
if conflict_count != 0:
4150
def _do_interactive(self, merger):
4151
"""Perform an interactive merge.
4153
This works by generating a preview tree of the merge, then using
4154
Shelver to selectively remove the differences between the working tree
4155
and the preview tree.
4157
from bzrlib import shelf_ui
4158
result_tree = self._get_preview(merger)
4159
writer = bzrlib.option.diff_writer_registry.get()
4160
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4161
reporter=shelf_ui.ApplyReporter(),
4162
diff_writer=writer(sys.stdout))
2506
conflict_count = _merge_helper(
2507
other, base, check_clean=(not force),
2508
merge_type=merge_type,
2509
reprocess=reprocess,
2510
show_base=show_base,
2513
pb=pb, file_list=interesting_files,
2514
change_reporter=change_reporter)
2517
if conflict_count != 0:
4168
def sanity_check_merger(self, merger):
4169
if (merger.show_base and
4170
not merger.merge_type is _mod_merge.Merge3Merger):
4171
raise errors.BzrCommandError("Show-base is not supported for this"
4172
" merge type. %s" % merger.merge_type)
4173
if merger.reprocess is None:
4174
if merger.show_base:
4175
merger.reprocess = False
2521
except errors.AmbiguousBase, e:
2522
m = ("sorry, bzr can't determine the right merge base yet\n"
2523
"candidates are:\n "
2524
+ "\n ".join(e.bases)
2526
"please specify an explicit base with -r,\n"
2527
"and (if you want) report this to the bzr developers\n")
2530
# TODO: move up to common parent; this isn't merge-specific anymore.
2531
def _get_remembered_parent(self, tree, supplied_location, verb_string):
4177
# Use reprocess if the merger supports it
4178
merger.reprocess = merger.merge_type.supports_reprocess
4179
if merger.reprocess and not merger.merge_type.supports_reprocess:
4180
raise errors.BzrCommandError("Conflict reduction is not supported"
4181
" for merge type %s." %
4183
if merger.reprocess and merger.show_base:
4184
raise errors.BzrCommandError("Cannot do conflict reduction and"
4187
def _get_merger_from_branch(self, tree, location, revision, remember,
4188
possible_transports, pb):
4189
"""Produce a merger from a location, assuming it refers to a branch."""
4190
from bzrlib.tag import _merge_tags_if_possible
4191
# find the branch locations
4192
other_loc, user_location = self._select_branch_location(tree, location,
4194
if revision is not None and len(revision) == 2:
4195
base_loc, _unused = self._select_branch_location(tree,
4196
location, revision, 0)
4198
base_loc = other_loc
4200
other_branch, other_path = Branch.open_containing(other_loc,
4201
possible_transports)
4202
if base_loc == other_loc:
4203
base_branch = other_branch
4205
base_branch, base_path = Branch.open_containing(base_loc,
4206
possible_transports)
4207
# Find the revision ids
4208
other_revision_id = None
4209
base_revision_id = None
4210
if revision is not None:
4211
if len(revision) >= 1:
4212
other_revision_id = revision[-1].as_revision_id(other_branch)
4213
if len(revision) == 2:
4214
base_revision_id = revision[0].as_revision_id(base_branch)
4215
if other_revision_id is None:
4216
other_revision_id = _mod_revision.ensure_null(
4217
other_branch.last_revision())
4218
# Remember where we merge from. We need to remember if:
4219
# - user specify a location (and we don't merge from the parent
4221
# - user ask to remember or there is no previous location set to merge
4222
# from and user didn't ask to *not* remember
4223
if (user_location is not None
4225
or (remember is None
4226
and tree.branch.get_submit_branch() is None)))):
4227
tree.branch.set_submit_branch(other_branch.base)
4228
# Merge tags (but don't set them in the master branch yet, the user
4229
# might revert this merge). Commit will propagate them.
4230
_merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
4231
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4232
other_revision_id, base_revision_id, other_branch, base_branch)
4233
if other_path != '':
4234
allow_pending = False
4235
merger.interesting_files = [other_path]
4237
allow_pending = True
4238
return merger, allow_pending
4240
def get_merger_from_uncommitted(self, tree, location, pb):
4241
"""Get a merger for uncommitted changes.
4243
:param tree: The tree the merger should apply to.
4244
:param location: The location containing uncommitted changes.
4245
:param pb: The progress bar to use for showing progress.
4247
location = self._select_branch_location(tree, location)[0]
4248
other_tree, other_path = WorkingTree.open_containing(location)
4249
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
4250
if other_path != '':
4251
merger.interesting_files = [other_path]
4254
def _select_branch_location(self, tree, user_location, revision=None,
4256
"""Select a branch location, according to possible inputs.
4258
If provided, branches from ``revision`` are preferred. (Both
4259
``revision`` and ``index`` must be supplied.)
4261
Otherwise, the ``location`` parameter is used. If it is None, then the
4262
``submit`` or ``parent`` location is used, and a note is printed.
4264
:param tree: The working tree to select a branch for merging into
4265
:param location: The location entered by the user
4266
:param revision: The revision parameter to the command
4267
:param index: The index to use for the revision parameter. Negative
4268
indices are permitted.
4269
:return: (selected_location, user_location). The default location
4270
will be the user-entered location.
4272
if (revision is not None and index is not None
4273
and revision[index] is not None):
4274
branch = revision[index].get_branch()
4275
if branch is not None:
4276
return branch, branch
4277
if user_location is None:
4278
location = self._get_remembered(tree, 'Merging from')
4280
location = user_location
4281
return location, user_location
4283
def _get_remembered(self, tree, verb_string):
2532
4284
"""Use tree.branch's parent if none was supplied.
2534
4286
Report if the remembered location was used.
2536
if supplied_location is not None:
2537
return supplied_location
2538
stored_location = tree.branch.get_parent()
4288
stored_location = tree.branch.get_submit_branch()
4289
stored_location_type = "submit"
4290
if stored_location is None:
4291
stored_location = tree.branch.get_parent()
4292
stored_location_type = "parent"
2539
4293
mutter("%s", stored_location)
2540
4294
if stored_location is None:
2541
4295
raise errors.BzrCommandError("No location specified or remembered")
2542
display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2543
self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
4296
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4297
note(u"%s remembered %s location %s", verb_string,
4298
stored_location_type, display_url)
2544
4299
return stored_location
2547
4302
class cmd_remerge(Command):
4303
__doc__ = """Redo a merge.
2550
4305
Use this if you want to try a different merge technique while resolving
2551
conflicts. Some merge techniques are better than others, and remerge
4306
conflicts. Some merge techniques are better than others, and remerge
2552
4307
lets you try different ones on different files.
2554
4309
The options for remerge have the same meaning and defaults as the ones for
2555
4310
merge. The difference is that remerge can (only) be run when there is a
2556
4311
pending merge, and it lets you specify particular files.
2559
$ bzr remerge --show-base
2560
4314
Re-do the merge of all conflicted files, and show the base text in
2561
conflict regions, in addition to the usual THIS and OTHER texts.
2563
$ bzr remerge --merge-type weave --reprocess foobar
4315
conflict regions, in addition to the usual THIS and OTHER texts::
4317
bzr remerge --show-base
2564
4319
Re-do the merge of "foobar", using the weave merge algorithm, with
2565
additional processing to reduce the size of conflict regions.
2567
The following merge types are available:"""
4320
additional processing to reduce the size of conflict regions::
4322
bzr remerge --merge-type weave --reprocess foobar
2568
4324
takes_args = ['file*']
2569
takes_options = ['merge-type', 'reprocess',
2570
Option('show-base', help="Show base revision text in "
4329
help="Show base revision text in conflicts."),
2573
4332
def run(self, file_list=None, merge_type=None, show_base=False,
2574
4333
reprocess=False):
4334
from bzrlib.conflicts import restore
2575
4335
if merge_type is None:
2576
4336
merge_type = _mod_merge.Merge3Merger
2577
tree, file_list = tree_files(file_list)
4337
tree, file_list = WorkingTree.open_containing_paths(file_list)
4338
self.add_cleanup(tree.lock_write().unlock)
4339
parents = tree.get_parent_ids()
4340
if len(parents) != 2:
4341
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4342
" merges. Not cherrypicking or"
4344
repository = tree.branch.repository
4345
interesting_ids = None
4347
conflicts = tree.conflicts()
4348
if file_list is not None:
4349
interesting_ids = set()
4350
for filename in file_list:
4351
file_id = tree.path2id(filename)
4353
raise errors.NotVersionedError(filename)
4354
interesting_ids.add(file_id)
4355
if tree.kind(file_id) != "directory":
4358
for name, ie in tree.inventory.iter_entries(file_id):
4359
interesting_ids.add(ie.file_id)
4360
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4362
# Remerge only supports resolving contents conflicts
4363
allowed_conflicts = ('text conflict', 'contents conflict')
4364
restore_files = [c.path for c in conflicts
4365
if c.typestring in allowed_conflicts]
4366
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4367
tree.set_conflicts(ConflictList(new_conflicts))
4368
if file_list is not None:
4369
restore_files = file_list
4370
for filename in restore_files:
4372
restore(tree.abspath(filename))
4373
except errors.NotConflicted:
4375
# Disable pending merges, because the file texts we are remerging
4376
# have not had those merges performed. If we use the wrong parents
4377
# list, we imply that the working tree text has seen and rejected
4378
# all the changes from the other tree, when in fact those changes
4379
# have not yet been seen.
4380
tree.set_parent_ids(parents[:1])
2580
parents = tree.get_parent_ids()
2581
if len(parents) != 2:
2582
raise errors.BzrCommandError("Sorry, remerge only works after normal"
2583
" merges. Not cherrypicking or"
2585
repository = tree.branch.repository
2586
base_revision = common_ancestor(parents[0],
2587
parents[1], repository)
2588
base_tree = repository.revision_tree(base_revision)
2589
other_tree = repository.revision_tree(parents[1])
2590
interesting_ids = None
2592
conflicts = tree.conflicts()
2593
if file_list is not None:
2594
interesting_ids = set()
2595
for filename in file_list:
2596
file_id = tree.path2id(filename)
2598
raise errors.NotVersionedError(filename)
2599
interesting_ids.add(file_id)
2600
if tree.kind(file_id) != "directory":
2603
for name, ie in tree.inventory.iter_entries(file_id):
2604
interesting_ids.add(ie.file_id)
2605
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2607
# Remerge only supports resolving contents conflicts
2608
allowed_conflicts = ('text conflict', 'contents conflict')
2609
restore_files = [c.path for c in conflicts
2610
if c.typestring in allowed_conflicts]
2611
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
2612
tree.set_conflicts(ConflictList(new_conflicts))
2613
if file_list is not None:
2614
restore_files = file_list
2615
for filename in restore_files:
2617
restore(tree.abspath(filename))
2618
except errors.NotConflicted:
2620
conflicts = _mod_merge.merge_inner(
2621
tree.branch, other_tree, base_tree,
2623
interesting_ids=interesting_ids,
2624
other_rev_id=parents[1],
2625
merge_type=merge_type,
2626
show_base=show_base,
2627
reprocess=reprocess)
4382
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4383
merger.interesting_ids = interesting_ids
4384
merger.merge_type = merge_type
4385
merger.show_base = show_base
4386
merger.reprocess = reprocess
4387
conflicts = merger.do_merge()
4389
tree.set_parent_ids(parents)
2630
4390
if conflicts > 0:
2712
4497
class cmd_shell_complete(Command):
2713
"""Show appropriate completions for context.
4498
__doc__ = """Show appropriate completions for context.
2715
4500
For a list of all available commands, say 'bzr shell-complete'.
2717
4502
takes_args = ['context?']
2718
4503
aliases = ['s-c']
2721
4506
@display_command
2722
4507
def run(self, context=None):
2723
4508
import shellcomplete
2724
4509
shellcomplete.shellcomplete(context)
2727
class cmd_fetch(Command):
2728
"""Copy in history from another branch but don't merge it.
2730
This is an internal method used for pull and merge.
2733
takes_args = ['from_branch', 'to_branch']
2734
def run(self, from_branch, to_branch):
2735
from bzrlib.fetch import Fetcher
2736
from_b = Branch.open(from_branch)
2737
to_b = Branch.open(to_branch)
2738
Fetcher(to_b, from_b)
2741
4512
class cmd_missing(Command):
2742
"""Show unmerged/unpulled revisions between two branches.
4513
__doc__ = """Show unmerged/unpulled revisions between two branches.
2744
4515
OTHER_BRANCH may be local or remote.
4517
To filter on a range of revisions, you can use the command -r begin..end
4518
-r revision requests a specific revision, -r ..end or -r begin.. are
4522
1 - some missing revisions
4523
0 - no missing revisions
4527
Determine the missing revisions between this and the branch at the
4528
remembered pull location::
4532
Determine the missing revisions between this and another branch::
4534
bzr missing http://server/branch
4536
Determine the missing revisions up to a specific revision on the other
4539
bzr missing -r ..-10
4541
Determine the missing revisions up to a specific revision on this
4544
bzr missing --my-revision ..-10
4547
_see_also = ['merge', 'pull']
2746
4548
takes_args = ['other_branch?']
2747
takes_options = [Option('reverse', 'Reverse the order of revisions'),
2749
'Display changes in the local branch only'),
2750
Option('theirs-only',
2751
'Display changes in the remote branch only'),
4551
Option('reverse', 'Reverse the order of revisions.'),
4553
'Display changes in the local branch only.'),
4554
Option('this' , 'Same as --mine-only.'),
4555
Option('theirs-only',
4556
'Display changes in the remote branch only.'),
4557
Option('other', 'Same as --theirs-only.'),
4561
custom_help('revision',
4562
help='Filter on other branch revisions (inclusive). '
4563
'See "help revisionspec" for details.'),
4564
Option('my-revision',
4565
type=_parse_revision_str,
4566
help='Filter on local branch revisions (inclusive). '
4567
'See "help revisionspec" for details.'),
4568
Option('include-merges',
4569
'Show all revisions in addition to the mainline ones.'),
2756
4571
encoding_type = 'replace'
2758
4573
@display_command
2759
4574
def run(self, other_branch=None, reverse=False, mine_only=False,
2760
theirs_only=False, log_format=None, long=False, short=False, line=False,
2761
show_ids=False, verbose=False):
2762
from bzrlib.missing import find_unmerged, iter_log_data
2763
from bzrlib.log import log_formatter
2764
local_branch = Branch.open_containing(u".")[0]
4576
log_format=None, long=False, short=False, line=False,
4577
show_ids=False, verbose=False, this=False, other=False,
4578
include_merges=False, revision=None, my_revision=None,
4580
from bzrlib.missing import find_unmerged, iter_log_revisions
4589
# TODO: We should probably check that we don't have mine-only and
4590
# theirs-only set, but it gets complicated because we also have
4591
# this and other which could be used.
4598
local_branch = Branch.open_containing(directory)[0]
4599
self.add_cleanup(local_branch.lock_read().unlock)
2765
4601
parent = local_branch.get_parent()
2766
4602
if other_branch is None:
2767
4603
other_branch = parent
2768
4604
if other_branch is None:
2769
raise errors.BzrCommandError("No peer location known or specified.")
4605
raise errors.BzrCommandError("No peer location known"
2770
4607
display_url = urlutils.unescape_for_display(parent,
2771
4608
self.outf.encoding)
2772
print "Using last location: " + display_url
4609
message("Using saved parent location: "
4610
+ display_url + "\n")
2774
4612
remote_branch = Branch.open(other_branch)
2775
4613
if remote_branch.base == local_branch.base:
2776
4614
remote_branch = local_branch
2777
local_branch.lock_read()
2779
remote_branch.lock_read()
2781
local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2782
if (log_format is None):
2783
log_format = log.log_formatter_registry.get_default(
2785
lf = log_format(to_file=self.outf,
2787
show_timezone='original')
2788
if reverse is False:
2789
local_extra.reverse()
2790
remote_extra.reverse()
2791
if local_extra and not theirs_only:
2792
print "You have %d extra revision(s):" % len(local_extra)
2793
for data in iter_log_data(local_extra, local_branch.repository,
2796
printed_local = True
2798
printed_local = False
2799
if remote_extra and not mine_only:
2800
if printed_local is True:
2802
print "You are missing %d revision(s):" % len(remote_extra)
2803
for data in iter_log_data(remote_extra, remote_branch.repository,
2806
if not remote_extra and not local_extra:
2808
print "Branches are up to date."
2812
remote_branch.unlock()
2814
local_branch.unlock()
4616
self.add_cleanup(remote_branch.lock_read().unlock)
4618
local_revid_range = _revision_range_to_revid_range(
4619
_get_revision_range(my_revision, local_branch,
4622
remote_revid_range = _revision_range_to_revid_range(
4623
_get_revision_range(revision,
4624
remote_branch, self.name()))
4626
local_extra, remote_extra = find_unmerged(
4627
local_branch, remote_branch, restrict,
4628
backward=not reverse,
4629
include_merges=include_merges,
4630
local_revid_range=local_revid_range,
4631
remote_revid_range=remote_revid_range)
4633
if log_format is None:
4634
registry = log.log_formatter_registry
4635
log_format = registry.get_default(local_branch)
4636
lf = log_format(to_file=self.outf,
4638
show_timezone='original')
4641
if local_extra and not theirs_only:
4642
message("You have %d extra revision(s):\n" %
4644
for revision in iter_log_revisions(local_extra,
4645
local_branch.repository,
4647
lf.log_revision(revision)
4648
printed_local = True
4651
printed_local = False
4653
if remote_extra and not mine_only:
4654
if printed_local is True:
4656
message("You are missing %d revision(s):\n" %
4658
for revision in iter_log_revisions(remote_extra,
4659
remote_branch.repository,
4661
lf.log_revision(revision)
4664
if mine_only and not local_extra:
4665
# We checked local, and found nothing extra
4666
message('This branch is up to date.\n')
4667
elif theirs_only and not remote_extra:
4668
# We checked remote, and found nothing extra
4669
message('Other branch is up to date.\n')
4670
elif not (mine_only or theirs_only or local_extra or
4672
# We checked both branches, and neither one had extra
4674
message("Branches are up to date.\n")
2815
4676
if not status_code and parent is None and other_branch is not None:
2816
local_branch.lock_write()
2818
# handle race conditions - a parent might be set while we run.
2819
if local_branch.get_parent() is None:
2820
local_branch.set_parent(remote_branch.base)
2822
local_branch.unlock()
4677
self.add_cleanup(local_branch.lock_write().unlock)
4678
# handle race conditions - a parent might be set while we run.
4679
if local_branch.get_parent() is None:
4680
local_branch.set_parent(remote_branch.base)
2823
4681
return status_code
4684
class cmd_pack(Command):
4685
__doc__ = """Compress the data within a repository.
4687
This operation compresses the data within a bazaar repository. As
4688
bazaar supports automatic packing of repository, this operation is
4689
normally not required to be done manually.
4691
During the pack operation, bazaar takes a backup of existing repository
4692
data, i.e. pack files. This backup is eventually removed by bazaar
4693
automatically when it is safe to do so. To save disk space by removing
4694
the backed up pack files, the --clean-obsolete-packs option may be
4697
Warning: If you use --clean-obsolete-packs and your machine crashes
4698
during or immediately after repacking, you may be left with a state
4699
where the deletion has been written to disk but the new packs have not
4700
been. In this case the repository may be unusable.
4703
_see_also = ['repositories']
4704
takes_args = ['branch_or_repo?']
4706
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4709
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4710
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4712
branch = dir.open_branch()
4713
repository = branch.repository
4714
except errors.NotBranchError:
4715
repository = dir.open_repository()
4716
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
2826
4719
class cmd_plugins(Command):
4720
__doc__ = """List the installed plugins.
4722
This command displays the list of installed plugins including
4723
version of plugin and a short description of each.
4725
--verbose shows the path where each plugin is located.
4727
A plugin is an external component for Bazaar that extends the
4728
revision control system, by adding or replacing code in Bazaar.
4729
Plugins can do a variety of things, including overriding commands,
4730
adding new commands, providing additional network transports and
4731
customizing log output.
4733
See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4734
for further information on plugins including where to find them and how to
4735
install them. Instructions are also provided there on how to write new
4736
plugins using the Python programming language.
4738
takes_options = ['verbose']
2829
4740
@display_command
2831
import bzrlib.plugin
2832
from inspect import getdoc
2833
for name, plugin in bzrlib.plugin.all_plugins().items():
2834
if getattr(plugin, '__path__', None) is not None:
2835
print plugin.__path__[0]
2836
elif getattr(plugin, '__file__', None) is not None:
2837
print plugin.__file__
2843
print '\t', d.split('\n')[0]
4741
def run(self, verbose=False):
4742
from bzrlib import plugin
4743
# Don't give writelines a generator as some codecs don't like that
4744
self.outf.writelines(
4745
list(plugin.describe_plugins(show_paths=verbose)))
2846
4748
class cmd_testament(Command):
2847
"""Show testament (signing-form) of a revision."""
2848
takes_options = ['revision',
2849
Option('long', help='Produce long-format testament'),
2850
Option('strict', help='Produce a strict-format'
4749
__doc__ = """Show testament (signing-form) of a revision."""
4752
Option('long', help='Produce long-format testament.'),
4754
help='Produce a strict-format testament.')]
2852
4755
takes_args = ['branch?']
2853
4756
@display_command
2854
4757
def run(self, branch=u'.', revision=None, long=False, strict=False):
3128
5121
class cmd_serve(Command):
3129
"""Run the bzr server."""
5122
__doc__ = """Run the bzr server."""
3131
5124
aliases = ['server']
3133
5126
takes_options = [
3135
help='serve on stdin/out for use from inetd or sshd'),
5128
help='Serve on stdin/out for use from inetd or sshd.'),
5129
RegistryOption('protocol',
5130
help="Protocol to serve.",
5131
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
5132
value_switches=True),
3137
help='listen for connections on nominated port of the form '
3138
'[hostname:]portnumber. Passing 0 as the port number will '
3139
'result in a dynamically allocated port.',
5134
help='Listen for connections on nominated port of the form '
5135
'[hostname:]portnumber. Passing 0 as the port number will '
5136
'result in a dynamically allocated port. The default port '
5137
'depends on the protocol.',
3142
help='serve contents of directory',
5139
custom_help('directory',
5140
help='Serve contents of this directory.'),
3144
5141
Option('allow-writes',
3145
help='By default the server is a readonly server. Supplying '
5142
help='By default the server is a readonly server. Supplying '
3146
5143
'--allow-writes enables write access to the contents of '
3147
'the served directory and below. '
5144
'the served directory and below. Note that ``bzr serve`` '
5145
'does not perform authentication, so unless some form of '
5146
'external authentication is arranged supplying this '
5147
'option leads to global uncontrolled write access to your '
3151
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3152
from bzrlib.transport import smart
3153
from bzrlib.transport import get_transport
5152
def get_host_and_port(self, port):
5153
"""Return the host and port to run the smart server on.
5155
If 'port' is None, None will be returned for the host and port.
5157
If 'port' has a colon in it, the string before the colon will be
5158
interpreted as the host.
5160
:param port: A string of the port to run the server on.
5161
:return: A tuple of (host, port), where 'host' is a host name or IP,
5162
and port is an integer TCP/IP port.
5165
if port is not None:
5167
host, port = port.split(':')
5171
def run(self, port=None, inet=False, directory=None, allow_writes=False,
5173
from bzrlib import transport
3154
5174
if directory is None:
3155
5175
directory = os.getcwd()
5176
if protocol is None:
5177
protocol = transport.transport_server_registry.get()
5178
host, port = self.get_host_and_port(port)
3156
5179
url = urlutils.local_path_to_url(directory)
3157
5180
if not allow_writes:
3158
5181
url = 'readonly+' + url
3159
t = get_transport(url)
3161
server = smart.SmartServerPipeStreamMedium(sys.stdin, sys.stdout, t)
3162
elif port is not None:
3164
host, port = port.split(':')
3167
server = smart.SmartTCPServer(t, host=host, port=int(port))
3168
print 'listening on port: ', server.port
3171
raise errors.BzrCommandError("bzr serve requires one of --inet or --port")
3175
# command-line interpretation helper for merge-related commands
3176
def _merge_helper(other_revision, base_revision,
3177
check_clean=True, ignore_zero=False,
3178
this_dir=None, backup_files=False,
3180
file_list=None, show_base=False, reprocess=False,
3183
change_reporter=None):
3184
"""Merge changes into a tree.
3187
list(path, revno) Base for three-way merge.
3188
If [None, None] then a base will be automatically determined.
3190
list(path, revno) Other revision for three-way merge.
3192
Directory to merge changes into; '.' by default.
3194
If true, this_dir must have no uncommitted changes before the
3196
ignore_zero - If true, suppress the "zero conflicts" message when
3197
there are no conflicts; should be set when doing something we expect
3198
to complete perfectly.
3199
file_list - If supplied, merge only changes to selected files.
3201
All available ancestors of other_revision and base_revision are
3202
automatically pulled into the branch.
3204
The revno may be -1 to indicate the last revision on the branch, which is
3207
This function is intended for use from the command line; programmatic
3208
clients might prefer to call merge.merge_inner(), which has less magic
3211
# Loading it late, so that we don't always have to import bzrlib.merge
3212
if merge_type is None:
3213
merge_type = _mod_merge.Merge3Merger
3214
if this_dir is None:
3216
this_tree = WorkingTree.open_containing(this_dir)[0]
3217
if show_base and not merge_type is _mod_merge.Merge3Merger:
3218
raise errors.BzrCommandError("Show-base is not supported for this merge"
3219
" type. %s" % merge_type)
3220
if reprocess and not merge_type.supports_reprocess:
3221
raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3222
" type %s." % merge_type)
3223
if reprocess and show_base:
3224
raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3226
merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3227
pb=pb, change_reporter=change_reporter)
3228
merger.pp = ProgressPhase("Merge phase", 5, pb)
3229
merger.pp.next_phase()
3230
merger.check_basis(check_clean)
3231
merger.set_other(other_revision)
3232
merger.pp.next_phase()
3233
merger.set_base(base_revision)
3234
if merger.base_rev_id == merger.other_rev_id:
3235
note('Nothing to do.')
3237
if file_list is None:
3238
if pull and merger.base_rev_id == merger.this_rev_id:
3239
count = merger.this_tree.pull(merger.this_branch,
3240
False, merger.other_rev_id)
3241
note('%d revision(s) pulled.' % (count,))
3243
merger.backup_files = backup_files
3244
merger.merge_type = merge_type
3245
merger.set_interesting_files(file_list)
3246
merger.show_base = show_base
3247
merger.reprocess = reprocess
3248
conflicts = merger.do_merge()
3249
if file_list is None:
3250
merger.set_pending()
3257
merge = _merge_helper
3260
# these get imported and then picked up by the scan for cmd_*
3261
# TODO: Some more consistent way to split command definitions across files;
3262
# we do need to load at least some information about them to know of
3263
# aliases. ideally we would avoid loading the implementation until the
3264
# details were needed.
3265
from bzrlib.cmd_version_info import cmd_version_info
3266
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3267
from bzrlib.bundle.commands import cmd_bundle_revisions
3268
from bzrlib.sign_my_commits import cmd_sign_my_commits
3269
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
3270
cmd_weave_plan_merge, cmd_weave_merge_text
5182
t = transport.get_transport(url)
5183
protocol(t, host, port, inet)
5186
class cmd_join(Command):
5187
__doc__ = """Combine a tree into its containing tree.
5189
This command requires the target tree to be in a rich-root format.
5191
The TREE argument should be an independent tree, inside another tree, but
5192
not part of it. (Such trees can be produced by "bzr split", but also by
5193
running "bzr branch" with the target inside a tree.)
5195
The result is a combined tree, with the subtree no longer an independent
5196
part. This is marked as a merge of the subtree into the containing tree,
5197
and all history is preserved.
5200
_see_also = ['split']
5201
takes_args = ['tree']
5203
Option('reference', help='Join by reference.', hidden=True),
5206
def run(self, tree, reference=False):
5207
sub_tree = WorkingTree.open(tree)
5208
parent_dir = osutils.dirname(sub_tree.basedir)
5209
containing_tree = WorkingTree.open_containing(parent_dir)[0]
5210
repo = containing_tree.branch.repository
5211
if not repo.supports_rich_root():
5212
raise errors.BzrCommandError(
5213
"Can't join trees because %s doesn't support rich root data.\n"
5214
"You can use bzr upgrade on the repository."
5218
containing_tree.add_reference(sub_tree)
5219
except errors.BadReferenceTarget, e:
5220
# XXX: Would be better to just raise a nicely printable
5221
# exception from the real origin. Also below. mbp 20070306
5222
raise errors.BzrCommandError("Cannot join %s. %s" %
5226
containing_tree.subsume(sub_tree)
5227
except errors.BadSubsumeSource, e:
5228
raise errors.BzrCommandError("Cannot join %s. %s" %
5232
class cmd_split(Command):
5233
__doc__ = """Split a subdirectory of a tree into a separate tree.
5235
This command will produce a target tree in a format that supports
5236
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
5237
converted into earlier formats like 'dirstate-tags'.
5239
The TREE argument should be a subdirectory of a working tree. That
5240
subdirectory will be converted into an independent tree, with its own
5241
branch. Commits in the top-level tree will not apply to the new subtree.
5244
_see_also = ['join']
5245
takes_args = ['tree']
5247
def run(self, tree):
5248
containing_tree, subdir = WorkingTree.open_containing(tree)
5249
sub_id = containing_tree.path2id(subdir)
5251
raise errors.NotVersionedError(subdir)
5253
containing_tree.extract(sub_id)
5254
except errors.RootNotRich:
5255
raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
5258
class cmd_merge_directive(Command):
5259
__doc__ = """Generate a merge directive for auto-merge tools.
5261
A directive requests a merge to be performed, and also provides all the
5262
information necessary to do so. This means it must either include a
5263
revision bundle, or the location of a branch containing the desired
5266
A submit branch (the location to merge into) must be supplied the first
5267
time the command is issued. After it has been supplied once, it will
5268
be remembered as the default.
5270
A public branch is optional if a revision bundle is supplied, but required
5271
if --diff or --plain is specified. It will be remembered as the default
5272
after the first use.
5275
takes_args = ['submit_branch?', 'public_branch?']
5279
_see_also = ['send']
5283
RegistryOption.from_kwargs('patch-type',
5284
'The type of patch to include in the directive.',
5286
value_switches=True,
5288
bundle='Bazaar revision bundle (default).',
5289
diff='Normal unified diff.',
5290
plain='No patch, just directive.'),
5291
Option('sign', help='GPG-sign the directive.'), 'revision',
5292
Option('mail-to', type=str,
5293
help='Instead of printing the directive, email to this address.'),
5294
Option('message', type=str, short_name='m',
5295
help='Message to use when committing this merge.')
5298
encoding_type = 'exact'
5300
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5301
sign=False, revision=None, mail_to=None, message=None,
5303
from bzrlib.revision import ensure_null, NULL_REVISION
5304
include_patch, include_bundle = {
5305
'plain': (False, False),
5306
'diff': (True, False),
5307
'bundle': (True, True),
5309
branch = Branch.open(directory)
5310
stored_submit_branch = branch.get_submit_branch()
5311
if submit_branch is None:
5312
submit_branch = stored_submit_branch
5314
if stored_submit_branch is None:
5315
branch.set_submit_branch(submit_branch)
5316
if submit_branch is None:
5317
submit_branch = branch.get_parent()
5318
if submit_branch is None:
5319
raise errors.BzrCommandError('No submit branch specified or known')
5321
stored_public_branch = branch.get_public_branch()
5322
if public_branch is None:
5323
public_branch = stored_public_branch
5324
elif stored_public_branch is None:
5325
branch.set_public_branch(public_branch)
5326
if not include_bundle and public_branch is None:
5327
raise errors.BzrCommandError('No public branch specified or'
5329
base_revision_id = None
5330
if revision is not None:
5331
if len(revision) > 2:
5332
raise errors.BzrCommandError('bzr merge-directive takes '
5333
'at most two one revision identifiers')
5334
revision_id = revision[-1].as_revision_id(branch)
5335
if len(revision) == 2:
5336
base_revision_id = revision[0].as_revision_id(branch)
5338
revision_id = branch.last_revision()
5339
revision_id = ensure_null(revision_id)
5340
if revision_id == NULL_REVISION:
5341
raise errors.BzrCommandError('No revisions to bundle.')
5342
directive = merge_directive.MergeDirective2.from_objects(
5343
branch.repository, revision_id, time.time(),
5344
osutils.local_time_offset(), submit_branch,
5345
public_branch=public_branch, include_patch=include_patch,
5346
include_bundle=include_bundle, message=message,
5347
base_revision_id=base_revision_id)
5350
self.outf.write(directive.to_signed(branch))
5352
self.outf.writelines(directive.to_lines())
5354
message = directive.to_email(mail_to, branch, sign)
5355
s = SMTPConnection(branch.get_config())
5356
s.send_email(message)
5359
class cmd_send(Command):
5360
__doc__ = """Mail or create a merge-directive for submitting changes.
5362
A merge directive provides many things needed for requesting merges:
5364
* A machine-readable description of the merge to perform
5366
* An optional patch that is a preview of the changes requested
5368
* An optional bundle of revision data, so that the changes can be applied
5369
directly from the merge directive, without retrieving data from a
5372
`bzr send` creates a compact data set that, when applied using bzr
5373
merge, has the same effect as merging from the source branch.
5375
By default the merge directive is self-contained and can be applied to any
5376
branch containing submit_branch in its ancestory without needing access to
5379
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5380
revisions, but only a structured request to merge from the
5381
public_location. In that case the public_branch is needed and it must be
5382
up-to-date and accessible to the recipient. The public_branch is always
5383
included if known, so that people can check it later.
5385
The submit branch defaults to the parent of the source branch, but can be
5386
overridden. Both submit branch and public branch will be remembered in
5387
branch.conf the first time they are used for a particular branch. The
5388
source branch defaults to that containing the working directory, but can
5389
be changed using --from.
5391
Both the submit branch and the public branch follow the usual behavior with
5392
respect to --remember: If there is no default location set, the first send
5393
will set it (use --no-remember to avoid settting it). After that, you can
5394
omit the location to use the default. To change the default, use
5395
--remember. The value will only be saved if the location can be accessed.
5397
In order to calculate those changes, bzr must analyse the submit branch.
5398
Therefore it is most efficient for the submit branch to be a local mirror.
5399
If a public location is known for the submit_branch, that location is used
5400
in the merge directive.
5402
The default behaviour is to send the merge directive by mail, unless -o is
5403
given, in which case it is sent to a file.
5405
Mail is sent using your preferred mail program. This should be transparent
5406
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
5407
If the preferred client can't be found (or used), your editor will be used.
5409
To use a specific mail program, set the mail_client configuration option.
5410
(For Thunderbird 1.5, this works around some bugs.) Supported values for
5411
specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5412
Mail.app), "mutt", and "thunderbird"; generic options are "default",
5413
"editor", "emacsclient", "mapi", and "xdg-email". Plugins may also add
5416
If mail is being sent, a to address is required. This can be supplied
5417
either on the commandline, by setting the submit_to configuration
5418
option in the branch itself or the child_submit_to configuration option
5419
in the submit branch.
5421
Two formats are currently supported: "4" uses revision bundle format 4 and
5422
merge directive format 2. It is significantly faster and smaller than
5423
older formats. It is compatible with Bazaar 0.19 and later. It is the
5424
default. "0.9" uses revision bundle format 0.9 and merge directive
5425
format 1. It is compatible with Bazaar 0.12 - 0.18.
5427
The merge directives created by bzr send may be applied using bzr merge or
5428
bzr pull by specifying a file containing a merge directive as the location.
5430
bzr send makes extensive use of public locations to map local locations into
5431
URLs that can be used by other people. See `bzr help configuration` to
5432
set them, and use `bzr info` to display them.
5435
encoding_type = 'exact'
5437
_see_also = ['merge', 'pull']
5439
takes_args = ['submit_branch?', 'public_branch?']
5443
help='Do not include a bundle in the merge directive.'),
5444
Option('no-patch', help='Do not include a preview patch in the merge'
5447
help='Remember submit and public branch.'),
5449
help='Branch to generate the submission from, '
5450
'rather than the one containing the working directory.',
5453
Option('output', short_name='o',
5454
help='Write merge directive to this file or directory; '
5455
'use - for stdout.',
5458
help='Refuse to send if there are uncommitted changes in'
5459
' the working tree, --no-strict disables the check.'),
5460
Option('mail-to', help='Mail the request to this address.',
5464
Option('body', help='Body for the email.', type=unicode),
5465
RegistryOption('format',
5466
help='Use the specified output format.',
5467
lazy_registry=('bzrlib.send', 'format_registry')),
5470
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5471
no_patch=False, revision=None, remember=None, output=None,
5472
format=None, mail_to=None, message=None, body=None,
5473
strict=None, **kwargs):
5474
from bzrlib.send import send
5475
return send(submit_branch, revision, public_branch, remember,
5476
format, no_bundle, no_patch, output,
5477
kwargs.get('from', '.'), mail_to, message, body,
5482
class cmd_bundle_revisions(cmd_send):
5483
__doc__ = """Create a merge-directive for submitting changes.
5485
A merge directive provides many things needed for requesting merges:
5487
* A machine-readable description of the merge to perform
5489
* An optional patch that is a preview of the changes requested
5491
* An optional bundle of revision data, so that the changes can be applied
5492
directly from the merge directive, without retrieving data from a
5495
If --no-bundle is specified, then public_branch is needed (and must be
5496
up-to-date), so that the receiver can perform the merge using the
5497
public_branch. The public_branch is always included if known, so that
5498
people can check it later.
5500
The submit branch defaults to the parent, but can be overridden. Both
5501
submit branch and public branch will be remembered if supplied.
5503
If a public_branch is known for the submit_branch, that public submit
5504
branch is used in the merge instructions. This means that a local mirror
5505
can be used as your actual submit branch, once you have set public_branch
5508
Two formats are currently supported: "4" uses revision bundle format 4 and
5509
merge directive format 2. It is significantly faster and smaller than
5510
older formats. It is compatible with Bazaar 0.19 and later. It is the
5511
default. "0.9" uses revision bundle format 0.9 and merge directive
5512
format 1. It is compatible with Bazaar 0.12 - 0.18.
5517
help='Do not include a bundle in the merge directive.'),
5518
Option('no-patch', help='Do not include a preview patch in the merge'
5521
help='Remember submit and public branch.'),
5523
help='Branch to generate the submission from, '
5524
'rather than the one containing the working directory.',
5527
Option('output', short_name='o', help='Write directive to this file.',
5530
help='Refuse to bundle revisions if there are uncommitted'
5531
' changes in the working tree, --no-strict disables the check.'),
5533
RegistryOption('format',
5534
help='Use the specified output format.',
5535
lazy_registry=('bzrlib.send', 'format_registry')),
5537
aliases = ['bundle']
5539
_see_also = ['send', 'merge']
5543
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5544
no_patch=False, revision=None, remember=False, output=None,
5545
format=None, strict=None, **kwargs):
5548
from bzrlib.send import send
5549
return send(submit_branch, revision, public_branch, remember,
5550
format, no_bundle, no_patch, output,
5551
kwargs.get('from', '.'), None, None, None,
5552
self.outf, strict=strict)
5555
class cmd_tag(Command):
5556
__doc__ = """Create, remove or modify a tag naming a revision.
5558
Tags give human-meaningful names to revisions. Commands that take a -r
5559
(--revision) option can be given -rtag:X, where X is any previously
5562
Tags are stored in the branch. Tags are copied from one branch to another
5563
along when you branch, push, pull or merge.
5565
It is an error to give a tag name that already exists unless you pass
5566
--force, in which case the tag is moved to point to the new revision.
5568
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5569
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5571
If no tag name is specified it will be determined through the
5572
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5573
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5577
_see_also = ['commit', 'tags']
5578
takes_args = ['tag_name?']
5581
help='Delete this tag rather than placing it.',
5583
custom_help('directory',
5584
help='Branch in which to place the tag.'),
5586
help='Replace existing tags.',
5591
def run(self, tag_name=None,
5597
branch, relpath = Branch.open_containing(directory)
5598
self.add_cleanup(branch.lock_write().unlock)
5600
if tag_name is None:
5601
raise errors.BzrCommandError("No tag specified to delete.")
5602
branch.tags.delete_tag(tag_name)
5603
note('Deleted tag %s.' % tag_name)
5606
if len(revision) != 1:
5607
raise errors.BzrCommandError(
5608
"Tags can only be placed on a single revision, "
5610
revision_id = revision[0].as_revision_id(branch)
5612
revision_id = branch.last_revision()
5613
if tag_name is None:
5614
tag_name = branch.automatic_tag_name(revision_id)
5615
if tag_name is None:
5616
raise errors.BzrCommandError(
5617
"Please specify a tag name.")
5618
if (not force) and branch.tags.has_tag(tag_name):
5619
raise errors.TagAlreadyExists(tag_name)
5620
branch.tags.set_tag(tag_name, revision_id)
5621
note('Created tag %s.' % tag_name)
5624
class cmd_tags(Command):
5625
__doc__ = """List tags.
5627
This command shows a table of tag names and the revisions they reference.
5632
custom_help('directory',
5633
help='Branch whose tags should be displayed.'),
5634
RegistryOption('sort',
5635
'Sort tags by different criteria.', title='Sorting',
5636
lazy_registry=('bzrlib.tag', 'tag_sort_methods')
5643
def run(self, directory='.', sort=None, show_ids=False, revision=None):
5644
from bzrlib.tag import tag_sort_methods
5645
branch, relpath = Branch.open_containing(directory)
5647
tags = branch.tags.get_tag_dict().items()
5651
self.add_cleanup(branch.lock_read().unlock)
5653
graph = branch.repository.get_graph()
5654
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5655
revid1, revid2 = rev1.rev_id, rev2.rev_id
5656
# only show revisions between revid1 and revid2 (inclusive)
5657
tags = [(tag, revid) for tag, revid in tags if
5658
graph.is_between(revid, revid1, revid2)]
5660
sort = tag_sort_methods.get()
5663
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5664
for index, (tag, revid) in enumerate(tags):
5666
revno = branch.revision_id_to_dotted_revno(revid)
5667
if isinstance(revno, tuple):
5668
revno = '.'.join(map(str, revno))
5669
except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
5670
# Bad tag data/merges can lead to tagged revisions
5671
# which are not in this branch. Fail gracefully ...
5673
tags[index] = (tag, revno)
5675
for tag, revspec in tags:
5676
self.outf.write('%-20s %s\n' % (tag, revspec))
5679
class cmd_reconfigure(Command):
5680
__doc__ = """Reconfigure the type of a bzr directory.
5682
A target configuration must be specified.
5684
For checkouts, the bind-to location will be auto-detected if not specified.
5685
The order of preference is
5686
1. For a lightweight checkout, the current bound location.
5687
2. For branches that used to be checkouts, the previously-bound location.
5688
3. The push location.
5689
4. The parent location.
5690
If none of these is available, --bind-to must be specified.
5693
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5694
takes_args = ['location?']
5696
RegistryOption.from_kwargs(
5698
title='Target type',
5699
help='The type to reconfigure the directory to.',
5700
value_switches=True, enum_switch=False,
5701
branch='Reconfigure to be an unbound branch with no working tree.',
5702
tree='Reconfigure to be an unbound branch with a working tree.',
5703
checkout='Reconfigure to be a bound branch with a working tree.',
5704
lightweight_checkout='Reconfigure to be a lightweight'
5705
' checkout (with no local history).',
5706
standalone='Reconfigure to be a standalone branch '
5707
'(i.e. stop using shared repository).',
5708
use_shared='Reconfigure to use a shared repository.',
5709
with_trees='Reconfigure repository to create '
5710
'working trees on branches by default.',
5711
with_no_trees='Reconfigure repository to not create '
5712
'working trees on branches by default.'
5714
Option('bind-to', help='Branch to bind checkout to.', type=str),
5716
help='Perform reconfiguration even if local changes'
5718
Option('stacked-on',
5719
help='Reconfigure a branch to be stacked on another branch.',
5723
help='Reconfigure a branch to be unstacked. This '
5724
'may require copying substantial data into it.',
5728
def run(self, location=None, target_type=None, bind_to=None, force=False,
5731
directory = bzrdir.BzrDir.open(location)
5732
if stacked_on and unstacked:
5733
raise errors.BzrCommandError("Can't use both --stacked-on and --unstacked")
5734
elif stacked_on is not None:
5735
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5737
reconfigure.ReconfigureUnstacked().apply(directory)
5738
# At the moment you can use --stacked-on and a different
5739
# reconfiguration shape at the same time; there seems no good reason
5741
if target_type is None:
5742
if stacked_on or unstacked:
5745
raise errors.BzrCommandError('No target configuration '
5747
elif target_type == 'branch':
5748
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5749
elif target_type == 'tree':
5750
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5751
elif target_type == 'checkout':
5752
reconfiguration = reconfigure.Reconfigure.to_checkout(
5754
elif target_type == 'lightweight-checkout':
5755
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5757
elif target_type == 'use-shared':
5758
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5759
elif target_type == 'standalone':
5760
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5761
elif target_type == 'with-trees':
5762
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5764
elif target_type == 'with-no-trees':
5765
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5767
reconfiguration.apply(force)
5770
class cmd_switch(Command):
5771
__doc__ = """Set the branch of a checkout and update.
5773
For lightweight checkouts, this changes the branch being referenced.
5774
For heavyweight checkouts, this checks that there are no local commits
5775
versus the current bound branch, then it makes the local branch a mirror
5776
of the new location and binds to it.
5778
In both cases, the working tree is updated and uncommitted changes
5779
are merged. The user can commit or revert these as they desire.
5781
Pending merges need to be committed or reverted before using switch.
5783
The path to the branch to switch to can be specified relative to the parent
5784
directory of the current branch. For example, if you are currently in a
5785
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5788
Bound branches use the nickname of its master branch unless it is set
5789
locally, in which case switching will update the local nickname to be
5793
takes_args = ['to_location?']
5794
takes_options = ['directory',
5796
help='Switch even if local commits will be lost.'),
5798
Option('create-branch', short_name='b',
5799
help='Create the target branch from this one before'
5800
' switching to it.'),
5803
def run(self, to_location=None, force=False, create_branch=False,
5804
revision=None, directory=u'.'):
5805
from bzrlib import switch
5806
tree_location = directory
5807
revision = _get_one_revision('switch', revision)
5808
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5809
if to_location is None:
5810
if revision is None:
5811
raise errors.BzrCommandError('You must supply either a'
5812
' revision or a location')
5813
to_location = tree_location
5815
branch = control_dir.open_branch()
5816
had_explicit_nick = branch.get_config().has_explicit_nickname()
5817
except errors.NotBranchError:
5819
had_explicit_nick = False
5822
raise errors.BzrCommandError('cannot create branch without'
5824
to_location = directory_service.directories.dereference(
5826
if '/' not in to_location and '\\' not in to_location:
5827
# This path is meant to be relative to the existing branch
5828
this_url = self._get_branch_location(control_dir)
5829
to_location = urlutils.join(this_url, '..', to_location)
5830
to_branch = branch.bzrdir.sprout(to_location,
5831
possible_transports=[branch.bzrdir.root_transport],
5832
source_branch=branch).open_branch()
5835
to_branch = Branch.open(to_location)
5836
except errors.NotBranchError:
5837
this_url = self._get_branch_location(control_dir)
5838
to_branch = Branch.open(
5839
urlutils.join(this_url, '..', to_location))
5840
if revision is not None:
5841
revision = revision.as_revision_id(to_branch)
5842
switch.switch(control_dir, to_branch, force, revision_id=revision)
5843
if had_explicit_nick:
5844
branch = control_dir.open_branch() #get the new branch!
5845
branch.nick = to_branch.nick
5846
note('Switched to branch: %s',
5847
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5849
def _get_branch_location(self, control_dir):
5850
"""Return location of branch for this control dir."""
5852
this_branch = control_dir.open_branch()
5853
# This may be a heavy checkout, where we want the master branch
5854
master_location = this_branch.get_bound_location()
5855
if master_location is not None:
5856
return master_location
5857
# If not, use a local sibling
5858
return this_branch.base
5859
except errors.NotBranchError:
5860
format = control_dir.find_branch_format()
5861
if getattr(format, 'get_reference', None) is not None:
5862
return format.get_reference(control_dir)
5864
return control_dir.root_transport.base
5867
class cmd_view(Command):
5868
__doc__ = """Manage filtered views.
5870
Views provide a mask over the tree so that users can focus on
5871
a subset of a tree when doing their work. After creating a view,
5872
commands that support a list of files - status, diff, commit, etc -
5873
effectively have that list of files implicitly given each time.
5874
An explicit list of files can still be given but those files
5875
must be within the current view.
5877
In most cases, a view has a short life-span: it is created to make
5878
a selected change and is deleted once that change is committed.
5879
At other times, you may wish to create one or more named views
5880
and switch between them.
5882
To disable the current view without deleting it, you can switch to
5883
the pseudo view called ``off``. This can be useful when you need
5884
to see the whole tree for an operation or two (e.g. merge) but
5885
want to switch back to your view after that.
5888
To define the current view::
5890
bzr view file1 dir1 ...
5892
To list the current view::
5896
To delete the current view::
5900
To disable the current view without deleting it::
5902
bzr view --switch off
5904
To define a named view and switch to it::
5906
bzr view --name view-name file1 dir1 ...
5908
To list a named view::
5910
bzr view --name view-name
5912
To delete a named view::
5914
bzr view --name view-name --delete
5916
To switch to a named view::
5918
bzr view --switch view-name
5920
To list all views defined::
5924
To delete all views::
5926
bzr view --delete --all
5930
takes_args = ['file*']
5933
help='Apply list or delete action to all views.',
5936
help='Delete the view.',
5939
help='Name of the view to define, list or delete.',
5943
help='Name of the view to switch to.',
5948
def run(self, file_list,
5954
tree, file_list = WorkingTree.open_containing_paths(file_list,
5956
current_view, view_dict = tree.views.get_view_info()
5961
raise errors.BzrCommandError(
5962
"Both --delete and a file list specified")
5964
raise errors.BzrCommandError(
5965
"Both --delete and --switch specified")
5967
tree.views.set_view_info(None, {})
5968
self.outf.write("Deleted all views.\n")
5970
raise errors.BzrCommandError("No current view to delete")
5972
tree.views.delete_view(name)
5973
self.outf.write("Deleted '%s' view.\n" % name)
5976
raise errors.BzrCommandError(
5977
"Both --switch and a file list specified")
5979
raise errors.BzrCommandError(
5980
"Both --switch and --all specified")
5981
elif switch == 'off':
5982
if current_view is None:
5983
raise errors.BzrCommandError("No current view to disable")
5984
tree.views.set_view_info(None, view_dict)
5985
self.outf.write("Disabled '%s' view.\n" % (current_view))
5987
tree.views.set_view_info(switch, view_dict)
5988
view_str = views.view_display_str(tree.views.lookup_view())
5989
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5992
self.outf.write('Views defined:\n')
5993
for view in sorted(view_dict):
5994
if view == current_view:
5998
view_str = views.view_display_str(view_dict[view])
5999
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
6001
self.outf.write('No views defined.\n')
6004
# No name given and no current view set
6007
raise errors.BzrCommandError(
6008
"Cannot change the 'off' pseudo view")
6009
tree.views.set_view(name, sorted(file_list))
6010
view_str = views.view_display_str(tree.views.lookup_view())
6011
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
6015
# No name given and no current view set
6016
self.outf.write('No current view.\n')
6018
view_str = views.view_display_str(tree.views.lookup_view(name))
6019
self.outf.write("'%s' view is: %s\n" % (name, view_str))
6022
class cmd_hooks(Command):
6023
__doc__ = """Show hooks."""
6028
for hook_key in sorted(hooks.known_hooks.keys()):
6029
some_hooks = hooks.known_hooks_key_to_object(hook_key)
6030
self.outf.write("%s:\n" % type(some_hooks).__name__)
6031
for hook_name, hook_point in sorted(some_hooks.items()):
6032
self.outf.write(" %s:\n" % (hook_name,))
6033
found_hooks = list(hook_point)
6035
for hook in found_hooks:
6036
self.outf.write(" %s\n" %
6037
(some_hooks.get_hook_name(hook),))
6039
self.outf.write(" <no hooks installed>\n")
6042
class cmd_remove_branch(Command):
6043
__doc__ = """Remove a branch.
6045
This will remove the branch from the specified location but
6046
will keep any working tree or repository in place.
6050
Remove the branch at repo/trunk::
6052
bzr remove-branch repo/trunk
6056
takes_args = ["location?"]
6058
aliases = ["rmbranch"]
6060
def run(self, location=None):
6061
if location is None:
6063
branch = Branch.open_containing(location)[0]
6064
branch.bzrdir.destroy_branch()
6067
class cmd_shelve(Command):
6068
__doc__ = """Temporarily set aside some changes from the current tree.
6070
Shelve allows you to temporarily put changes you've made "on the shelf",
6071
ie. out of the way, until a later time when you can bring them back from
6072
the shelf with the 'unshelve' command. The changes are stored alongside
6073
your working tree, and so they aren't propagated along with your branch nor
6074
will they survive its deletion.
6076
If shelve --list is specified, previously-shelved changes are listed.
6078
Shelve is intended to help separate several sets of changes that have
6079
been inappropriately mingled. If you just want to get rid of all changes
6080
and you don't need to restore them later, use revert. If you want to
6081
shelve all text changes at once, use shelve --all.
6083
If filenames are specified, only the changes to those files will be
6084
shelved. Other files will be left untouched.
6086
If a revision is specified, changes since that revision will be shelved.
6088
You can put multiple items on the shelf, and by default, 'unshelve' will
6089
restore the most recently shelved changes.
6091
For complicated changes, it is possible to edit the changes in a separate
6092
editor program to decide what the file remaining in the working copy
6093
should look like. To do this, add the configuration option
6095
change_editor = PROGRAM @new_path @old_path
6097
where @new_path is replaced with the path of the new version of the
6098
file and @old_path is replaced with the path of the old version of
6099
the file. The PROGRAM should save the new file with the desired
6100
contents of the file in the working tree.
6104
takes_args = ['file*']
6109
Option('all', help='Shelve all changes.'),
6111
RegistryOption('writer', 'Method to use for writing diffs.',
6112
bzrlib.option.diff_writer_registry,
6113
value_switches=True, enum_switch=False),
6115
Option('list', help='List shelved changes.'),
6117
help='Destroy removed changes instead of shelving them.'),
6119
_see_also = ['unshelve', 'configuration']
6121
def run(self, revision=None, all=False, file_list=None, message=None,
6122
writer=None, list=False, destroy=False, directory=None):
6124
return self.run_for_list(directory=directory)
6125
from bzrlib.shelf_ui import Shelver
6127
writer = bzrlib.option.diff_writer_registry.get()
6129
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
6130
file_list, message, destroy=destroy, directory=directory)
6135
except errors.UserAbort:
6138
def run_for_list(self, directory=None):
6139
if directory is None:
6141
tree = WorkingTree.open_containing(directory)[0]
6142
self.add_cleanup(tree.lock_read().unlock)
6143
manager = tree.get_shelf_manager()
6144
shelves = manager.active_shelves()
6145
if len(shelves) == 0:
6146
note('No shelved changes.')
6148
for shelf_id in reversed(shelves):
6149
message = manager.get_metadata(shelf_id).get('message')
6151
message = '<no message>'
6152
self.outf.write('%3d: %s\n' % (shelf_id, message))
6156
class cmd_unshelve(Command):
6157
__doc__ = """Restore shelved changes.
6159
By default, the most recently shelved changes are restored. However if you
6160
specify a shelf by id those changes will be restored instead. This works
6161
best when the changes don't depend on each other.
6164
takes_args = ['shelf_id?']
6167
RegistryOption.from_kwargs(
6168
'action', help="The action to perform.",
6169
enum_switch=False, value_switches=True,
6170
apply="Apply changes and remove from the shelf.",
6171
dry_run="Show changes, but do not apply or remove them.",
6172
preview="Instead of unshelving the changes, show the diff that "
6173
"would result from unshelving.",
6174
delete_only="Delete changes without applying them.",
6175
keep="Apply changes but don't delete them.",
6178
_see_also = ['shelve']
6180
def run(self, shelf_id=None, action='apply', directory=u'.'):
6181
from bzrlib.shelf_ui import Unshelver
6182
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
6186
unshelver.tree.unlock()
6189
class cmd_clean_tree(Command):
6190
__doc__ = """Remove unwanted files from working tree.
6192
By default, only unknown files, not ignored files, are deleted. Versioned
6193
files are never deleted.
6195
Another class is 'detritus', which includes files emitted by bzr during
6196
normal operations and selftests. (The value of these files decreases with
6199
If no options are specified, unknown files are deleted. Otherwise, option
6200
flags are respected, and may be combined.
6202
To check what clean-tree will do, use --dry-run.
6204
takes_options = ['directory',
6205
Option('ignored', help='Delete all ignored files.'),
6206
Option('detritus', help='Delete conflict files, merge and revert'
6207
' backups, and failed selftest dirs.'),
6209
help='Delete files unknown to bzr (default).'),
6210
Option('dry-run', help='Show files to delete instead of'
6212
Option('force', help='Do not prompt before deleting.')]
6213
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6214
force=False, directory=u'.'):
6215
from bzrlib.clean_tree import clean_tree
6216
if not (unknown or ignored or detritus):
6220
clean_tree(directory, unknown=unknown, ignored=ignored,
6221
detritus=detritus, dry_run=dry_run, no_prompt=force)
6224
class cmd_reference(Command):
6225
__doc__ = """list, view and set branch locations for nested trees.
6227
If no arguments are provided, lists the branch locations for nested trees.
6228
If one argument is provided, display the branch location for that tree.
6229
If two arguments are provided, set the branch location for that tree.
6234
takes_args = ['path?', 'location?']
6236
def run(self, path=None, location=None):
6238
if path is not None:
6240
tree, branch, relpath =(
6241
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6242
if path is not None:
6245
tree = branch.basis_tree()
6247
info = branch._get_all_reference_info().iteritems()
6248
self._display_reference_info(tree, branch, info)
6250
file_id = tree.path2id(path)
6252
raise errors.NotVersionedError(path)
6253
if location is None:
6254
info = [(file_id, branch.get_reference_info(file_id))]
6255
self._display_reference_info(tree, branch, info)
6257
branch.set_reference_info(file_id, path, location)
6259
def _display_reference_info(self, tree, branch, info):
6261
for file_id, (path, location) in info:
6263
path = tree.id2path(file_id)
6264
except errors.NoSuchId:
6266
ref_list.append((path, location))
6267
for path, location in sorted(ref_list):
6268
self.outf.write('%s %s\n' % (path, location))
6271
class cmd_export_pot(Command):
6272
__doc__ = """Export command helps and error messages in po format."""
6277
from bzrlib.export_pot import export_pot
6278
export_pot(self.outf)
6281
def _register_lazy_builtins():
6282
# register lazy builtins from other modules; called at startup and should
6283
# be only called once.
6284
for (name, aliases, module_name) in [
6285
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6286
('cmd_config', [], 'bzrlib.config'),
6287
('cmd_dpush', [], 'bzrlib.foreign'),
6288
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6289
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6290
('cmd_conflicts', [], 'bzrlib.conflicts'),
6291
('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
6292
('cmd_verify_signatures', [],
6293
'bzrlib.commit_signature_commands'),
6294
('cmd_test_script', [], 'bzrlib.cmd_test_script'),
6296
builtin_command_registry.register_lazy(name, aliases, module_name)