274
144
Not versioned and not matching an ignore pattern.
276
Additionally for directories, symlinks and files with an executable
277
bit, Bazaar indicates their type using a trailing character: '/', '@'
280
146
To see ignored files use 'bzr ignored'. For details on the
281
147
changes to file texts, use 'bzr diff'.
283
149
Note that --short or -S gives status flags for each item, similar
284
150
to Subversion's status command. To get output similar to svn -q,
287
153
If no arguments are specified, the status of the entire working
288
154
directory is shown. Otherwise, only the status of the specified
289
155
files or directories is reported. If a directory is given, status
290
156
is reported for everything inside that directory.
292
Before merges are committed, the pending merge tip revisions are
293
shown. To see all pending merge revisions, use the -v option.
294
To skip the display of pending merge information altogether, use
295
the no-pending option or specify a file/directory.
297
158
If a revision argument is given, the status is calculated against
298
159
that revision, or between two revisions if two are provided.
301
162
# TODO: --no-recurse, --recurse options
303
164
takes_args = ['file*']
304
takes_options = ['show-ids', 'revision', 'change', 'verbose',
165
takes_options = ['show-ids', 'revision', 'change',
305
166
Option('short', help='Use short status indicators.',
307
168
Option('versioned', help='Only show versioned files.',
309
Option('no-pending', help='Don\'t show pending merges.',
312
171
aliases = ['st', 'stat']
314
173
encoding_type = 'replace'
315
174
_see_also = ['diff', 'revert', 'status-flags']
318
177
def run(self, show_ids=False, file_list=None, revision=None, short=False,
319
versioned=False, no_pending=False, verbose=False):
320
179
from bzrlib.status import show_tree_status
322
181
if revision and len(revision) > 2:
323
182
raise errors.BzrCommandError('bzr status --revision takes exactly'
324
183
' one or two revision specifiers')
326
tree, relfile_list = tree_files(file_list)
327
# Avoid asking for specific files when that is not needed.
328
if relfile_list == ['']:
330
# Don't disable pending merges for full trees other than '.'.
331
if file_list == ['.']:
333
# A specific path within a tree was given.
334
elif relfile_list is not None:
185
tree, file_list = tree_files(file_list)
336
187
show_tree_status(tree, show_ids=show_ids,
337
specific_files=relfile_list, revision=revision,
338
to_file=self.outf, short=short, versioned=versioned,
339
show_pending=(not no_pending), verbose=verbose)
188
specific_files=file_list, revision=revision,
189
to_file=self.outf, short=short, versioned=versioned)
342
192
class cmd_cat_revision(Command):
343
__doc__ = """Write out metadata for a revision.
193
"""Write out metadata for a revision.
345
195
The revision to print can either be specified by a specific
346
196
revision identifier, or you can use --revision.
350
200
takes_args = ['revision_id?']
351
takes_options = ['directory', 'revision']
201
takes_options = ['revision']
352
202
# cat-revision is more for frontends so should be exact
353
203
encoding = 'strict'
355
def print_revision(self, revisions, revid):
356
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
357
record = stream.next()
358
if record.storage_kind == 'absent':
359
raise errors.NoSuchRevision(revisions, revid)
360
revtext = record.get_bytes_as('fulltext')
361
self.outf.write(revtext.decode('utf-8'))
364
def run(self, revision_id=None, revision=None, directory=u'.'):
206
def run(self, revision_id=None, revision=None):
365
207
if revision_id is not None and revision is not None:
366
208
raise errors.BzrCommandError('You can only supply one of'
367
209
' revision_id or --revision')
368
210
if revision_id is None and revision is None:
369
211
raise errors.BzrCommandError('You must supply either'
370
212
' --revision or a revision_id')
371
b = WorkingTree.open_containing(directory)[0].branch
373
revisions = b.repository.revisions
374
if revisions is None:
375
raise errors.BzrCommandError('Repository %r does not support '
376
'access to raw revision texts')
378
b.repository.lock_read()
380
# TODO: jam 20060112 should cat-revision always output utf-8?
381
if revision_id is not None:
382
revision_id = osutils.safe_revision_id(revision_id, warn=False)
384
self.print_revision(revisions, revision_id)
385
except errors.NoSuchRevision:
386
msg = "The repository %s contains no revision %s." % (
387
b.repository.base, revision_id)
388
raise errors.BzrCommandError(msg)
389
elif revision is not None:
392
raise errors.BzrCommandError(
393
'You cannot specify a NULL revision.')
394
rev_id = rev.as_revision_id(b)
395
self.print_revision(revisions, rev_id)
397
b.repository.unlock()
400
class cmd_dump_btree(Command):
401
__doc__ = """Dump the contents of a btree index file to stdout.
403
PATH is a btree index file, it can be any URL. This includes things like
404
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
406
By default, the tuples stored in the index file will be displayed. With
407
--raw, we will uncompress the pages, but otherwise display the raw bytes
411
# TODO: Do we want to dump the internal nodes as well?
412
# TODO: It would be nice to be able to dump the un-parsed information,
413
# rather than only going through iter_all_entries. However, this is
414
# good enough for a start
416
encoding_type = 'exact'
417
takes_args = ['path']
418
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
419
' rather than the parsed tuples.'),
422
def run(self, path, raw=False):
423
dirname, basename = osutils.split(path)
424
t = transport.get_transport(dirname)
426
self._dump_raw_bytes(t, basename)
428
self._dump_entries(t, basename)
430
def _get_index_and_bytes(self, trans, basename):
431
"""Create a BTreeGraphIndex and raw bytes."""
432
bt = btree_index.BTreeGraphIndex(trans, basename, None)
433
bytes = trans.get_bytes(basename)
434
bt._file = cStringIO.StringIO(bytes)
435
bt._size = len(bytes)
438
def _dump_raw_bytes(self, trans, basename):
441
# We need to parse at least the root node.
442
# This is because the first page of every row starts with an
443
# uncompressed header.
444
bt, bytes = self._get_index_and_bytes(trans, basename)
445
for page_idx, page_start in enumerate(xrange(0, len(bytes),
446
btree_index._PAGE_SIZE)):
447
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
448
page_bytes = bytes[page_start:page_end]
450
self.outf.write('Root node:\n')
451
header_end, data = bt._parse_header_from_bytes(page_bytes)
452
self.outf.write(page_bytes[:header_end])
454
self.outf.write('\nPage %d\n' % (page_idx,))
455
decomp_bytes = zlib.decompress(page_bytes)
456
self.outf.write(decomp_bytes)
457
self.outf.write('\n')
459
def _dump_entries(self, trans, basename):
461
st = trans.stat(basename)
462
except errors.TransportNotPossible:
463
# We can't stat, so we'll fake it because we have to do the 'get()'
465
bt, _ = self._get_index_and_bytes(trans, basename)
467
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
468
for node in bt.iter_all_entries():
469
# Node is made up of:
470
# (index, key, value, [references])
474
refs_as_tuples = None
476
refs_as_tuples = static_tuple.as_tuples(refs)
477
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
478
self.outf.write('%s\n' % (as_tuple,))
213
b = WorkingTree.open_containing(u'.')[0].branch
215
# TODO: jam 20060112 should cat-revision always output utf-8?
216
if revision_id is not None:
217
revision_id = osutils.safe_revision_id(revision_id, warn=False)
218
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
219
elif revision is not None:
222
raise errors.BzrCommandError('You cannot specify a NULL'
224
revno, rev_id = rev.in_history(b)
225
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
481
228
class cmd_remove_tree(Command):
482
__doc__ = """Remove the working tree from a given branch/checkout.
229
"""Remove the working tree from a given branch/checkout.
484
231
Since a lightweight checkout is little more than a working tree
485
232
this will refuse to run against one.
487
234
To re-create the working tree, use "bzr checkout".
489
236
_see_also = ['checkout', 'working-trees']
490
takes_args = ['location*']
493
help='Remove the working tree even if it has '
494
'uncommitted or shelved changes.'),
497
def run(self, location_list, force=False):
498
if not location_list:
501
for location in location_list:
502
d = bzrdir.BzrDir.open(location)
505
working = d.open_workingtree()
506
except errors.NoWorkingTree:
507
raise errors.BzrCommandError("No working tree to remove")
508
except errors.NotLocalUrl:
509
raise errors.BzrCommandError("You cannot remove the working tree"
512
if (working.has_changes()):
513
raise errors.UncommittedChanges(working)
514
if working.get_shelf_manager().last_shelf() is not None:
515
raise errors.ShelvedChanges(working)
517
if working.user_url != working.branch.user_url:
518
raise errors.BzrCommandError("You cannot remove the working tree"
519
" from a lightweight checkout")
521
d.destroy_workingtree()
238
takes_args = ['location?']
240
def run(self, location='.'):
241
d = bzrdir.BzrDir.open(location)
244
working = d.open_workingtree()
245
except errors.NoWorkingTree:
246
raise errors.BzrCommandError("No working tree to remove")
247
except errors.NotLocalUrl:
248
raise errors.BzrCommandError("You cannot remove the working tree of a "
251
working_path = working.bzrdir.root_transport.base
252
branch_path = working.branch.bzrdir.root_transport.base
253
if working_path != branch_path:
254
raise errors.BzrCommandError("You cannot remove the working tree from "
255
"a lightweight checkout")
257
d.destroy_workingtree()
524
260
class cmd_revno(Command):
525
__doc__ = """Show current revision number.
261
"""Show current revision number.
527
263
This is equal to the number of revisions on this branch.
530
266
_see_also = ['info']
531
267
takes_args = ['location?']
533
Option('tree', help='Show revno of working tree'),
537
def run(self, tree=False, location=u'.'):
540
wt = WorkingTree.open_containing(location)[0]
541
self.add_cleanup(wt.lock_read().unlock)
542
except (errors.NoWorkingTree, errors.NotLocalUrl):
543
raise errors.NoWorkingTree(location)
544
revid = wt.last_revision()
546
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
547
except errors.NoSuchRevision:
549
revno = ".".join(str(n) for n in revno_t)
551
b = Branch.open_containing(location)[0]
552
self.add_cleanup(b.lock_read().unlock)
555
self.outf.write(str(revno) + '\n')
270
def run(self, location=u'.'):
271
self.outf.write(str(Branch.open_containing(location)[0].revno()))
272
self.outf.write('\n')
558
275
class cmd_revision_info(Command):
559
__doc__ = """Show revision number and revision id for a given revision identifier.
276
"""Show revision number and revision id for a given revision identifier.
562
279
takes_args = ['revision_info*']
565
custom_help('directory',
566
help='Branch to examine, '
567
'rather than the one containing the working directory.'),
568
Option('tree', help='Show revno of working tree'),
280
takes_options = ['revision']
572
def run(self, revision=None, directory=u'.', tree=False,
573
revision_info_list=[]):
283
def run(self, revision=None, revision_info_list=[]):
576
wt = WorkingTree.open_containing(directory)[0]
578
self.add_cleanup(wt.lock_read().unlock)
579
except (errors.NoWorkingTree, errors.NotLocalUrl):
581
b = Branch.open_containing(directory)[0]
582
self.add_cleanup(b.lock_read().unlock)
584
286
if revision is not None:
585
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
287
revs.extend(revision)
586
288
if revision_info_list is not None:
587
for rev_str in revision_info_list:
588
rev_spec = RevisionSpec.from_string(rev_str)
589
revision_ids.append(rev_spec.as_revision_id(b))
590
# No arguments supplied, default to the last revision
591
if len(revision_ids) == 0:
594
raise errors.NoWorkingTree(directory)
595
revision_ids.append(wt.last_revision())
289
for rev in revision_info_list:
290
revs.append(RevisionSpec.from_string(rev))
292
b = Branch.open_containing(u'.')[0]
295
revs.append(RevisionSpec.from_string('-1'))
298
revinfo = rev.in_history(b)
299
if revinfo.revno is None:
300
dotted_map = b.get_revision_id_to_revno_map()
301
revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
302
print '%s %s' % (revno, revinfo.rev_id)
597
revision_ids.append(b.last_revision())
601
for revision_id in revision_ids:
603
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
604
revno = '.'.join(str(i) for i in dotted_revno)
605
except errors.NoSuchRevision:
607
maxlen = max(maxlen, len(revno))
608
revinfos.append([revno, revision_id])
612
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
304
print '%4d %s' % (revinfo.revno, revinfo.rev_id)
615
307
class cmd_add(Command):
616
__doc__ = """Add specified files or directories.
308
"""Add specified files or directories.
618
310
In non-recursive mode, all the named items are added, regardless
619
311
of whether they were previously ignored. A warning is given if
817
523
takes_args = ['names*']
818
524
takes_options = [Option("after", help="Move only the bzr identifier"
819
525
" of the file, because the file has already been moved."),
820
Option('auto', help='Automatically guess renames.'),
821
Option('dry-run', help='Avoid making changes when guessing renames.'),
823
527
aliases = ['move', 'rename']
824
528
encoding_type = 'replace'
826
def run(self, names_list, after=False, auto=False, dry_run=False):
828
return self.run_auto(names_list, after, dry_run)
830
raise errors.BzrCommandError('--dry-run requires --auto.')
530
def run(self, names_list, after=False):
831
531
if names_list is None:
833
534
if len(names_list) < 2:
834
535
raise errors.BzrCommandError("missing file argument")
835
tree, rel_names = tree_files(names_list, canonicalize=False)
836
self.add_cleanup(tree.lock_tree_write().unlock)
837
self._run(tree, names_list, rel_names, after)
839
def run_auto(self, names_list, after, dry_run):
840
if names_list is not None and len(names_list) > 1:
841
raise errors.BzrCommandError('Only one path may be specified to'
844
raise errors.BzrCommandError('--after cannot be specified with'
846
work_tree, file_list = tree_files(names_list, default_branch='.')
847
self.add_cleanup(work_tree.lock_tree_write().unlock)
848
rename_map.RenameMap.guess_renames(work_tree, dry_run)
850
def _run(self, tree, names_list, rel_names, after):
851
into_existing = osutils.isdir(names_list[-1])
852
if into_existing and len(names_list) == 2:
854
# a. case-insensitive filesystem and change case of dir
855
# b. move directory after the fact (if the source used to be
856
# a directory, but now doesn't exist in the working tree
857
# and the target is an existing directory, just rename it)
858
if (not tree.case_sensitive
859
and rel_names[0].lower() == rel_names[1].lower()):
860
into_existing = False
863
# 'fix' the case of a potential 'from'
864
from_id = tree.path2id(
865
tree.get_canonical_inventory_path(rel_names[0]))
866
if (not osutils.lexists(names_list[0]) and
867
from_id and inv.get_file_kind(from_id) == "directory"):
868
into_existing = False
536
tree, rel_names = tree_files(names_list)
538
if os.path.isdir(names_list[-1]):
871
539
# move into existing directory
872
# All entries reference existing inventory items, so fix them up
873
# for cicp file-systems.
874
rel_names = tree.get_canonical_inventory_paths(rel_names)
875
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
877
self.outf.write("%s => %s\n" % (src, dest))
540
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
541
self.outf.write("%s => %s\n" % pair)
879
543
if len(names_list) != 2:
880
544
raise errors.BzrCommandError('to mv multiple files the'
881
545
' destination must be a versioned'
884
# for cicp file-systems: the src references an existing inventory
886
src = tree.get_canonical_inventory_path(rel_names[0])
887
# Find the canonical version of the destination: In all cases, the
888
# parent of the target must be in the inventory, so we fetch the
889
# canonical version from there (we do not always *use* the
890
# canonicalized tail portion - we may be attempting to rename the
892
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
893
dest_parent = osutils.dirname(canon_dest)
894
spec_tail = osutils.basename(rel_names[1])
895
# For a CICP file-system, we need to avoid creating 2 inventory
896
# entries that differ only by case. So regardless of the case
897
# we *want* to use (ie, specified by the user or the file-system),
898
# we must always choose to use the case of any existing inventory
899
# items. The only exception to this is when we are attempting a
900
# case-only rename (ie, canonical versions of src and dest are
902
dest_id = tree.path2id(canon_dest)
903
if dest_id is None or tree.path2id(src) == dest_id:
904
# No existing item we care about, so work out what case we
905
# are actually going to use.
907
# If 'after' is specified, the tail must refer to a file on disk.
909
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
911
# pathjoin with an empty tail adds a slash, which breaks
913
dest_parent_fq = tree.basedir
915
dest_tail = osutils.canonical_relpath(
917
osutils.pathjoin(dest_parent_fq, spec_tail))
919
# not 'after', so case as specified is used
920
dest_tail = spec_tail
922
# Use the existing item so 'mv' fails with AlreadyVersioned.
923
dest_tail = os.path.basename(canon_dest)
924
dest = osutils.pathjoin(dest_parent, dest_tail)
925
mutter("attempting to move %s => %s", src, dest)
926
tree.rename_one(src, dest, after=after)
928
self.outf.write("%s => %s\n" % (src, dest))
547
tree.rename_one(rel_names[0], rel_names[1], after=after)
548
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
931
551
class cmd_pull(Command):
932
__doc__ = """Turn this branch into a mirror of another branch.
552
"""Turn this branch into a mirror of another branch.
934
By default, this command only works on branches that have not diverged.
935
Branches are considered diverged if the destination branch's most recent
936
commit is one that has not been merged (directly or indirectly) into the
554
This command only works on branches that have not diverged. Branches are
555
considered diverged if the destination branch's most recent commit is one
556
that has not been merged (directly or indirectly) into the parent.
939
558
If branches have diverged, you can use 'bzr merge' to integrate the changes
940
559
from one into the other. Once one branch has merged, the other should
941
560
be able to pull it again.
943
If you want to replace your local changes and just want your branch to
944
match the remote one, use pull --overwrite. This will work even if the two
945
branches have diverged.
562
If you want to forget your local changes and just update your branch to
563
match the remote one, use pull --overwrite.
947
565
If there is no default location set, the first pull will set it. After
948
566
that, you can omit the location to use the default. To change the
949
567
default, use --remember. The value will only be saved if the remote
950
568
location can be accessed.
952
Note: The location can be specified either in the form of a branch,
953
or in the form of a path to a file containing a merge directive generated
957
_see_also = ['push', 'update', 'status-flags', 'send']
571
_see_also = ['push', 'update', 'status-flags']
958
572
takes_options = ['remember', 'overwrite', 'revision',
959
573
custom_help('verbose',
960
574
help='Show logs of pulled revisions.'),
961
custom_help('directory',
962
576
help='Branch to pull into, '
963
'rather than the one containing the working directory.'),
965
help="Perform a local pull in a bound "
966
"branch. Local pulls are not applied to "
577
'rather than the one containing the working directory.',
970
582
takes_args = ['location?']
1078
683
_see_also = ['pull', 'update', 'working-trees']
1079
takes_options = ['remember', 'overwrite', 'verbose', 'revision',
684
takes_options = ['remember', 'overwrite', 'verbose',
1080
685
Option('create-prefix',
1081
686
help='Create the path leading up to the branch '
1082
687
'if it does not already exist.'),
1083
custom_help('directory',
1084
689
help='Branch to push from, '
1085
'rather than the one containing the working directory.'),
690
'rather than the one containing the working directory.',
1086
694
Option('use-existing-dir',
1087
695
help='By default push will fail if the target'
1088
696
' directory exists, but does not already'
1089
697
' have a control directory. This flag will'
1090
698
' allow push to proceed.'),
1092
help='Create a stacked branch that references the public location '
1093
'of the parent branch.'),
1094
Option('stacked-on',
1095
help='Create a stacked branch that refers to another branch '
1096
'for the commit history. Only the work not present in the '
1097
'referenced branch is included in the branch created.',
1100
help='Refuse to push if there are uncommitted changes in'
1101
' the working tree, --no-strict disables the check.'),
1103
700
takes_args = ['location?']
1104
701
encoding_type = 'replace'
1106
703
def run(self, location=None, remember=False, overwrite=False,
1107
create_prefix=False, verbose=False, revision=None,
1108
use_existing_dir=False, directory=None, stacked_on=None,
1109
stacked=False, strict=None):
1110
from bzrlib.push import _show_push_branch
704
create_prefix=False, verbose=False,
705
use_existing_dir=False,
707
# FIXME: Way too big! Put this into a function called from the
1112
709
if directory is None:
1114
# Get the source branch
1116
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1117
# Get the tip's revision_id
1118
revision = _get_one_revision('push', revision)
1119
if revision is not None:
1120
revision_id = revision.in_history(br_from).rev_id
1123
if tree is not None and revision_id is None:
1124
tree.check_changed_or_out_of_date(
1125
strict, 'push_strict',
1126
more_error='Use --no-strict to force the push.',
1127
more_warning='Uncommitted changes will not be pushed.')
1128
# Get the stacked_on branch, if any
1129
if stacked_on is not None:
1130
stacked_on = urlutils.normalize_url(stacked_on)
1132
parent_url = br_from.get_parent()
1134
parent = Branch.open(parent_url)
1135
stacked_on = parent.get_public_branch()
1137
# I considered excluding non-http url's here, thus forcing
1138
# 'public' branches only, but that only works for some
1139
# users, so it's best to just depend on the user spotting an
1140
# error by the feedback given to them. RBC 20080227.
1141
stacked_on = parent_url
1143
raise errors.BzrCommandError(
1144
"Could not determine branch to refer to.")
1146
# Get the destination location
711
br_from = Branch.open_containing(directory)[0]
712
stored_loc = br_from.get_push_location()
1147
713
if location is None:
1148
stored_loc = br_from.get_push_location()
1149
714
if stored_loc is None:
1150
raise errors.BzrCommandError(
1151
"No push location known or specified.")
715
raise errors.BzrCommandError("No push location known or specified.")
1153
717
display_url = urlutils.unescape_for_display(stored_loc,
1154
718
self.outf.encoding)
1155
self.outf.write("Using saved push location: %s\n" % display_url)
719
self.outf.write("Using saved location: %s\n" % display_url)
1156
720
location = stored_loc
1158
_show_push_branch(br_from, revision_id, location, self.outf,
1159
verbose=verbose, overwrite=overwrite, remember=remember,
1160
stacked_on=stacked_on, create_prefix=create_prefix,
1161
use_existing_dir=use_existing_dir)
722
to_transport = transport.get_transport(location)
724
br_to = repository_to = dir_to = None
726
dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
727
except errors.NotBranchError:
728
pass # Didn't find anything
730
# If we can open a branch, use its direct repository, otherwise see
731
# if there is a repository without a branch.
733
br_to = dir_to.open_branch()
734
except errors.NotBranchError:
735
# Didn't find a branch, can we find a repository?
737
repository_to = dir_to.find_repository()
738
except errors.NoRepositoryPresent:
741
# Found a branch, so we must have found a repository
742
repository_to = br_to.repository
747
# The destination doesn't exist; create it.
748
# XXX: Refactor the create_prefix/no_create_prefix code into a
749
# common helper function
751
to_transport.mkdir('.')
752
except errors.FileExists:
753
if not use_existing_dir:
754
raise errors.BzrCommandError("Target directory %s"
755
" already exists, but does not have a valid .bzr"
756
" directory. Supply --use-existing-dir to push"
757
" there anyway." % location)
758
except errors.NoSuchFile:
759
if not create_prefix:
760
raise errors.BzrCommandError("Parent directory of %s"
762
"\nYou may supply --create-prefix to create all"
763
" leading parent directories."
765
_create_prefix(to_transport)
767
# Now the target directory exists, but doesn't have a .bzr
768
# directory. So we need to create it, along with any work to create
769
# all of the dependent branches, etc.
770
dir_to = br_from.bzrdir.clone_on_transport(to_transport,
771
revision_id=br_from.last_revision())
772
br_to = dir_to.open_branch()
773
# TODO: Some more useful message about what was copied
774
note('Created new branch.')
775
# We successfully created the target, remember it
776
if br_from.get_push_location() is None or remember:
777
br_from.set_push_location(br_to.base)
778
elif repository_to is None:
779
# we have a bzrdir but no branch or repository
780
# XXX: Figure out what to do other than complain.
781
raise errors.BzrCommandError("At %s you have a valid .bzr control"
782
" directory, but not a branch or repository. This is an"
783
" unsupported configuration. Please move the target directory"
784
" out of the way and try again."
787
# We have a repository but no branch, copy the revisions, and then
789
last_revision_id = br_from.last_revision()
790
repository_to.fetch(br_from.repository,
791
revision_id=last_revision_id)
792
br_to = br_from.clone(dir_to, revision_id=last_revision_id)
793
note('Created new branch.')
794
if br_from.get_push_location() is None or remember:
795
br_from.set_push_location(br_to.base)
796
else: # We have a valid to branch
797
# We were able to connect to the remote location, so remember it
798
# we don't need to successfully push because of possible divergence.
799
if br_from.get_push_location() is None or remember:
800
br_from.set_push_location(br_to.base)
802
old_rh = br_to.revision_history()
805
tree_to = dir_to.open_workingtree()
806
except errors.NotLocalUrl:
807
warning("This transport does not update the working "
808
"tree of: %s. See 'bzr help working-trees' for "
809
"more information." % br_to.base)
810
push_result = br_from.push(br_to, overwrite)
811
except errors.NoWorkingTree:
812
push_result = br_from.push(br_to, overwrite)
816
push_result = br_from.push(tree_to.branch, overwrite)
820
except errors.DivergedBranches:
821
raise errors.BzrCommandError('These branches have diverged.'
822
' Try using "merge" and then "push".')
823
if push_result is not None:
824
push_result.report(self.outf)
826
new_rh = br_to.revision_history()
829
from bzrlib.log import show_changed_revisions
830
show_changed_revisions(br_to, old_rh, new_rh,
833
# we probably did a clone rather than a push, so a message was
1164
838
class cmd_branch(Command):
1165
__doc__ = """Create a new branch that is a copy of an existing branch.
839
"""Create a new copy of a branch.
1167
841
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1168
842
be used. In other words, "branch ../foo/bar" will attempt to create ./bar.
1178
852
_see_also = ['checkout']
1179
853
takes_args = ['from_location', 'to_location?']
1180
takes_options = ['revision', Option('hardlink',
1181
help='Hard-link working tree files where possible.'),
1183
help="Create a branch without a working-tree."),
1185
help="Switch the checkout in the current directory "
1186
"to the new branch."),
1188
help='Create a stacked branch referring to the source branch. '
1189
'The new branch will depend on the availability of the source '
1190
'branch for all operations.'),
1191
Option('standalone',
1192
help='Do not use a shared repository, even if available.'),
1193
Option('use-existing-dir',
1194
help='By default branch will fail if the target'
1195
' directory exists, but does not already'
1196
' have a control directory. This flag will'
1197
' allow branch to proceed.'),
1199
help="Bind new branch to from location."),
854
takes_options = ['revision']
1201
855
aliases = ['get', 'clone']
1203
def run(self, from_location, to_location=None, revision=None,
1204
hardlink=False, stacked=False, standalone=False, no_tree=False,
1205
use_existing_dir=False, switch=False, bind=False):
1206
from bzrlib import switch as _mod_switch
857
def run(self, from_location, to_location=None, revision=None):
1207
858
from bzrlib.tag import _merge_tags_if_possible
1208
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1210
revision = _get_one_revision('branch', revision)
1211
self.add_cleanup(br_from.lock_read().unlock)
1212
if revision is not None:
1213
revision_id = revision.as_revision_id(br_from)
1215
# FIXME - wt.last_revision, fallback to branch, fall back to
1216
# None or perhaps NULL_REVISION to mean copy nothing
1218
revision_id = br_from.last_revision()
1219
if to_location is None:
1220
to_location = urlutils.derive_to_location(from_location)
1221
to_transport = transport.get_transport(to_location)
1223
to_transport.mkdir('.')
1224
except errors.FileExists:
1225
if not use_existing_dir:
1226
raise errors.BzrCommandError('Target directory "%s" '
1227
'already exists.' % to_location)
1230
bzrdir.BzrDir.open_from_transport(to_transport)
1231
except errors.NotBranchError:
1234
raise errors.AlreadyBranchError(to_location)
1235
except errors.NoSuchFile:
1236
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1239
# preserve whatever source format we have.
1240
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1241
possible_transports=[to_transport],
1242
accelerator_tree=accelerator_tree,
1243
hardlink=hardlink, stacked=stacked,
1244
force_new_repo=standalone,
1245
create_tree_if_local=not no_tree,
1246
source_branch=br_from)
1247
branch = dir.open_branch()
1248
except errors.NoSuchRevision:
1249
to_transport.delete_tree('.')
1250
msg = "The branch %s has no revision %s." % (from_location,
1252
raise errors.BzrCommandError(msg)
1253
_merge_tags_if_possible(br_from, branch)
1254
# If the source branch is stacked, the new branch may
1255
# be stacked whether we asked for that explicitly or not.
1256
# We therefore need a try/except here and not just 'if stacked:'
1258
note('Created new stacked branch referring to %s.' %
1259
branch.get_stacked_on_url())
1260
except (errors.NotStacked, errors.UnstackableBranchFormat,
1261
errors.UnstackableRepositoryFormat), e:
861
elif len(revision) > 1:
862
raise errors.BzrCommandError(
863
'bzr branch --revision takes exactly 1 revision value')
865
br_from = Branch.open(from_location)
868
if len(revision) == 1 and revision[0] is not None:
869
revision_id = revision[0].in_history(br_from)[1]
871
# FIXME - wt.last_revision, fallback to branch, fall back to
872
# None or perhaps NULL_REVISION to mean copy nothing
874
revision_id = br_from.last_revision()
875
if to_location is None:
876
to_location = urlutils.derive_to_location(from_location)
879
name = os.path.basename(to_location) + '\n'
881
to_transport = transport.get_transport(to_location)
883
to_transport.mkdir('.')
884
except errors.FileExists:
885
raise errors.BzrCommandError('Target directory "%s" already'
886
' exists.' % to_location)
887
except errors.NoSuchFile:
888
raise errors.BzrCommandError('Parent of "%s" does not exist.'
891
# preserve whatever source format we have.
892
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
893
possible_transports=[to_transport])
894
branch = dir.open_branch()
895
except errors.NoSuchRevision:
896
to_transport.delete_tree('.')
897
msg = "The branch %s has no revision %s." % (from_location, revision[0])
898
raise errors.BzrCommandError(msg)
900
branch.control_files.put_utf8('branch-name', name)
901
_merge_tags_if_possible(br_from, branch)
1262
902
note('Branched %d revision(s).' % branch.revno())
1264
# Bind to the parent
1265
parent_branch = Branch.open(from_location)
1266
branch.bind(parent_branch)
1267
note('New branch bound to %s' % from_location)
1269
# Switch to the new branch
1270
wt, _ = WorkingTree.open_containing('.')
1271
_mod_switch.switch(wt.bzrdir, branch)
1272
note('Switched to branch: %s',
1273
urlutils.unescape_for_display(branch.base, 'utf-8'))
1276
907
class cmd_checkout(Command):
1277
__doc__ = """Create a new checkout of an existing branch.
908
"""Create a new checkout of an existing branch.
1279
910
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1280
911
the branch found in '.'. This is useful if you have removed the working tree
1281
912
or if it was never created - i.e. if you pushed the branch to its current
1282
913
location using SFTP.
1284
915
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1285
916
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1286
917
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1354
981
@display_command
1355
982
def run(self, dir=u'.'):
1356
983
tree = WorkingTree.open_containing(dir)[0]
1357
self.add_cleanup(tree.lock_read().unlock)
1358
new_inv = tree.inventory
1359
old_tree = tree.basis_tree()
1360
self.add_cleanup(old_tree.lock_read().unlock)
1361
old_inv = old_tree.inventory
1363
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1364
for f, paths, c, v, p, n, k, e in iterator:
1365
if paths[0] == paths[1]:
1369
renames.append(paths)
1371
for old_name, new_name in renames:
1372
self.outf.write("%s => %s\n" % (old_name, new_name))
986
new_inv = tree.inventory
987
old_tree = tree.basis_tree()
990
old_inv = old_tree.inventory
991
renames = list(_mod_tree.find_renames(old_inv, new_inv))
993
for old_name, new_name in renames:
994
self.outf.write("%s => %s\n" % (old_name, new_name))
1375
1001
class cmd_update(Command):
1376
__doc__ = """Update a tree to have the latest code committed to its branch.
1002
"""Update a tree to have the latest code committed to its branch.
1378
1004
This will perform a merge into the working tree, and may generate
1379
conflicts. If you have any local changes, you will still
1005
conflicts. If you have any local changes, you will still
1380
1006
need to commit them after the update for the update to be complete.
1382
If you want to discard your local changes, you can just do a
1008
If you want to discard your local changes, you can just do a
1383
1009
'bzr revert' instead of 'bzr commit' after the update.
1385
If the tree's branch is bound to a master branch, it will also update
1386
the branch from the master.
1389
1012
_see_also = ['pull', 'working-trees', 'status-flags']
1390
1013
takes_args = ['dir?']
1391
takes_options = ['revision']
1392
1014
aliases = ['up']
1394
def run(self, dir='.', revision=None):
1395
if revision is not None and len(revision) != 1:
1396
raise errors.BzrCommandError(
1397
"bzr update --revision takes exactly one revision")
1016
def run(self, dir='.'):
1398
1017
tree = WorkingTree.open_containing(dir)[0]
1399
branch = tree.branch
1400
1018
possible_transports = []
1401
master = branch.get_master_branch(
1019
master = tree.branch.get_master_branch(
1402
1020
possible_transports=possible_transports)
1403
1021
if master is not None:
1404
branch_location = master.base
1405
1022
tree.lock_write()
1407
branch_location = tree.branch.base
1408
1024
tree.lock_tree_write()
1409
self.add_cleanup(tree.unlock)
1410
# get rid of the final '/' and be ready for display
1411
branch_location = urlutils.unescape_for_display(
1412
branch_location.rstrip('/'),
1414
existing_pending_merges = tree.get_parent_ids()[1:]
1418
# may need to fetch data into a heavyweight checkout
1419
# XXX: this may take some time, maybe we should display a
1421
old_tip = branch.update(possible_transports)
1422
if revision is not None:
1423
revision_id = revision[0].as_revision_id(branch)
1425
revision_id = branch.last_revision()
1426
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1427
revno = branch.revision_id_to_dotted_revno(revision_id)
1428
note("Tree is up to date at revision %s of branch %s" %
1429
('.'.join(map(str, revno)), branch_location))
1431
view_info = _get_view_info_for_change_reporter(tree)
1432
change_reporter = delta._ChangeReporter(
1433
unversioned_filter=tree.is_ignored,
1434
view_info=view_info)
1026
existing_pending_merges = tree.get_parent_ids()[1:]
1027
last_rev = _mod_revision.ensure_null(tree.last_revision())
1028
if last_rev == _mod_revision.ensure_null(
1029
tree.branch.last_revision()):
1030
# may be up to date, check master too.
1031
if master is None or last_rev == _mod_revision.ensure_null(
1032
master.last_revision()):
1033
revno = tree.branch.revision_id_to_revno(last_rev)
1034
note("Tree is up to date at revision %d." % (revno,))
1436
1036
conflicts = tree.update(
1438
possible_transports=possible_transports,
1439
revision=revision_id,
1441
except errors.NoSuchRevision, e:
1442
raise errors.BzrCommandError(
1443
"branch has no revision %s\n"
1444
"bzr update --revision only works"
1445
" for a revision in the branch history"
1447
revno = tree.branch.revision_id_to_dotted_revno(
1448
_mod_revision.ensure_null(tree.last_revision()))
1449
note('Updated to revision %s of branch %s' %
1450
('.'.join(map(str, revno)), branch_location))
1451
parent_ids = tree.get_parent_ids()
1452
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1453
note('Your local commits will now show as pending merges with '
1454
"'bzr status', and can be committed with 'bzr commit'.")
1037
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1038
possible_transports=possible_transports)
1039
revno = tree.branch.revision_id_to_revno(
1040
_mod_revision.ensure_null(tree.last_revision()))
1041
note('Updated to revision %d.' % (revno,))
1042
if tree.get_parent_ids()[1:] != existing_pending_merges:
1043
note('Your local commits will now show as pending merges with '
1044
"'bzr status', and can be committed with 'bzr commit'.")
1461
1053
class cmd_info(Command):
1462
__doc__ = """Show information about a working tree, branch or repository.
1054
"""Show information about a working tree, branch or repository.
1464
1056
This command will show all known locations and formats associated to the
1465
tree, branch or repository.
1467
In verbose mode, statistical information is included with each report.
1468
To see extended statistic information, use a verbosity level of 2 or
1469
higher by specifying the verbose option multiple times, e.g. -vv.
1057
tree, branch or repository. Statistical information is included with
1471
1060
Branches and working trees will also report any missing revisions.
1475
Display information on the format and related locations:
1479
Display the above together with extended format information and
1480
basic statistics (like the number of files in the working tree and
1481
number of revisions in the branch and repository):
1485
Display the above together with number of committers to the branch:
1489
1062
_see_also = ['revno', 'working-trees', 'repositories']
1490
1063
takes_args = ['location?']
2080
1611
raise errors.BzrCommandError(msg)
2083
def _parse_levels(s):
2087
msg = "The levels argument must be an integer."
2088
raise errors.BzrCommandError(msg)
2091
1614
class cmd_log(Command):
2092
__doc__ = """Show historical log for a branch or subset of a branch.
2094
log is bzr's default tool for exploring the history of a branch.
2095
The branch to use is taken from the first parameter. If no parameters
2096
are given, the branch containing the working directory is logged.
2097
Here are some simple examples::
2099
bzr log log the current branch
2100
bzr log foo.py log a file in its branch
2101
bzr log http://server/branch log a branch on a server
2103
The filtering, ordering and information shown for each revision can
2104
be controlled as explained below. By default, all revisions are
2105
shown sorted (topologically) so that newer revisions appear before
2106
older ones and descendants always appear before ancestors. If displayed,
2107
merged revisions are shown indented under the revision in which they
2112
The log format controls how information about each revision is
2113
displayed. The standard log formats are called ``long``, ``short``
2114
and ``line``. The default is long. See ``bzr help log-formats``
2115
for more details on log formats.
2117
The following options can be used to control what information is
2120
-l N display a maximum of N revisions
2121
-n N display N levels of revisions (0 for all, 1 for collapsed)
2122
-v display a status summary (delta) for each revision
2123
-p display a diff (patch) for each revision
2124
--show-ids display revision-ids (and file-ids), not just revnos
2126
Note that the default number of levels to display is a function of the
2127
log format. If the -n option is not used, the standard log formats show
2128
just the top level (mainline).
2130
Status summaries are shown using status flags like A, M, etc. To see
2131
the changes explained using words like ``added`` and ``modified``
2132
instead, use the -vv option.
2136
To display revisions from oldest to newest, use the --forward option.
2137
In most cases, using this option will have little impact on the total
2138
time taken to produce a log, though --forward does not incrementally
2139
display revisions like --reverse does when it can.
2141
:Revision filtering:
2143
The -r option can be used to specify what revision or range of revisions
2144
to filter against. The various forms are shown below::
2146
-rX display revision X
2147
-rX.. display revision X and later
2148
-r..Y display up to and including revision Y
2149
-rX..Y display from X to Y inclusive
2151
See ``bzr help revisionspec`` for details on how to specify X and Y.
2152
Some common examples are given below::
2154
-r-1 show just the tip
2155
-r-10.. show the last 10 mainline revisions
2156
-rsubmit:.. show what's new on this branch
2157
-rancestor:path.. show changes since the common ancestor of this
2158
branch and the one at location path
2159
-rdate:yesterday.. show changes since yesterday
2161
When logging a range of revisions using -rX..Y, log starts at
2162
revision Y and searches back in history through the primary
2163
("left-hand") parents until it finds X. When logging just the
2164
top level (using -n1), an error is reported if X is not found
2165
along the way. If multi-level logging is used (-n0), X may be
2166
a nested merge revision and the log will be truncated accordingly.
2170
If parameters are given and the first one is not a branch, the log
2171
will be filtered to show only those revisions that changed the
2172
nominated files or directories.
2174
Filenames are interpreted within their historical context. To log a
2175
deleted file, specify a revision range so that the file existed at
2176
the end or start of the range.
2178
Historical context is also important when interpreting pathnames of
2179
renamed files/directories. Consider the following example:
2181
* revision 1: add tutorial.txt
2182
* revision 2: modify tutorial.txt
2183
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2187
* ``bzr log guide.txt`` will log the file added in revision 1
2189
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2191
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2192
the original file in revision 2.
2194
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2195
was no file called guide.txt in revision 2.
2197
Renames are always followed by log. By design, there is no need to
2198
explicitly ask for this (and no way to stop logging a file back
2199
until it was last renamed).
2203
The --message option can be used for finding revisions that match a
2204
regular expression in a commit message.
2208
GUI tools and IDEs are often better at exploring history than command
2209
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2210
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2211
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2212
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2214
You may find it useful to add the aliases below to ``bazaar.conf``::
2218
top = log -l10 --line
2221
``bzr tip`` will then show the latest revision while ``bzr top``
2222
will show the last 10 mainline revisions. To see the details of a
2223
particular revision X, ``bzr show -rX``.
2225
If you are interested in looking deeper into a particular merge X,
2226
use ``bzr log -n0 -rX``.
2228
``bzr log -v`` on a branch with lots of history is currently
2229
very slow. A fix for this issue is currently under development.
2230
With or without that fix, it is recommended that a revision range
2231
be given when using the -v option.
2233
bzr has a generic full-text matching plugin, bzr-search, that can be
2234
used to find revisions matching user names, commit messages, etc.
2235
Among other features, this plugin can find all revisions containing
2236
a list of words but not others.
2238
When exploring non-mainline history on large projects with deep
2239
history, the performance of log can be greatly improved by installing
2240
the historycache plugin. This plugin buffers historical information
2241
trading disk space for faster speed.
1615
"""Show log of a branch, file, or directory.
1617
By default show the log of the branch containing the working directory.
1619
To request a range of logs, you can use the command -r begin..end
1620
-r revision requests a specific revision, -r ..end or -r begin.. are
1624
Log the current branch::
1632
Log the last 10 revisions of a branch::
1634
bzr log -r -10.. http://server/branch
2243
takes_args = ['file*']
2244
_see_also = ['log-formats', 'revisionspec']
1637
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1639
takes_args = ['location?']
2245
1640
takes_options = [
2246
1641
Option('forward',
2247
1642
help='Show from oldest to newest.'),
1645
help='Display timezone as local, original, or utc.'),
2249
1646
custom_help('verbose',
2250
1647
help='Show files changed in each revision.'),
2254
type=bzrlib.option._parse_revision_str,
2256
help='Show just the specified revision.'
2257
' See also "help revisionspec".'),
2259
RegistryOption('authors',
2260
'What names to list as authors - first, all or committer.',
2262
lazy_registry=('bzrlib.log', 'author_list_registry'),
2266
help='Number of levels to display - 0 for all, 1 for flat.',
2268
type=_parse_levels),
2269
1651
Option('message',
2270
1652
short_name='m',
2271
1653
help='Show revisions whose message matches this '
2272
1654
'regular expression.',
2274
1656
Option('limit',
2276
1657
help='Limit the output to the first N revisions.',
2278
1659
type=_parse_limit),
2281
help='Show changes made in each revision as a patch.'),
2282
Option('include-merges',
2283
help='Show merged revisions like --levels 0 does.'),
2284
Option('exclude-common-ancestry',
2285
help='Display only the revisions that are not part'
2286
' of both ancestries (require -rX..Y)'
2289
1661
encoding_type = 'replace'
2291
1663
@display_command
2292
def run(self, file_list=None, timezone='original',
1664
def run(self, location=None, timezone='original',
2294
1666
show_ids=False,
2298
1669
log_format=None,
2303
include_merges=False,
2305
exclude_common_ancestry=False,
2307
from bzrlib.log import (
2309
make_log_request_dict,
2310
_get_info_for_log_files,
1672
from bzrlib.log import show_log
1673
assert message is None or isinstance(message, basestring), \
1674
"invalid message argument %r" % message
2312
1675
direction = (forward and 'forward') or 'reverse'
2313
if (exclude_common_ancestry
2314
and (revision is None or len(revision) != 2)):
2315
raise errors.BzrCommandError(
2316
'--exclude-common-ancestry requires -r with two revisions')
2321
raise errors.BzrCommandError(
2322
'--levels and --include-merges are mutually exclusive')
2324
if change is not None:
2326
raise errors.RangeInChangeOption()
2327
if revision is not None:
2328
raise errors.BzrCommandError(
2329
'--revision and --change are mutually exclusive')
2334
filter_by_dir = False
2336
# find the file ids to log and check for directory filtering
2337
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2338
revision, file_list, self.add_cleanup)
2339
for relpath, file_id, kind in file_info_list:
1680
# find the file id to log:
1682
tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1686
tree = b.basis_tree()
1687
file_id = tree.path2id(fp)
2340
1688
if file_id is None:
2341
1689
raise errors.BzrCommandError(
2342
"Path unknown at end or start of revision range: %s" %
2344
# If the relpath is the top of the tree, we log everything
2349
file_ids.append(file_id)
2350
filter_by_dir = filter_by_dir or (
2351
kind in ['directory', 'tree-reference'])
1690
"Path does not have any revision history: %s" %
2354
# FIXME ? log the current subdir only RBC 20060203
1694
# FIXME ? log the current subdir only RBC 20060203
2355
1695
if revision is not None \
2356
1696
and len(revision) > 0 and revision[0].get_branch():
2357
1697
location = revision[0].get_branch()
2360
1700
dir, relpath = bzrdir.BzrDir.open_containing(location)
2361
1701
b = dir.open_branch()
2362
self.add_cleanup(b.lock_read().unlock)
2363
rev1, rev2 = _get_revision_range(revision, b, self.name())
2365
# Decide on the type of delta & diff filtering to use
2366
# TODO: add an --all-files option to make this configurable & consistent
2374
diff_type = 'partial'
2378
# Build the log formatter
2379
if log_format is None:
2380
log_format = log.log_formatter_registry.get_default(b)
2381
# Make a non-encoding output to include the diffs - bug 328007
2382
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2383
lf = log_format(show_ids=show_ids, to_file=self.outf,
2384
to_exact_file=unencoded_output,
2385
show_timezone=timezone,
2386
delta_format=get_verbosity_level(),
2388
show_advice=levels is None,
2389
author_list_handler=authors)
2391
# Choose the algorithm for doing the logging. It's annoying
2392
# having multiple code paths like this but necessary until
2393
# the underlying repository format is faster at generating
2394
# deltas or can provide everything we need from the indices.
2395
# The default algorithm - match-using-deltas - works for
2396
# multiple files and directories and is faster for small
2397
# amounts of history (200 revisions say). However, it's too
2398
# slow for logging a single file in a repository with deep
2399
# history, i.e. > 10K revisions. In the spirit of "do no
2400
# evil when adding features", we continue to use the
2401
# original algorithm - per-file-graph - for the "single
2402
# file that isn't a directory without showing a delta" case.
2403
partial_history = revision and b.repository._format.supports_chks
2404
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2405
or delta_type or partial_history)
2407
# Build the LogRequest and execute it
2408
if len(file_ids) == 0:
2410
rqst = make_log_request_dict(
2411
direction=direction, specific_fileids=file_ids,
2412
start_revision=rev1, end_revision=rev2, limit=limit,
2413
message_search=message, delta_type=delta_type,
2414
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2415
exclude_common_ancestry=exclude_common_ancestry,
2417
Logger(b, rqst).show(lf)
2420
def _get_revision_range(revisionspec_list, branch, command_name):
2421
"""Take the input of a revision option and turn it into a revision range.
2423
It returns RevisionInfo objects which can be used to obtain the rev_id's
2424
of the desired revisions. It does some user input validations.
2426
if revisionspec_list is None:
2429
elif len(revisionspec_list) == 1:
2430
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2431
elif len(revisionspec_list) == 2:
2432
start_spec = revisionspec_list[0]
2433
end_spec = revisionspec_list[1]
2434
if end_spec.get_branch() != start_spec.get_branch():
2435
# b is taken from revision[0].get_branch(), and
2436
# show_log will use its revision_history. Having
2437
# different branches will lead to weird behaviors.
2438
raise errors.BzrCommandError(
2439
"bzr %s doesn't accept two revisions in different"
2440
" branches." % command_name)
2441
if start_spec.spec is None:
2442
# Avoid loading all the history.
2443
rev1 = RevisionInfo(branch, None, None)
2445
rev1 = start_spec.in_history(branch)
2446
# Avoid loading all of history when we know a missing
2447
# end of range means the last revision ...
2448
if end_spec.spec is None:
2449
last_revno, last_revision_id = branch.last_revision_info()
2450
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2452
rev2 = end_spec.in_history(branch)
2454
raise errors.BzrCommandError(
2455
'bzr %s --revision takes one or two values.' % command_name)
2459
def _revision_range_to_revid_range(revision_range):
2462
if revision_range[0] is not None:
2463
rev_id1 = revision_range[0].rev_id
2464
if revision_range[1] is not None:
2465
rev_id2 = revision_range[1].rev_id
2466
return rev_id1, rev_id2
1705
if revision is None:
1708
elif len(revision) == 1:
1709
rev1 = rev2 = revision[0].in_history(b)
1710
elif len(revision) == 2:
1711
if revision[1].get_branch() != revision[0].get_branch():
1712
# b is taken from revision[0].get_branch(), and
1713
# show_log will use its revision_history. Having
1714
# different branches will lead to weird behaviors.
1715
raise errors.BzrCommandError(
1716
"Log doesn't accept two revisions in different"
1718
rev1 = revision[0].in_history(b)
1719
rev2 = revision[1].in_history(b)
1721
raise errors.BzrCommandError(
1722
'bzr log --revision takes one or two values.')
1724
if log_format is None:
1725
log_format = log.log_formatter_registry.get_default(b)
1727
lf = log_format(show_ids=show_ids, to_file=self.outf,
1728
show_timezone=timezone)
1734
direction=direction,
1735
start_revision=rev1,
2468
1743
def get_log_format(long=False, short=False, line=False, default='long'):
2469
1744
log_format = default
2540
1812
if path is None:
2544
1817
raise errors.BzrCommandError('cannot specify both --from-root'
2547
tree, branch, relpath = \
2548
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2550
# Calculate the prefix to use
1821
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2554
prefix = relpath + '/'
2555
elif fs_path != '.' and not fs_path.endswith('/'):
2556
prefix = fs_path + '/'
2558
if revision is not None or tree is None:
2559
tree = _get_one_revision_tree('ls', revision, branch=branch)
2562
if isinstance(tree, WorkingTree) and tree.supports_views():
2563
view_files = tree.views.lookup_view()
2566
view_str = views.view_display_str(view_files)
2567
note("Ignoring files outside view. View is %s" % view_str)
2569
self.add_cleanup(tree.lock_read().unlock)
2570
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2571
from_dir=relpath, recursive=recursive):
2572
# Apply additional masking
2573
if not all and not selection[fc]:
2575
if kind is not None and fkind != kind:
2580
fullpath = osutils.pathjoin(relpath, fp)
2583
views.check_path_in_view(tree, fullpath)
2584
except errors.FileOutsideView:
2589
fp = osutils.pathjoin(prefix, fp)
2590
kindch = entry.kind_character()
2591
outstring = fp + kindch
2592
ui.ui_factory.clear_term()
2594
outstring = '%-8s %s' % (fc, outstring)
2595
if show_ids and fid is not None:
2596
outstring = "%-50s %s" % (outstring, fid)
2597
self.outf.write(outstring + '\n')
2599
self.outf.write(fp + '\0')
2602
self.outf.write(fid)
2603
self.outf.write('\0')
2611
self.outf.write('%-50s %s\n' % (outstring, my_id))
2613
self.outf.write(outstring + '\n')
1827
if revision is not None:
1828
tree = branch.repository.revision_tree(
1829
revision[0].in_history(branch).rev_id)
1831
tree = branch.basis_tree()
1835
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1836
if fp.startswith(relpath):
1837
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1838
if non_recursive and '/' in fp:
1840
if not all and not selection[fc]:
1842
if kind is not None and fkind != kind:
1845
kindch = entry.kind_character()
1846
outstring = '%-8s %s%s' % (fc, fp, kindch)
1847
if show_ids and fid is not None:
1848
outstring = "%-50s %s" % (outstring, fid)
1849
self.outf.write(outstring + '\n')
1851
self.outf.write(fp + '\0')
1854
self.outf.write(fid)
1855
self.outf.write('\0')
1863
self.outf.write('%-50s %s\n' % (fp, my_id))
1865
self.outf.write(fp + '\n')
2616
1870
class cmd_unknowns(Command):
2617
__doc__ = """List unknown files.
1871
"""List unknown files.
2621
1875
_see_also = ['ls']
2622
takes_options = ['directory']
2624
1877
@display_command
2625
def run(self, directory=u'.'):
2626
for f in WorkingTree.open_containing(directory)[0].unknowns():
1879
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2627
1880
self.outf.write(osutils.quotefn(f) + '\n')
2630
1883
class cmd_ignore(Command):
2631
__doc__ = """Ignore specified files or patterns.
2633
See ``bzr help patterns`` for details on the syntax of patterns.
2635
If a .bzrignore file does not exist, the ignore command
2636
will create one and add the specified files or patterns to the newly
2637
created file. The ignore command will also automatically add the
2638
.bzrignore file to be versioned. Creating a .bzrignore file without
2639
the use of the ignore command will require an explicit add command.
1884
"""Ignore specified files or patterns.
2641
1886
To remove patterns from the ignore list, edit the .bzrignore file.
2642
After adding, editing or deleting that file either indirectly by
2643
using this command or directly by using an editor, be sure to commit
2646
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2647
the global ignore file can be found in the application data directory as
2648
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2649
Global ignores are not touched by this command. The global ignore file
2650
can be edited directly using an editor.
2652
Patterns prefixed with '!' are exceptions to ignore patterns and take
2653
precedence over regular ignores. Such exceptions are used to specify
2654
files that should be versioned which would otherwise be ignored.
2656
Patterns prefixed with '!!' act as regular ignore patterns, but have
2657
precedence over the '!' exception patterns.
2659
Note: ignore patterns containing shell wildcards must be quoted from
1888
Trailing slashes on patterns are ignored.
1889
If the pattern contains a slash or is a regular expression, it is compared
1890
to the whole path from the branch root. Otherwise, it is compared to only
1891
the last component of the path. To match a file only in the root
1892
directory, prepend './'.
1894
Ignore patterns specifying absolute paths are not allowed.
1896
Ignore patterns may include globbing wildcards such as::
1898
? - Matches any single character except '/'
1899
* - Matches 0 or more characters except '/'
1900
/**/ - Matches 0 or more directories in a path
1901
[a-z] - Matches a single character from within a group of characters
1903
Ignore patterns may also be Python regular expressions.
1904
Regular expression ignore patterns are identified by a 'RE:' prefix
1905
followed by the regular expression. Regular expression ignore patterns
1906
may not include named or numbered groups.
1908
Note: ignore patterns containing shell wildcards must be quoted from
2660
1909
the shell on Unix.
2679
1924
Ignore .o files under the lib directory::
2681
1926
bzr ignore "RE:lib/.*\.o"
2683
Ignore everything but the "debian" toplevel directory::
2685
bzr ignore "RE:(?!debian/).*"
2687
Ignore everything except the "local" toplevel directory,
2688
but always ignore "*~" autosave files, even under local/::
2691
bzr ignore "!./local"
2695
_see_also = ['status', 'ignored', 'patterns']
1929
_see_also = ['status', 'ignored']
2696
1930
takes_args = ['name_pattern*']
2697
takes_options = ['directory',
2698
Option('default-rules',
2699
help='Display the default ignore rules that bzr uses.')
1932
Option('old-default-rules',
1933
help='Write out the ignore rules bzr < 0.9 always used.')
2702
def run(self, name_pattern_list=None, default_rules=None,
2704
from bzrlib import ignores
2705
if default_rules is not None:
2706
# dump the default rules and exit
2707
for pattern in ignores.USER_DEFAULTS:
2708
self.outf.write("%s\n" % pattern)
1936
def run(self, name_pattern_list=None, old_default_rules=None):
1937
from bzrlib.atomicfile import AtomicFile
1938
if old_default_rules is not None:
1939
# dump the rules and exit
1940
for pattern in ignores.OLD_DEFAULTS:
2710
1943
if not name_pattern_list:
2711
1944
raise errors.BzrCommandError("ignore requires at least one "
2712
"NAME_PATTERN or --default-rules.")
2713
name_pattern_list = [globbing.normalize_pattern(p)
1945
"NAME_PATTERN or --old-default-rules")
1946
name_pattern_list = [globbing.normalize_pattern(p)
2714
1947
for p in name_pattern_list]
2716
for p in name_pattern_list:
2717
if not globbing.Globster.is_pattern_valid(p):
2718
bad_patterns += ('\n %s' % p)
2720
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2721
ui.ui_factory.show_error(msg)
2722
raise errors.InvalidPattern('')
2723
1948
for name_pattern in name_pattern_list:
2724
if (name_pattern[0] == '/' or
1949
if (name_pattern[0] == '/' or
2725
1950
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2726
1951
raise errors.BzrCommandError(
2727
1952
"NAME_PATTERN should not be an absolute path")
2728
tree, relpath = WorkingTree.open_containing(directory)
2729
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
1953
tree, relpath = WorkingTree.open_containing(u'.')
1954
ifn = tree.abspath('.bzrignore')
1955
if os.path.exists(ifn):
1958
igns = f.read().decode('utf-8')
1964
# TODO: If the file already uses crlf-style termination, maybe
1965
# we should use that for the newly added lines?
1967
if igns and igns[-1] != '\n':
1969
for name_pattern in name_pattern_list:
1970
igns += name_pattern + '\n'
1972
f = AtomicFile(ifn, 'wb')
1974
f.write(igns.encode('utf-8'))
1979
if not tree.path2id('.bzrignore'):
1980
tree.add(['.bzrignore'])
2730
1982
ignored = globbing.Globster(name_pattern_list)
2732
self.add_cleanup(tree.lock_read().unlock)
2733
1985
for entry in tree.list_files():
2735
1987
if id is not None:
2736
1988
filename = entry[0]
2737
1989
if ignored.match(filename):
2738
matches.append(filename)
1990
matches.append(filename.encode('utf-8'))
2739
1992
if len(matches) > 0:
2740
self.outf.write("Warning: the following files are version controlled and"
2741
" match your ignore pattern:\n%s"
2742
"\nThese files will continue to be version controlled"
2743
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1993
print "Warning: the following files are version controlled and" \
1994
" match your ignore pattern:\n%s" % ("\n".join(matches),)
2746
1996
class cmd_ignored(Command):
2747
__doc__ = """List ignored files and the patterns that matched them.
2749
List all the ignored files and the ignore pattern that caused the file to
2752
Alternatively, to list just the files::
1997
"""List ignored files and the patterns that matched them.
2757
encoding_type = 'replace'
2758
_see_also = ['ignore', 'ls']
2759
takes_options = ['directory']
2000
_see_also = ['ignore']
2761
2001
@display_command
2762
def run(self, directory=u'.'):
2763
tree = WorkingTree.open_containing(directory)[0]
2764
self.add_cleanup(tree.lock_read().unlock)
2765
for path, file_class, kind, file_id, entry in tree.list_files():
2766
if file_class != 'I':
2768
## XXX: Slightly inefficient since this was already calculated
2769
pat = tree.is_ignored(path)
2770
self.outf.write('%-50s %s\n' % (path, pat))
2003
tree = WorkingTree.open_containing(u'.')[0]
2006
for path, file_class, kind, file_id, entry in tree.list_files():
2007
if file_class != 'I':
2009
## XXX: Slightly inefficient since this was already calculated
2010
pat = tree.is_ignored(path)
2011
print '%-50s %s' % (path, pat)
2773
2016
class cmd_lookup_revision(Command):
2774
__doc__ = """Lookup the revision-id from a revision-number
2017
"""Lookup the revision-id from a revision-number
2777
2020
bzr lookup-revision 33
2780
2023
takes_args = ['revno']
2781
takes_options = ['directory']
2783
2025
@display_command
2784
def run(self, revno, directory=u'.'):
2026
def run(self, revno):
2786
2028
revno = int(revno)
2787
2029
except ValueError:
2788
raise errors.BzrCommandError("not a valid revision-number: %r"
2790
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2791
self.outf.write("%s\n" % revid)
2030
raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2032
print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
2794
2035
class cmd_export(Command):
2795
__doc__ = """Export current or past revision to a destination directory or archive.
2036
"""Export current or past revision to a destination directory or archive.
2797
2038
If no revision is specified this exports the last committed revision.
2820
2061
================= =========================
2822
takes_args = ['dest', 'branch_or_subdir?']
2823
takes_options = ['directory',
2063
takes_args = ['dest', 'branch?']
2824
2065
Option('format',
2825
2066
help="Type of file to export to.",
2828
Option('filters', help='Apply content filters to export the '
2829
'convenient form.'),
2832
2071
help="Name of the root directory inside the exported file."),
2833
Option('per-file-timestamps',
2834
help='Set modification time of files to that of the last '
2835
'revision in which it was changed.'),
2837
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2838
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2073
def run(self, dest, branch=None, revision=None, format=None, root=None):
2839
2074
from bzrlib.export import export
2841
if branch_or_subdir is None:
2842
tree = WorkingTree.open_containing(directory)[0]
2077
tree = WorkingTree.open_containing(u'.')[0]
2843
2078
b = tree.branch
2846
b, subdir = Branch.open_containing(branch_or_subdir)
2849
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2080
b = Branch.open(branch)
2082
if revision is None:
2083
# should be tree.last_revision FIXME
2084
rev_id = b.last_revision()
2086
if len(revision) != 1:
2087
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2088
rev_id = revision[0].in_history(b).rev_id
2089
t = b.repository.revision_tree(rev_id)
2851
export(rev_tree, dest, format, root, subdir, filtered=filters,
2852
per_file_timestamps=per_file_timestamps)
2091
export(t, dest, format, root)
2853
2092
except errors.NoSuchExportFormat, e:
2854
2093
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2857
2096
class cmd_cat(Command):
2858
__doc__ = """Write the contents of a file as of a given revision to standard output.
2097
"""Write the contents of a file as of a given revision to standard output.
2860
2099
If no revision is nominated, the last revision is used.
2862
2101
Note: Take care to redirect standard output when using this command on a
2866
2105
_see_also = ['ls']
2867
takes_options = ['directory',
2868
2107
Option('name-from-revision', help='The path name in the old tree.'),
2869
Option('filters', help='Apply content filters to display the '
2870
'convenience form.'),
2873
2110
takes_args = ['filename']
2874
2111
encoding_type = 'exact'
2876
2113
@display_command
2877
def run(self, filename, revision=None, name_from_revision=False,
2878
filters=False, directory=None):
2114
def run(self, filename, revision=None, name_from_revision=False):
2879
2115
if revision is not None and len(revision) != 1:
2880
2116
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2881
" one revision specifier")
2882
tree, branch, relpath = \
2883
_open_directory_or_containing_tree_or_branch(filename, directory)
2884
self.add_cleanup(branch.lock_read().unlock)
2885
return self._run(tree, branch, relpath, filename, revision,
2886
name_from_revision, filters)
2888
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2120
tree, b, relpath = \
2121
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2122
except errors.NotBranchError:
2125
if revision is not None and revision[0].get_branch() is not None:
2126
b = Branch.open(revision[0].get_branch())
2129
return self._run(tree, b, relpath, filename, revision,
2134
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2890
2135
if tree is None:
2891
2136
tree = b.basis_tree()
2892
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2893
self.add_cleanup(rev_tree.lock_read().unlock)
2137
if revision is None:
2138
revision_id = b.last_revision()
2140
revision_id = revision[0].in_history(b).rev_id
2142
cur_file_id = tree.path2id(relpath)
2143
rev_tree = b.repository.revision_tree(revision_id)
2895
2144
old_file_id = rev_tree.path2id(relpath)
2897
2146
if name_from_revision:
2898
# Try in revision if requested
2899
2147
if old_file_id is None:
2900
raise errors.BzrCommandError(
2901
"%r is not present in revision %s" % (
2902
filename, rev_tree.get_revision_id()))
2148
raise errors.BzrCommandError("%r is not present in revision %s"
2149
% (filename, revision_id))
2904
content = rev_tree.get_file_text(old_file_id)
2906
cur_file_id = tree.path2id(relpath)
2908
if cur_file_id is not None:
2909
# Then try with the actual file id
2911
content = rev_tree.get_file_text(cur_file_id)
2913
except errors.NoSuchId:
2914
# The actual file id didn't exist at that time
2916
if not found and old_file_id is not None:
2917
# Finally try with the old file id
2918
content = rev_tree.get_file_text(old_file_id)
2921
# Can't be found anywhere
2922
raise errors.BzrCommandError(
2923
"%r is not present in revision %s" % (
2924
filename, rev_tree.get_revision_id()))
2926
from bzrlib.filters import (
2927
ContentFilterContext,
2928
filtered_output_bytes,
2930
filters = rev_tree._content_filter_stack(relpath)
2931
chunks = content.splitlines(True)
2932
content = filtered_output_bytes(chunks, filters,
2933
ContentFilterContext(relpath, rev_tree))
2935
self.outf.writelines(content)
2938
self.outf.write(content)
2151
rev_tree.print_file(old_file_id)
2152
elif cur_file_id is not None:
2153
rev_tree.print_file(cur_file_id)
2154
elif old_file_id is not None:
2155
rev_tree.print_file(old_file_id)
2157
raise errors.BzrCommandError("%r is not present in revision %s" %
2158
(filename, revision_id))
2941
2161
class cmd_local_time_offset(Command):
2942
__doc__ = """Show the offset in seconds from GMT to local time."""
2162
"""Show the offset in seconds from GMT to local time."""
2944
2164
@display_command
2946
self.outf.write("%s\n" % osutils.local_time_offset())
2166
print osutils.local_time_offset()
2950
2170
class cmd_commit(Command):
2951
__doc__ = """Commit changes into a new revision.
2953
An explanatory message needs to be given for each commit. This is
2954
often done by using the --message option (getting the message from the
2955
command line) or by using the --file option (getting the message from
2956
a file). If neither of these options is given, an editor is opened for
2957
the user to enter the message. To see the changed files in the
2958
boilerplate text loaded into the editor, use the --show-diff option.
2960
By default, the entire tree is committed and the person doing the
2961
commit is assumed to be the author. These defaults can be overridden
2966
If selected files are specified, only changes to those files are
2967
committed. If a directory is specified then the directory and
2968
everything within it is committed.
2970
When excludes are given, they take precedence over selected files.
2971
For example, to commit only changes within foo, but not changes
2974
bzr commit foo -x foo/bar
2976
A selective commit after a merge is not yet supported.
2980
If the author of the change is not the same person as the committer,
2981
you can specify the author's name using the --author option. The
2982
name should be in the same format as a committer-id, e.g.
2983
"John Doe <jdoe@example.com>". If there is more than one author of
2984
the change you can specify the option multiple times, once for each
2989
A common mistake is to forget to add a new file or directory before
2990
running the commit command. The --strict option checks for unknown
2991
files and aborts the commit if any are found. More advanced pre-commit
2992
checks can be implemented by defining hooks. See ``bzr help hooks``
2997
If you accidentially commit the wrong changes or make a spelling
2998
mistake in the commit message say, you can use the uncommit command
2999
to undo it. See ``bzr help uncommit`` for details.
3001
Hooks can also be configured to run after a commit. This allows you
3002
to trigger updates to external systems like bug trackers. The --fixes
3003
option can be used to record the association between a revision and
3004
one or more bugs. See ``bzr help bugs`` for details.
3006
A selective commit may fail in some cases where the committed
3007
tree would be invalid. Consider::
3012
bzr commit foo -m "committing foo"
3013
bzr mv foo/bar foo/baz
3016
bzr commit foo/bar -m "committing bar but not baz"
3018
In the example above, the last commit will fail by design. This gives
3019
the user the opportunity to decide whether they want to commit the
3020
rename at the same time, separately first, or not at all. (As a general
3021
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2171
"""Commit changes into a new revision.
2173
If no arguments are given, the entire tree is committed.
2175
If selected files are specified, only changes to those files are
2176
committed. If a directory is specified then the directory and everything
2177
within it is committed.
2179
If author of the change is not the same person as the committer, you can
2180
specify the author's name using the --author option. The name should be
2181
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2183
A selected-file commit may fail in some cases where the committed
2184
tree would be invalid. Consider::
2189
bzr commit foo -m "committing foo"
2190
bzr mv foo/bar foo/baz
2193
bzr commit foo/bar -m "committing bar but not baz"
2195
In the example above, the last commit will fail by design. This gives
2196
the user the opportunity to decide whether they want to commit the
2197
rename at the same time, separately first, or not at all. (As a general
2198
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2200
Note: A selected-file commit after a merge is not yet supported.
3023
2202
# TODO: Run hooks on tree to-be-committed, and after commit.
3209
2340
raise errors.BzrCommandError("Commit refused because there are"
3210
2341
" unknown files in the working tree.")
3211
2342
except errors.BoundBranchOutOfDate, e:
3212
e.extra_help = ("\n"
3213
'To commit to master branch, run update and then commit.\n'
3214
'You can also pass --local to commit to continue working '
2343
raise errors.BzrCommandError(str(e) + "\n"
2344
'To commit to master branch, run update and then commit.\n'
2345
'You can also pass --local to commit to continue working '
3219
2349
class cmd_check(Command):
3220
__doc__ = """Validate working tree structure, branch consistency and repository history.
3222
This command checks various invariants about branch and repository storage
3223
to detect data corruption or bzr bugs.
3225
The working tree and branch checks will only give output if a problem is
3226
detected. The output fields of the repository check are:
3229
This is just the number of revisions checked. It doesn't
3233
This is just the number of versionedfiles checked. It
3234
doesn't indicate a problem.
3236
unreferenced ancestors
3237
Texts that are ancestors of other texts, but
3238
are not properly referenced by the revision ancestry. This is a
3239
subtle problem that Bazaar can work around.
3242
This is the total number of unique file contents
3243
seen in the checked revisions. It does not indicate a problem.
3246
This is the total number of repeated texts seen
3247
in the checked revisions. Texts can be repeated when their file
3248
entries are modified, but the file contents are not. It does not
3251
If no restrictions are specified, all Bazaar data that is found at the given
3252
location will be checked.
3256
Check the tree and branch at 'foo'::
3258
bzr check --tree --branch foo
3260
Check only the repository at 'bar'::
3262
bzr check --repo bar
3264
Check everything at 'baz'::
2350
"""Validate consistency of branch history.
2352
This command checks various invariants about the branch storage to
2353
detect data corruption or bzr bugs.
2357
revisions: This is just the number of revisions checked. It doesn't
2359
versionedfiles: This is just the number of versionedfiles checked. It
2360
doesn't indicate a problem.
2361
unreferenced ancestors: Texts that are ancestors of other texts, but
2362
are not properly referenced by the revision ancestry. This is a
2363
subtle problem that Bazaar can work around.
2364
unique file texts: This is the total number of unique file contents
2365
seen in the checked revisions. It does not indicate a problem.
2366
repeated file texts: This is the total number of repeated texts seen
2367
in the checked revisions. Texts can be repeated when their file
2368
entries are modified, but the file contents are not. It does not
3269
2372
_see_also = ['reconcile']
3270
takes_args = ['path?']
3271
takes_options = ['verbose',
3272
Option('branch', help="Check the branch related to the"
3273
" current directory."),
3274
Option('repo', help="Check the repository related to the"
3275
" current directory."),
3276
Option('tree', help="Check the working tree related to"
3277
" the current directory.")]
2373
takes_args = ['branch?']
2374
takes_options = ['verbose']
3279
def run(self, path=None, verbose=False, branch=False, repo=False,
3281
from bzrlib.check import check_dwim
3284
if not branch and not repo and not tree:
3285
branch = repo = tree = True
3286
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2376
def run(self, branch=None, verbose=False):
2377
from bzrlib.check import check
2379
branch_obj = Branch.open_containing('.')[0]
2381
branch_obj = Branch.open(branch)
2382
check(branch_obj, verbose)
2383
# bit hacky, check the tree parent is accurate
2386
tree = WorkingTree.open_containing('.')[0]
2388
tree = WorkingTree.open(branch)
2389
except (errors.NoWorkingTree, errors.NotLocalUrl):
2392
# This is a primitive 'check' for tree state. Currently this is not
2393
# integrated into the main check logic as yet.
2396
tree_basis = tree.basis_tree()
2397
tree_basis.lock_read()
2399
repo_basis = tree.branch.repository.revision_tree(
2400
tree.last_revision())
2401
if len(list(repo_basis._iter_changes(tree_basis))):
2402
raise errors.BzrCheckError(
2403
"Mismatched basis inventory content.")
3289
2411
class cmd_upgrade(Command):
3290
__doc__ = """Upgrade branch storage to current format.
2412
"""Upgrade branch storage to current format.
3292
2414
The check command or bzr developers may sometimes advise you to run
3293
2415
this command. When the default format has changed you may also be warned
3562
2597
short_name='x',
3563
2598
help='Exclude tests that match this regular'
3564
2599
' expression.'),
3566
help='Output test progress via subunit.'),
3567
2600
Option('strict', help='Fail on missing dependencies or '
3568
2601
'known failures.'),
3569
Option('load-list', type=str, argname='TESTLISTFILE',
3570
help='Load a test id list from a text file.'),
3571
ListOption('debugflag', type=str, short_name='E',
3572
help='Turn on a selftest debug flag.'),
3573
ListOption('starting-with', type=str, argname='TESTID',
3574
param_name='starting_with', short_name='s',
3576
'Load only the tests starting with TESTID.'),
3578
2603
encoding_type = 'replace'
3581
Command.__init__(self)
3582
self.additional_selftest_args = {}
3584
2605
def run(self, testspecs_list=None, verbose=False, one=False,
3585
2606
transport=None, benchmark=None,
2607
lsprof_timed=None, cache_dir=None,
3587
2608
first=False, list_only=False,
3588
randomize=None, exclude=None, strict=False,
3589
load_list=None, debugflag=None, starting_with=None, subunit=False,
3590
parallel=None, lsprof_tests=False):
2609
randomize=None, exclude=None, strict=False):
3591
2611
from bzrlib.tests import selftest
3593
# Make deprecation warnings visible, unless -Werror is set
3594
symbol_versioning.activate_deprecation_warnings(override=False)
2612
import bzrlib.benchmarks as benchmarks
2613
from bzrlib.benchmarks import tree_creator
2615
if cache_dir is not None:
2616
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2618
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2619
print ' %s (%s python%s)' % (
2621
bzrlib.version_string,
2622
'.'.join(map(str, sys.version_info)),
3596
2625
if testspecs_list is not None:
3597
2626
pattern = '|'.join(testspecs_list)
3602
from bzrlib.tests import SubUnitBzrRunner
3604
raise errors.BzrCommandError("subunit not available. subunit "
3605
"needs to be installed to use --subunit.")
3606
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3607
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3608
# stdout, which would corrupt the subunit stream.
3609
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3610
# following code can be deleted when it's sufficiently deployed
3611
# -- vila/mgz 20100514
3612
if (sys.platform == "win32"
3613
and getattr(sys.stdout, 'fileno', None) is not None):
3615
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3617
self.additional_selftest_args.setdefault(
3618
'suite_decorators', []).append(parallel)
3620
raise errors.BzrCommandError(
3621
"--benchmark is no longer supported from bzr 2.2; "
3622
"use bzr-usertest instead")
3623
test_suite_factory = None
3624
selftest_kwargs = {"verbose": verbose,
3626
"stop_on_failure": one,
3627
"transport": transport,
3628
"test_suite_factory": test_suite_factory,
3629
"lsprof_timed": lsprof_timed,
3630
"lsprof_tests": lsprof_tests,
3631
"matching_tests_first": first,
3632
"list_only": list_only,
3633
"random_seed": randomize,
3634
"exclude_pattern": exclude,
3636
"load_list": load_list,
3637
"debug_flags": debugflag,
3638
"starting_with": starting_with
3640
selftest_kwargs.update(self.additional_selftest_args)
3641
result = selftest(**selftest_kwargs)
2630
test_suite_factory = benchmarks.test_suite
2631
# Unless user explicitly asks for quiet, be verbose in benchmarks
2632
verbose = not is_quiet()
2633
# TODO: should possibly lock the history file...
2634
benchfile = open(".perf_history", "at", buffering=1)
2636
test_suite_factory = None
2639
result = selftest(verbose=verbose,
2641
stop_on_failure=one,
2642
transport=transport,
2643
test_suite_factory=test_suite_factory,
2644
lsprof_timed=lsprof_timed,
2645
bench_history=benchfile,
2646
matching_tests_first=first,
2647
list_only=list_only,
2648
random_seed=randomize,
2649
exclude_pattern=exclude,
2653
if benchfile is not None:
2656
info('tests passed')
2658
info('tests failed')
3642
2659
return int(not result)
3645
2662
class cmd_version(Command):
3646
__doc__ = """Show version of bzr."""
2663
"""Show version of bzr."""
3648
2665
encoding_type = 'replace'
3650
Option("short", help="Print just the version number."),
3653
2667
@display_command
3654
def run(self, short=False):
3655
2669
from bzrlib.version import show_version
3657
self.outf.write(bzrlib.version_string + '\n')
3659
show_version(to_file=self.outf)
2670
show_version(to_file=self.outf)
3662
2673
class cmd_rocks(Command):
3663
__doc__ = """Statement of optimism."""
2674
"""Statement of optimism."""
3667
2678
@display_command
3669
self.outf.write("It sure does!\n")
2680
print "It sure does!"
3672
2683
class cmd_find_merge_base(Command):
3673
__doc__ = """Find and print a base revision for merging two branches."""
2684
"""Find and print a base revision for merging two branches."""
3674
2685
# TODO: Options to specify revisions on either side, as if
3675
2686
# merging only part of the history.
3676
2687
takes_args = ['branch', 'other']
3679
2690
@display_command
3680
2691
def run(self, branch, other):
3681
2692
from bzrlib.revision import ensure_null
3683
2694
branch1 = Branch.open_containing(branch)[0]
3684
2695
branch2 = Branch.open_containing(other)[0]
3685
self.add_cleanup(branch1.lock_read().unlock)
3686
self.add_cleanup(branch2.lock_read().unlock)
3687
last1 = ensure_null(branch1.last_revision())
3688
last2 = ensure_null(branch2.last_revision())
3690
graph = branch1.repository.get_graph(branch2.repository)
3691
base_rev_id = graph.find_unique_lca(last1, last2)
3693
self.outf.write('merge base is revision %s\n' % base_rev_id)
2700
last1 = ensure_null(branch1.last_revision())
2701
last2 = ensure_null(branch2.last_revision())
2703
graph = branch1.repository.get_graph(branch2.repository)
2704
base_rev_id = graph.find_unique_lca(last1, last2)
2706
print 'merge base is revision %s' % base_rev_id
3696
2713
class cmd_merge(Command):
3697
__doc__ = """Perform a three-way merge.
3699
The source of the merge can be specified either in the form of a branch,
3700
or in the form of a path to a file containing a merge directive generated
3701
with bzr send. If neither is specified, the default is the upstream branch
3702
or the branch most recently merged using --remember.
3704
When merging a branch, by default the tip will be merged. To pick a different
3705
revision, pass --revision. If you specify two values, the first will be used as
3706
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3707
available revisions, like this is commonly referred to as "cherrypicking".
3709
Revision numbers are always relative to the branch being merged.
2714
"""Perform a three-way merge.
2716
The branch is the branch you will merge from. By default, it will merge
2717
the latest revision. If you specify a revision, that revision will be
2718
merged. If you specify two revisions, the first will be used as a BASE,
2719
and the second one as OTHER. Revision numbers are always relative to the
3711
2722
By default, bzr will try to merge in all new work from the other
3712
2723
branch, automatically determining an appropriate base. If this
3713
2724
fails, you may need to give an explicit base.
3715
2726
Merge will do its best to combine the changes in two branches, but there
3716
2727
are some kinds of problems only a human can fix. When it encounters those,
3717
2728
it will mark a conflict. A conflict means that you need to fix something,
3808
2800
allow_pending = True
3809
2801
verified = 'inapplicable'
3810
2802
tree = WorkingTree.open_containing(directory)[0]
3813
basis_tree = tree.revision_tree(tree.last_revision())
3814
except errors.NoSuchRevision:
3815
basis_tree = tree.basis_tree()
3817
# die as quickly as possible if there are uncommitted changes
3819
if tree.has_changes():
3820
raise errors.UncommittedChanges(tree)
3822
view_info = _get_view_info_for_change_reporter(tree)
3823
2803
change_reporter = delta._ChangeReporter(
3824
unversioned_filter=tree.is_ignored, view_info=view_info)
3825
pb = ui.ui_factory.nested_progress_bar()
3826
self.add_cleanup(pb.finished)
3827
self.add_cleanup(tree.lock_write().unlock)
3828
if location is not None:
3830
mergeable = bundle.read_mergeable_from_url(location,
3831
possible_transports=possible_transports)
3832
except errors.NotABundle:
2804
unversioned_filter=tree.is_ignored)
2807
pb = ui.ui_factory.nested_progress_bar()
2808
cleanups.append(pb.finished)
2810
cleanups.append(tree.unlock)
2811
if location is not None:
2812
mergeable, other_transport = _get_mergeable_helper(location)
2815
raise errors.BzrCommandError('Cannot use --uncommitted'
2816
' with bundles or merge directives.')
2818
if revision is not None:
2819
raise errors.BzrCommandError(
2820
'Cannot use -r with merge directives or bundles')
2821
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2823
possible_transports.append(other_transport)
2825
if merger is None and uncommitted:
2826
if revision is not None and len(revision) > 0:
2827
raise errors.BzrCommandError('Cannot use --uncommitted and'
2828
' --revision at the same time.')
2829
location = self._select_branch_location(tree, location)[0]
2830
other_tree, other_path = WorkingTree.open_containing(location)
2831
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2833
allow_pending = False
2834
if other_path != '':
2835
merger.interesting_files = [other_path]
2838
merger, allow_pending = self._get_merger_from_branch(tree,
2839
location, revision, remember, possible_transports, pb)
2841
merger.merge_type = merge_type
2842
merger.reprocess = reprocess
2843
merger.show_base = show_base
2844
merger.change_reporter = change_reporter
2845
self.sanity_check_merger(merger)
2846
if (merger.base_rev_id == merger.other_rev_id and
2847
merger.other_rev_id != None):
2848
note('Nothing to do.')
2851
if merger.interesting_files is not None:
2852
raise errors.BzrCommandError('Cannot pull individual files')
2853
if (merger.base_rev_id == tree.last_revision()):
2854
result = tree.pull(merger.other_branch, False,
2855
merger.other_rev_id)
2856
result.report(self.outf)
2858
merger.check_basis(not force)
2859
conflict_count = merger.do_merge()
2861
merger.set_pending()
2862
if verified == 'failed':
2863
warning('Preview patch does not match changes')
2864
if conflict_count != 0:
3836
raise errors.BzrCommandError('Cannot use --uncommitted'
3837
' with bundles or merge directives.')
3839
if revision is not None:
3840
raise errors.BzrCommandError(
3841
'Cannot use -r with merge directives or bundles')
3842
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3845
if merger is None and uncommitted:
3846
if revision is not None and len(revision) > 0:
3847
raise errors.BzrCommandError('Cannot use --uncommitted and'
3848
' --revision at the same time.')
3849
merger = self.get_merger_from_uncommitted(tree, location, None)
3850
allow_pending = False
3853
merger, allow_pending = self._get_merger_from_branch(tree,
3854
location, revision, remember, possible_transports, None)
3856
merger.merge_type = merge_type
3857
merger.reprocess = reprocess
3858
merger.show_base = show_base
3859
self.sanity_check_merger(merger)
3860
if (merger.base_rev_id == merger.other_rev_id and
3861
merger.other_rev_id is not None):
3862
note('Nothing to do.')
3865
if merger.interesting_files is not None:
3866
raise errors.BzrCommandError('Cannot pull individual files')
3867
if (merger.base_rev_id == tree.last_revision()):
3868
result = tree.pull(merger.other_branch, False,
3869
merger.other_rev_id)
3870
result.report(self.outf)
3872
if merger.this_basis is None:
3873
raise errors.BzrCommandError(
3874
"This branch has no commits."
3875
" (perhaps you would prefer 'bzr pull')")
3877
return self._do_preview(merger)
3879
return self._do_interactive(merger)
3881
return self._do_merge(merger, change_reporter, allow_pending,
3884
def _get_preview(self, merger):
3885
tree_merger = merger.make_merger()
3886
tt = tree_merger.make_preview_transform()
3887
self.add_cleanup(tt.finalize)
3888
result_tree = tt.get_preview_tree()
3891
def _do_preview(self, merger):
3892
from bzrlib.diff import show_diff_trees
3893
result_tree = self._get_preview(merger)
3894
path_encoding = osutils.get_diff_header_encoding()
3895
show_diff_trees(merger.this_tree, result_tree, self.outf,
3896
old_label='', new_label='',
3897
path_encoding=path_encoding)
3899
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3900
merger.change_reporter = change_reporter
3901
conflict_count = merger.do_merge()
3903
merger.set_pending()
3904
if verified == 'failed':
3905
warning('Preview patch does not match changes')
3906
if conflict_count != 0:
3911
def _do_interactive(self, merger):
3912
"""Perform an interactive merge.
3914
This works by generating a preview tree of the merge, then using
3915
Shelver to selectively remove the differences between the working tree
3916
and the preview tree.
3918
from bzrlib import shelf_ui
3919
result_tree = self._get_preview(merger)
3920
writer = bzrlib.option.diff_writer_registry.get()
3921
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3922
reporter=shelf_ui.ApplyReporter(),
3923
diff_writer=writer(sys.stdout))
2869
for cleanup in reversed(cleanups):
3929
2872
def sanity_check_merger(self, merger):
3930
2873
if (merger.show_base and
3931
2874
not merger.merge_type is _mod_merge.Merge3Merger):
3932
2875
raise errors.BzrCommandError("Show-base is not supported for this"
3933
2876
" merge type. %s" % merger.merge_type)
3934
if merger.reprocess is None:
3935
if merger.show_base:
3936
merger.reprocess = False
3938
# Use reprocess if the merger supports it
3939
merger.reprocess = merger.merge_type.supports_reprocess
3940
2877
if merger.reprocess and not merger.merge_type.supports_reprocess:
3941
2878
raise errors.BzrCommandError("Conflict reduction is not supported"
3942
2879
" for merge type %s." %
4085
3011
def run(self, file_list=None, merge_type=None, show_base=False,
4086
3012
reprocess=False):
4087
from bzrlib.conflicts import restore
4088
3013
if merge_type is None:
4089
3014
merge_type = _mod_merge.Merge3Merger
4090
3015
tree, file_list = tree_files(file_list)
4091
self.add_cleanup(tree.lock_write().unlock)
4092
parents = tree.get_parent_ids()
4093
if len(parents) != 2:
4094
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4095
" merges. Not cherrypicking or"
4097
repository = tree.branch.repository
4098
interesting_ids = None
4100
conflicts = tree.conflicts()
4101
if file_list is not None:
4102
interesting_ids = set()
4103
for filename in file_list:
4104
file_id = tree.path2id(filename)
4106
raise errors.NotVersionedError(filename)
4107
interesting_ids.add(file_id)
4108
if tree.kind(file_id) != "directory":
4111
for name, ie in tree.inventory.iter_entries(file_id):
4112
interesting_ids.add(ie.file_id)
4113
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4115
# Remerge only supports resolving contents conflicts
4116
allowed_conflicts = ('text conflict', 'contents conflict')
4117
restore_files = [c.path for c in conflicts
4118
if c.typestring in allowed_conflicts]
4119
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4120
tree.set_conflicts(ConflictList(new_conflicts))
4121
if file_list is not None:
4122
restore_files = file_list
4123
for filename in restore_files:
3018
parents = tree.get_parent_ids()
3019
if len(parents) != 2:
3020
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3021
" merges. Not cherrypicking or"
3023
repository = tree.branch.repository
3024
graph = repository.get_graph()
3025
base_revision = graph.find_unique_lca(parents[0], parents[1])
3026
base_tree = repository.revision_tree(base_revision)
3027
other_tree = repository.revision_tree(parents[1])
3028
interesting_ids = None
3030
conflicts = tree.conflicts()
3031
if file_list is not None:
3032
interesting_ids = set()
3033
for filename in file_list:
3034
file_id = tree.path2id(filename)
3036
raise errors.NotVersionedError(filename)
3037
interesting_ids.add(file_id)
3038
if tree.kind(file_id) != "directory":
3041
for name, ie in tree.inventory.iter_entries(file_id):
3042
interesting_ids.add(ie.file_id)
3043
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3045
# Remerge only supports resolving contents conflicts
3046
allowed_conflicts = ('text conflict', 'contents conflict')
3047
restore_files = [c.path for c in conflicts
3048
if c.typestring in allowed_conflicts]
3049
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3050
tree.set_conflicts(ConflictList(new_conflicts))
3051
if file_list is not None:
3052
restore_files = file_list
3053
for filename in restore_files:
3055
restore(tree.abspath(filename))
3056
except errors.NotConflicted:
3058
# Disable pending merges, because the file texts we are remerging
3059
# have not had those merges performed. If we use the wrong parents
3060
# list, we imply that the working tree text has seen and rejected
3061
# all the changes from the other tree, when in fact those changes
3062
# have not yet been seen.
3063
tree.set_parent_ids(parents[:1])
4125
restore(tree.abspath(filename))
4126
except errors.NotConflicted:
4128
# Disable pending merges, because the file texts we are remerging
4129
# have not had those merges performed. If we use the wrong parents
4130
# list, we imply that the working tree text has seen and rejected
4131
# all the changes from the other tree, when in fact those changes
4132
# have not yet been seen.
4133
tree.set_parent_ids(parents[:1])
4135
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4136
merger.interesting_ids = interesting_ids
4137
merger.merge_type = merge_type
4138
merger.show_base = show_base
4139
merger.reprocess = reprocess
4140
conflicts = merger.do_merge()
3065
conflicts = _mod_merge.merge_inner(
3066
tree.branch, other_tree, base_tree,
3068
interesting_ids=interesting_ids,
3069
other_rev_id=parents[1],
3070
merge_type=merge_type,
3071
show_base=show_base,
3072
reprocess=reprocess)
3074
tree.set_parent_ids(parents)
4142
tree.set_parent_ids(parents)
4143
3077
if conflicts > 0:
4358
3248
" or specified.")
4359
3249
display_url = urlutils.unescape_for_display(parent,
4360
3250
self.outf.encoding)
4361
message("Using saved parent location: "
4362
+ display_url + "\n")
3251
self.outf.write("Using last location: " + display_url + "\n")
4364
3253
remote_branch = Branch.open(other_branch)
4365
3254
if remote_branch.base == local_branch.base:
4366
3255
remote_branch = local_branch
4368
self.add_cleanup(remote_branch.lock_read().unlock)
4370
local_revid_range = _revision_range_to_revid_range(
4371
_get_revision_range(my_revision, local_branch,
4374
remote_revid_range = _revision_range_to_revid_range(
4375
_get_revision_range(revision,
4376
remote_branch, self.name()))
4378
local_extra, remote_extra = find_unmerged(
4379
local_branch, remote_branch, restrict,
4380
backward=not reverse,
4381
include_merges=include_merges,
4382
local_revid_range=local_revid_range,
4383
remote_revid_range=remote_revid_range)
4385
if log_format is None:
4386
registry = log.log_formatter_registry
4387
log_format = registry.get_default(local_branch)
4388
lf = log_format(to_file=self.outf,
4390
show_timezone='original')
4393
if local_extra and not theirs_only:
4394
message("You have %d extra revision(s):\n" %
4396
for revision in iter_log_revisions(local_extra,
4397
local_branch.repository,
4399
lf.log_revision(revision)
4400
printed_local = True
4403
printed_local = False
4405
if remote_extra and not mine_only:
4406
if printed_local is True:
4408
message("You are missing %d revision(s):\n" %
4410
for revision in iter_log_revisions(remote_extra,
4411
remote_branch.repository,
4413
lf.log_revision(revision)
4416
if mine_only and not local_extra:
4417
# We checked local, and found nothing extra
4418
message('This branch is up to date.\n')
4419
elif theirs_only and not remote_extra:
4420
# We checked remote, and found nothing extra
4421
message('Other branch is up to date.\n')
4422
elif not (mine_only or theirs_only or local_extra or
4424
# We checked both branches, and neither one had extra
4426
message("Branches are up to date.\n")
3256
local_branch.lock_read()
3258
remote_branch.lock_read()
3260
local_extra, remote_extra = find_unmerged(local_branch,
3262
if log_format is None:
3263
registry = log.log_formatter_registry
3264
log_format = registry.get_default(local_branch)
3265
lf = log_format(to_file=self.outf,
3267
show_timezone='original')
3268
if reverse is False:
3269
local_extra.reverse()
3270
remote_extra.reverse()
3271
if local_extra and not theirs_only:
3272
self.outf.write("You have %d extra revision(s):\n" %
3274
for revision in iter_log_revisions(local_extra,
3275
local_branch.repository,
3277
lf.log_revision(revision)
3278
printed_local = True
3280
printed_local = False
3281
if remote_extra and not mine_only:
3282
if printed_local is True:
3283
self.outf.write("\n\n\n")
3284
self.outf.write("You are missing %d revision(s):\n" %
3286
for revision in iter_log_revisions(remote_extra,
3287
remote_branch.repository,
3289
lf.log_revision(revision)
3290
if not remote_extra and not local_extra:
3292
self.outf.write("Branches are up to date.\n")
3296
remote_branch.unlock()
3298
local_branch.unlock()
4428
3299
if not status_code and parent is None and other_branch is not None:
4429
self.add_cleanup(local_branch.lock_write().unlock)
4430
# handle race conditions - a parent might be set while we run.
4431
if local_branch.get_parent() is None:
4432
local_branch.set_parent(remote_branch.base)
3300
local_branch.lock_write()
3302
# handle race conditions - a parent might be set while we run.
3303
if local_branch.get_parent() is None:
3304
local_branch.set_parent(remote_branch.base)
3306
local_branch.unlock()
4433
3307
return status_code
4436
3310
class cmd_pack(Command):
4437
__doc__ = """Compress the data within a repository.
4439
This operation compresses the data within a bazaar repository. As
4440
bazaar supports automatic packing of repository, this operation is
4441
normally not required to be done manually.
4443
During the pack operation, bazaar takes a backup of existing repository
4444
data, i.e. pack files. This backup is eventually removed by bazaar
4445
automatically when it is safe to do so. To save disk space by removing
4446
the backed up pack files, the --clean-obsolete-packs option may be
4449
Warning: If you use --clean-obsolete-packs and your machine crashes
4450
during or immediately after repacking, you may be left with a state
4451
where the deletion has been written to disk but the new packs have not
4452
been. In this case the repository may be unusable.
3311
"""Compress the data within a repository."""
4455
3313
_see_also = ['repositories']
4456
3314
takes_args = ['branch_or_repo?']
4458
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4461
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3316
def run(self, branch_or_repo='.'):
4462
3317
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4464
3319
branch = dir.open_branch()
4465
3320
repository = branch.repository
4466
3321
except errors.NotBranchError:
4467
3322
repository = dir.open_repository()
4468
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4471
3326
class cmd_plugins(Command):
4472
__doc__ = """List the installed plugins.
4474
This command displays the list of installed plugins including
4475
version of plugin and a short description of each.
4477
--verbose shows the path where each plugin is located.
3327
"""List the installed plugins.
3329
This command displays the list of installed plugins including the
3330
path where each one is located and a short description of each.
4479
3332
A plugin is an external component for Bazaar that extends the
4480
3333
revision control system, by adding or replacing code in Bazaar.
5189
3978
'rather than the one containing the working directory.',
5190
3979
short_name='f',
5192
Option('output', short_name='o',
5193
help='Write merge directive to this file or directory; '
5194
'use - for stdout.',
3981
Option('output', short_name='o', help='Write directive to this file.',
5197
help='Refuse to send if there are uncommitted changes in'
5198
' the working tree, --no-strict disables the check.'),
5199
3983
Option('mail-to', help='Mail the request to this address.',
5203
Option('body', help='Body for the email.', type=unicode),
5204
RegistryOption('format',
5205
help='Use the specified output format.',
5206
lazy_registry=('bzrlib.send', 'format_registry')),
3987
RegistryOption.from_kwargs('format',
3988
'Use the specified output format.',
3989
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
3990
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5209
3993
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5210
3994
no_patch=False, revision=None, remember=False, output=None,
5211
format=None, mail_to=None, message=None, body=None,
5212
strict=None, **kwargs):
5213
from bzrlib.send import send
5214
return send(submit_branch, revision, public_branch, remember,
5215
format, no_bundle, no_patch, output,
5216
kwargs.get('from', '.'), mail_to, message, body,
3995
format='4', mail_to=None, message=None, **kwargs):
3996
return self._run(submit_branch, revision, public_branch, remember,
3997
format, no_bundle, no_patch, output,
3998
kwargs.get('from', '.'), mail_to, message)
4000
def _run(self, submit_branch, revision, public_branch, remember, format,
4001
no_bundle, no_patch, output, from_, mail_to, message):
4002
from bzrlib.revision import NULL_REVISION
4004
outfile = StringIO()
4008
outfile = open(output, 'wb')
4010
branch = Branch.open_containing(from_)[0]
4011
# we may need to write data into branch's repository to calculate
4015
config = branch.get_config()
4017
mail_to = config.get_user_option('submit_to')
4019
raise errors.BzrCommandError('No mail-to address'
4021
mail_client = config.get_mail_client()
4022
if remember and submit_branch is None:
4023
raise errors.BzrCommandError(
4024
'--remember requires a branch to be specified.')
4025
stored_submit_branch = branch.get_submit_branch()
4026
remembered_submit_branch = False
4027
if submit_branch is None:
4028
submit_branch = stored_submit_branch
4029
remembered_submit_branch = True
4031
if stored_submit_branch is None or remember:
4032
branch.set_submit_branch(submit_branch)
4033
if submit_branch is None:
4034
submit_branch = branch.get_parent()
4035
remembered_submit_branch = True
4036
if submit_branch is None:
4037
raise errors.BzrCommandError('No submit branch known or'
4039
if remembered_submit_branch:
4040
note('Using saved location: %s', submit_branch)
4042
stored_public_branch = branch.get_public_branch()
4043
if public_branch is None:
4044
public_branch = stored_public_branch
4045
elif stored_public_branch is None or remember:
4046
branch.set_public_branch(public_branch)
4047
if no_bundle and public_branch is None:
4048
raise errors.BzrCommandError('No public branch specified or'
4050
base_revision_id = None
4052
if revision is not None:
4053
if len(revision) > 2:
4054
raise errors.BzrCommandError('bzr send takes '
4055
'at most two one revision identifiers')
4056
revision_id = revision[-1].in_history(branch).rev_id
4057
if len(revision) == 2:
4058
base_revision_id = revision[0].in_history(branch).rev_id
4059
if revision_id is None:
4060
revision_id = branch.last_revision()
4061
if revision_id == NULL_REVISION:
4062
raise errors.BzrCommandError('No revisions to submit.')
4064
directive = merge_directive.MergeDirective2.from_objects(
4065
branch.repository, revision_id, time.time(),
4066
osutils.local_time_offset(), submit_branch,
4067
public_branch=public_branch, include_patch=not no_patch,
4068
include_bundle=not no_bundle, message=message,
4069
base_revision_id=base_revision_id)
4070
elif format == '0.9':
4073
patch_type = 'bundle'
4075
raise errors.BzrCommandError('Format 0.9 does not'
4076
' permit bundle with no patch')
4082
directive = merge_directive.MergeDirective.from_objects(
4083
branch.repository, revision_id, time.time(),
4084
osutils.local_time_offset(), submit_branch,
4085
public_branch=public_branch, patch_type=patch_type,
4088
outfile.writelines(directive.to_lines())
4090
subject = '[MERGE] '
4091
if message is not None:
4094
revision = branch.repository.get_revision(revision_id)
4095
subject += revision.get_summary()
4096
mail_client.compose_merge_request(mail_to, subject,
5221
4104
class cmd_bundle_revisions(cmd_send):
5222
__doc__ = """Create a merge-directive for submitting changes.
4106
"""Create a merge-directive for submiting changes.
5224
4108
A merge directive provides many things needed for requesting merges:
5444
4296
If none of these is available, --bind-to must be specified.
5447
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5448
4299
takes_args = ['location?']
5450
RegistryOption.from_kwargs(
5452
title='Target type',
5453
help='The type to reconfigure the directory to.',
5454
value_switches=True, enum_switch=False,
5455
branch='Reconfigure to be an unbound branch with no working tree.',
5456
tree='Reconfigure to be an unbound branch with a working tree.',
5457
checkout='Reconfigure to be a bound branch with a working tree.',
5458
lightweight_checkout='Reconfigure to be a lightweight'
5459
' checkout (with no local history).',
5460
standalone='Reconfigure to be a standalone branch '
5461
'(i.e. stop using shared repository).',
5462
use_shared='Reconfigure to use a shared repository.',
5463
with_trees='Reconfigure repository to create '
5464
'working trees on branches by default.',
5465
with_no_trees='Reconfigure repository to not create '
5466
'working trees on branches by default.'
5468
Option('bind-to', help='Branch to bind checkout to.', type=str),
5470
help='Perform reconfiguration even if local changes'
5472
Option('stacked-on',
5473
help='Reconfigure a branch to be stacked on another branch.',
5477
help='Reconfigure a branch to be unstacked. This '
5478
'may require copying substantial data into it.',
4300
takes_options = [RegistryOption.from_kwargs('target_type',
4301
title='Target type',
4302
help='The type to reconfigure the directory to.',
4303
value_switches=True, enum_switch=False,
4304
branch='Reconfigure to a branch.',
4305
tree='Reconfigure to a tree.',
4306
checkout='Reconfigure to a checkout.'),
4307
Option('bind-to', help='Branch to bind checkout to.',
4310
help='Perform reconfiguration even if local changes'
5482
def run(self, location=None, target_type=None, bind_to=None, force=False,
4314
def run(self, location=None, target_type=None, bind_to=None, force=False):
5485
4315
directory = bzrdir.BzrDir.open(location)
5486
if stacked_on and unstacked:
5487
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5488
elif stacked_on is not None:
5489
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5491
reconfigure.ReconfigureUnstacked().apply(directory)
5492
# At the moment you can use --stacked-on and a different
5493
# reconfiguration shape at the same time; there seems no good reason
5495
4316
if target_type is None:
5496
if stacked_on or unstacked:
5499
raise errors.BzrCommandError('No target configuration '
4317
raise errors.BzrCommandError('No target configuration specified')
5501
4318
elif target_type == 'branch':
5502
4319
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5503
4320
elif target_type == 'tree':
5504
4321
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5505
4322
elif target_type == 'checkout':
5506
reconfiguration = reconfigure.Reconfigure.to_checkout(
5508
elif target_type == 'lightweight-checkout':
5509
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5511
elif target_type == 'use-shared':
5512
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5513
elif target_type == 'standalone':
5514
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5515
elif target_type == 'with-trees':
5516
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5518
elif target_type == 'with-no-trees':
5519
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
4323
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
5521
4325
reconfiguration.apply(force)
5524
4328
class cmd_switch(Command):
5525
__doc__ = """Set the branch of a checkout and update.
5527
For lightweight checkouts, this changes the branch being referenced.
5528
For heavyweight checkouts, this checks that there are no local commits
5529
versus the current bound branch, then it makes the local branch a mirror
5530
of the new location and binds to it.
5532
In both cases, the working tree is updated and uncommitted changes
5533
are merged. The user can commit or revert these as they desire.
5535
Pending merges need to be committed or reverted before using switch.
5537
The path to the branch to switch to can be specified relative to the parent
5538
directory of the current branch. For example, if you are currently in a
5539
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5542
Bound branches use the nickname of its master branch unless it is set
5543
locally, in which case switching will update the local nickname to be
5547
takes_args = ['to_location?']
5548
takes_options = ['directory',
5550
help='Switch even if local commits will be lost.'),
5552
Option('create-branch', short_name='b',
5553
help='Create the target branch from this one before'
5554
' switching to it.'),
5557
def run(self, to_location=None, force=False, create_branch=False,
5558
revision=None, directory=u'.'):
4329
"""Set the branch of a lightweight checkout and update."""
4331
takes_args = ['to_location']
4333
def run(self, to_location):
5559
4334
from bzrlib import switch
5560
tree_location = directory
5561
revision = _get_one_revision('switch', revision)
4335
to_branch = Branch.open(to_location)
5562
4337
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5563
if to_location is None:
5564
if revision is None:
5565
raise errors.BzrCommandError('You must supply either a'
5566
' revision or a location')
5567
to_location = tree_location
5569
branch = control_dir.open_branch()
5570
had_explicit_nick = branch.get_config().has_explicit_nickname()
5571
except errors.NotBranchError:
5573
had_explicit_nick = False
5576
raise errors.BzrCommandError('cannot create branch without'
5578
to_location = directory_service.directories.dereference(
5580
if '/' not in to_location and '\\' not in to_location:
5581
# This path is meant to be relative to the existing branch
5582
this_url = self._get_branch_location(control_dir)
5583
to_location = urlutils.join(this_url, '..', to_location)
5584
to_branch = branch.bzrdir.sprout(to_location,
5585
possible_transports=[branch.bzrdir.root_transport],
5586
source_branch=branch).open_branch()
5589
to_branch = Branch.open(to_location)
5590
except errors.NotBranchError:
5591
this_url = self._get_branch_location(control_dir)
5592
to_branch = Branch.open(
5593
urlutils.join(this_url, '..', to_location))
5594
if revision is not None:
5595
revision = revision.as_revision_id(to_branch)
5596
switch.switch(control_dir, to_branch, force, revision_id=revision)
5597
if had_explicit_nick:
5598
branch = control_dir.open_branch() #get the new branch!
5599
branch.nick = to_branch.nick
4338
switch.switch(control_dir, to_branch)
5600
4339
note('Switched to branch: %s',
5601
4340
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5603
def _get_branch_location(self, control_dir):
5604
"""Return location of branch for this control dir."""
5606
this_branch = control_dir.open_branch()
5607
# This may be a heavy checkout, where we want the master branch
5608
master_location = this_branch.get_bound_location()
5609
if master_location is not None:
5610
return master_location
5611
# If not, use a local sibling
5612
return this_branch.base
5613
except errors.NotBranchError:
5614
format = control_dir.find_branch_format()
5615
if getattr(format, 'get_reference', None) is not None:
5616
return format.get_reference(control_dir)
5618
return control_dir.root_transport.base
5621
class cmd_view(Command):
5622
__doc__ = """Manage filtered views.
5624
Views provide a mask over the tree so that users can focus on
5625
a subset of a tree when doing their work. After creating a view,
5626
commands that support a list of files - status, diff, commit, etc -
5627
effectively have that list of files implicitly given each time.
5628
An explicit list of files can still be given but those files
5629
must be within the current view.
5631
In most cases, a view has a short life-span: it is created to make
5632
a selected change and is deleted once that change is committed.
5633
At other times, you may wish to create one or more named views
5634
and switch between them.
5636
To disable the current view without deleting it, you can switch to
5637
the pseudo view called ``off``. This can be useful when you need
5638
to see the whole tree for an operation or two (e.g. merge) but
5639
want to switch back to your view after that.
5642
To define the current view::
5644
bzr view file1 dir1 ...
5646
To list the current view::
5650
To delete the current view::
5654
To disable the current view without deleting it::
5656
bzr view --switch off
5658
To define a named view and switch to it::
5660
bzr view --name view-name file1 dir1 ...
5662
To list a named view::
5664
bzr view --name view-name
5666
To delete a named view::
5668
bzr view --name view-name --delete
5670
To switch to a named view::
5672
bzr view --switch view-name
5674
To list all views defined::
5678
To delete all views::
5680
bzr view --delete --all
5684
takes_args = ['file*']
5687
help='Apply list or delete action to all views.',
5690
help='Delete the view.',
5693
help='Name of the view to define, list or delete.',
5697
help='Name of the view to switch to.',
5702
def run(self, file_list,
5708
tree, file_list = tree_files(file_list, apply_view=False)
5709
current_view, view_dict = tree.views.get_view_info()
5714
raise errors.BzrCommandError(
5715
"Both --delete and a file list specified")
5717
raise errors.BzrCommandError(
5718
"Both --delete and --switch specified")
5720
tree.views.set_view_info(None, {})
5721
self.outf.write("Deleted all views.\n")
5723
raise errors.BzrCommandError("No current view to delete")
5725
tree.views.delete_view(name)
5726
self.outf.write("Deleted '%s' view.\n" % name)
5729
raise errors.BzrCommandError(
5730
"Both --switch and a file list specified")
5732
raise errors.BzrCommandError(
5733
"Both --switch and --all specified")
5734
elif switch == 'off':
5735
if current_view is None:
5736
raise errors.BzrCommandError("No current view to disable")
5737
tree.views.set_view_info(None, view_dict)
5738
self.outf.write("Disabled '%s' view.\n" % (current_view))
5740
tree.views.set_view_info(switch, view_dict)
5741
view_str = views.view_display_str(tree.views.lookup_view())
5742
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5745
self.outf.write('Views defined:\n')
5746
for view in sorted(view_dict):
5747
if view == current_view:
5751
view_str = views.view_display_str(view_dict[view])
5752
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5754
self.outf.write('No views defined.\n')
5757
# No name given and no current view set
5760
raise errors.BzrCommandError(
5761
"Cannot change the 'off' pseudo view")
5762
tree.views.set_view(name, sorted(file_list))
5763
view_str = views.view_display_str(tree.views.lookup_view())
5764
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5768
# No name given and no current view set
5769
self.outf.write('No current view.\n')
5771
view_str = views.view_display_str(tree.views.lookup_view(name))
5772
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5775
class cmd_hooks(Command):
5776
__doc__ = """Show hooks."""
5781
for hook_key in sorted(hooks.known_hooks.keys()):
5782
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5783
self.outf.write("%s:\n" % type(some_hooks).__name__)
5784
for hook_name, hook_point in sorted(some_hooks.items()):
5785
self.outf.write(" %s:\n" % (hook_name,))
5786
found_hooks = list(hook_point)
5788
for hook in found_hooks:
5789
self.outf.write(" %s\n" %
5790
(some_hooks.get_hook_name(hook),))
5792
self.outf.write(" <no hooks installed>\n")
5795
class cmd_remove_branch(Command):
5796
__doc__ = """Remove a branch.
5798
This will remove the branch from the specified location but
5799
will keep any working tree or repository in place.
5803
Remove the branch at repo/trunk::
5805
bzr remove-branch repo/trunk
5809
takes_args = ["location?"]
5811
aliases = ["rmbranch"]
5813
def run(self, location=None):
5814
if location is None:
5816
branch = Branch.open_containing(location)[0]
5817
branch.bzrdir.destroy_branch()
5820
class cmd_shelve(Command):
5821
__doc__ = """Temporarily set aside some changes from the current tree.
5823
Shelve allows you to temporarily put changes you've made "on the shelf",
5824
ie. out of the way, until a later time when you can bring them back from
5825
the shelf with the 'unshelve' command. The changes are stored alongside
5826
your working tree, and so they aren't propagated along with your branch nor
5827
will they survive its deletion.
5829
If shelve --list is specified, previously-shelved changes are listed.
5831
Shelve is intended to help separate several sets of changes that have
5832
been inappropriately mingled. If you just want to get rid of all changes
5833
and you don't need to restore them later, use revert. If you want to
5834
shelve all text changes at once, use shelve --all.
5836
If filenames are specified, only the changes to those files will be
5837
shelved. Other files will be left untouched.
5839
If a revision is specified, changes since that revision will be shelved.
5841
You can put multiple items on the shelf, and by default, 'unshelve' will
5842
restore the most recently shelved changes.
5845
takes_args = ['file*']
5850
Option('all', help='Shelve all changes.'),
5852
RegistryOption('writer', 'Method to use for writing diffs.',
5853
bzrlib.option.diff_writer_registry,
5854
value_switches=True, enum_switch=False),
5856
Option('list', help='List shelved changes.'),
5858
help='Destroy removed changes instead of shelving them.'),
5860
_see_also = ['unshelve']
5862
def run(self, revision=None, all=False, file_list=None, message=None,
5863
writer=None, list=False, destroy=False, directory=u'.'):
5865
return self.run_for_list()
5866
from bzrlib.shelf_ui import Shelver
5868
writer = bzrlib.option.diff_writer_registry.get()
5870
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5871
file_list, message, destroy=destroy, directory=directory)
5876
except errors.UserAbort:
5879
def run_for_list(self):
5880
tree = WorkingTree.open_containing('.')[0]
5881
self.add_cleanup(tree.lock_read().unlock)
5882
manager = tree.get_shelf_manager()
5883
shelves = manager.active_shelves()
5884
if len(shelves) == 0:
5885
note('No shelved changes.')
5887
for shelf_id in reversed(shelves):
5888
message = manager.get_metadata(shelf_id).get('message')
5890
message = '<no message>'
5891
self.outf.write('%3d: %s\n' % (shelf_id, message))
5895
class cmd_unshelve(Command):
5896
__doc__ = """Restore shelved changes.
5898
By default, the most recently shelved changes are restored. However if you
5899
specify a shelf by id those changes will be restored instead. This works
5900
best when the changes don't depend on each other.
5903
takes_args = ['shelf_id?']
5906
RegistryOption.from_kwargs(
5907
'action', help="The action to perform.",
5908
enum_switch=False, value_switches=True,
5909
apply="Apply changes and remove from the shelf.",
5910
dry_run="Show changes, but do not apply or remove them.",
5911
preview="Instead of unshelving the changes, show the diff that "
5912
"would result from unshelving.",
5913
delete_only="Delete changes without applying them.",
5914
keep="Apply changes but don't delete them.",
5917
_see_also = ['shelve']
5919
def run(self, shelf_id=None, action='apply', directory=u'.'):
5920
from bzrlib.shelf_ui import Unshelver
5921
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5925
unshelver.tree.unlock()
5928
class cmd_clean_tree(Command):
5929
__doc__ = """Remove unwanted files from working tree.
5931
By default, only unknown files, not ignored files, are deleted. Versioned
5932
files are never deleted.
5934
Another class is 'detritus', which includes files emitted by bzr during
5935
normal operations and selftests. (The value of these files decreases with
5938
If no options are specified, unknown files are deleted. Otherwise, option
5939
flags are respected, and may be combined.
5941
To check what clean-tree will do, use --dry-run.
5943
takes_options = ['directory',
5944
Option('ignored', help='Delete all ignored files.'),
5945
Option('detritus', help='Delete conflict files, merge'
5946
' backups, and failed selftest dirs.'),
5948
help='Delete files unknown to bzr (default).'),
5949
Option('dry-run', help='Show files to delete instead of'
5951
Option('force', help='Do not prompt before deleting.')]
5952
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5953
force=False, directory=u'.'):
5954
from bzrlib.clean_tree import clean_tree
5955
if not (unknown or ignored or detritus):
5959
clean_tree(directory, unknown=unknown, ignored=ignored,
5960
detritus=detritus, dry_run=dry_run, no_prompt=force)
5963
class cmd_reference(Command):
5964
__doc__ = """list, view and set branch locations for nested trees.
5966
If no arguments are provided, lists the branch locations for nested trees.
5967
If one argument is provided, display the branch location for that tree.
5968
If two arguments are provided, set the branch location for that tree.
5973
takes_args = ['path?', 'location?']
5975
def run(self, path=None, location=None):
5977
if path is not None:
5979
tree, branch, relpath =(
5980
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
5981
if path is not None:
5984
tree = branch.basis_tree()
5986
info = branch._get_all_reference_info().iteritems()
5987
self._display_reference_info(tree, branch, info)
5989
file_id = tree.path2id(path)
5991
raise errors.NotVersionedError(path)
5992
if location is None:
5993
info = [(file_id, branch.get_reference_info(file_id))]
5994
self._display_reference_info(tree, branch, info)
5996
branch.set_reference_info(file_id, path, location)
5998
def _display_reference_info(self, tree, branch, info):
6000
for file_id, (path, location) in info:
6002
path = tree.id2path(file_id)
6003
except errors.NoSuchId:
6005
ref_list.append((path, location))
6006
for path, location in sorted(ref_list):
6007
self.outf.write('%s %s\n' % (path, location))
6010
def _register_lazy_builtins():
6011
# register lazy builtins from other modules; called at startup and should
6012
# be only called once.
6013
for (name, aliases, module_name) in [
6014
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6015
('cmd_dpush', [], 'bzrlib.foreign'),
6016
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6017
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6018
('cmd_conflicts', [], 'bzrlib.conflicts'),
6019
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6021
builtin_command_registry.register_lazy(name, aliases, module_name)
4343
def _create_prefix(cur_transport):
4344
needed = [cur_transport]
4345
# Recurse upwards until we can create a directory successfully
4347
new_transport = cur_transport.clone('..')
4348
if new_transport.base == cur_transport.base:
4349
raise errors.BzrCommandError(
4350
"Failed to create path prefix for %s."
4351
% cur_transport.base)
4353
new_transport.mkdir('.')
4354
except errors.NoSuchFile:
4355
needed.append(new_transport)
4356
cur_transport = new_transport
4359
# Now we only need to create child directories
4361
cur_transport = needed.pop()
4362
cur_transport.ensure_base()
4365
def _get_mergeable_helper(location):
4366
"""Get a merge directive or bundle if 'location' points to one.
4368
Try try to identify a bundle and returns its mergeable form. If it's not,
4369
we return the tried transport anyway so that it can reused to access the
4372
:param location: can point to a bundle or a branch.
4374
:return: mergeable, transport
4377
url = urlutils.normalize_url(location)
4378
url, filename = urlutils.split(url, exclude_trailing_slash=False)
4379
location_transport = transport.get_transport(url)
4382
# There may be redirections but we ignore the intermediate
4383
# and final transports used
4384
read = bundle.read_mergeable_from_transport
4385
mergeable, t = read(location_transport, filename)
4386
except errors.NotABundle:
4387
# Continue on considering this url a Branch but adjust the
4388
# location_transport
4389
location_transport = location_transport.clone(filename)
4390
return mergeable, location_transport
4393
# these get imported and then picked up by the scan for cmd_*
4394
# TODO: Some more consistent way to split command definitions across files;
4395
# we do need to load at least some information about them to know of
4396
# aliases. ideally we would avoid loading the implementation until the
4397
# details were needed.
4398
from bzrlib.cmd_version_info import cmd_version_info
4399
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4400
from bzrlib.bundle.commands import (
4403
from bzrlib.sign_my_commits import cmd_sign_my_commits
4404
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
4405
cmd_weave_plan_merge, cmd_weave_merge_text