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