96
226
Text has changed since the previous revision.
99
Nothing about this file has changed since the previous revision.
100
Only shown with --all.
229
File kind has been changed (e.g. from file to directory).
103
232
Not versioned and not matching an ignore pattern.
105
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
106
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,
108
245
If no arguments are specified, the status of the entire working
109
246
directory is shown. Otherwise, only the status of the specified
110
247
files or directories is reported. If a directory is given, status
111
248
is reported for everything inside that directory.
113
If a revision argument is given, the status is calculated against
114
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'.
117
263
# TODO: --no-recurse, --recurse options
119
265
takes_args = ['file*']
120
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.',
121
274
aliases = ['st', 'stat']
276
encoding_type = 'replace'
277
_see_also = ['diff', 'revert', 'status-flags']
124
def run(self, all=False, show_ids=False, file_list=None, revision=None):
125
b, file_list = branch_files(file_list)
127
from bzrlib.status import show_status
128
show_status(b, show_unchanged=all, show_ids=show_ids,
129
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)
132
304
class cmd_cat_revision(Command):
133
"""Write out metadata for a revision.
305
__doc__ = """Write out metadata for a revision.
135
307
The revision to print can either be specified by a specific
136
308
revision identifier, or you can use --revision.
140
312
takes_args = ['revision_id?']
141
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'))
144
def run(self, revision_id=None, revision=None):
326
def run(self, revision_id=None, revision=None, directory=u'.'):
146
327
if revision_id is not None and revision is not None:
147
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')
148
330
if revision_id is None and revision is None:
149
raise BzrCommandError('You must supply either --revision or a revision_id')
150
b = Branch.open_containing('.')[0]
151
if revision_id is not None:
152
sys.stdout.write(b.get_revision_xml_file(revision_id).read())
153
elif revision is not None:
156
raise BzrCommandError('You cannot specify a NULL revision.')
157
revno, rev_id = rev.in_history(b)
158
sys.stdout.write(b.get_revision_xml_file(rev_id).read())
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()
161
486
class cmd_revno(Command):
162
"""Show current revision number.
164
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.
493
takes_args = ['location?']
495
Option('tree', help='Show revno of working tree'),
167
print Branch.open_containing('.')[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')
170
520
class cmd_revision_info(Command):
171
"""Show revision number and revision id for a given revision identifier.
521
__doc__ = """Show revision number and revision id for a given revision identifier.
174
524
takes_args = ['revision_info*']
175
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'),
177
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)
180
546
if revision is not None:
181
revs.extend(revision)
547
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
182
548
if revision_info_list is not None:
183
for rev in revision_info_list:
184
revs.append(RevisionSpec(rev))
186
raise BzrCommandError('You must supply a revision identifier')
188
b = Branch.open_containing('.')[0]
191
revinfo = rev.in_history(b)
192
if revinfo.revno is None:
193
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())
195
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]))
198
577
class cmd_add(Command):
199
"""Add specified files or directories.
578
__doc__ = """Add specified files or directories.
201
580
In non-recursive mode, all the named items are added, regardless
202
581
of whether they were previously ignored. A warning is given if
216
595
Adding a file whose parent directory is not versioned will
217
596
implicitly add the parent, and so on up to the root. This means
218
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
219
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.
221
614
takes_args = ['file*']
222
takes_options = ['no-recurse', 'quiet']
224
def run(self, file_list, no_recurse=False, quiet=False):
225
from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
227
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()))
229
reporter = add_reporter_print
230
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"
233
662
class cmd_mkdir(Command):
234
"""Create a new versioned directory.
663
__doc__ = """Create a new versioned directory.
236
665
This is equivalent to creating the directory and then adding it.
238
668
takes_args = ['dir+']
669
encoding_type = 'replace'
240
671
def run(self, dir_list):
243
672
for d in dir_list:
245
b, dd = Branch.open_containing(d)
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)
250
684
class cmd_relpath(Command):
251
"""Show path of a file relative to root"""
685
__doc__ = """Show path of a file relative to root"""
252
687
takes_args = ['filename']
256
691
def run(self, filename):
257
branch, relpath = Branch.open_containing(filename)
692
# TODO: jam 20050106 Can relpath return a munged path if
693
# sys.stdout encoding cannot represent it?
694
tree, relpath = WorkingTree.open_containing(filename)
695
self.outf.write(relpath)
696
self.outf.write('\n')
261
699
class cmd_inventory(Command):
262
"""Show inventory of the current working copy or a revision.
700
__doc__ = """Show inventory of the current working copy or a revision.
264
702
It is possible to limit the output to a particular entry
265
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
267
takes_options = ['revision', 'show-ids', 'kind']
715
help='List entries of a particular kind: file, directory, symlink.',
718
takes_args = ['file*']
270
def run(self, revision=None, show_ids=False, kind=None):
721
def run(self, revision=None, show_ids=False, kind=None, file_list=None):
271
722
if kind and kind not in ['file', 'directory', 'symlink']:
272
raise BzrCommandError('invalid kind specified')
273
b = Branch.open_containing('.')[0]
275
inv = b.working_tree().read_working_inventory()
277
if len(revision) > 1:
278
raise BzrCommandError('bzr inventory --revision takes'
279
' exactly one revision identifier')
280
inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
282
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:
283
749
if kind and kind != entry.kind:
286
print '%-50s %s' % (path, entry.file_id)
752
self.outf.write('%-50s %s\n' % (path, entry.file_id))
291
class cmd_move(Command):
292
"""Move files to a different directory.
297
The destination must be a versioned directory in the same branch.
299
takes_args = ['source$', 'dest']
300
def run(self, source_list, dest):
301
b, source_list = branch_files(source_list)
303
# TODO: glob expansion on windows?
304
tree = WorkingTree(b.base, b)
305
b.move(source_list, tree.relpath(dest))
308
class cmd_rename(Command):
309
"""Change the name of an entry.
312
bzr rename frob.c frobber.c
313
bzr rename src/frob.c lib/frob.c
315
It is an error if the destination name exists.
317
See also the 'move' command, which moves files into a different
318
directory without changing their name.
320
# TODO: Some way to rename multiple files without invoking
321
# bzr for each one?"""
322
takes_args = ['from_name', 'to_name']
324
def run(self, from_name, to_name):
325
b, (from_name, to_name) = branch_files((from_name, to_name))
326
b.rename_one(from_name, to_name)
754
self.outf.write(path)
755
self.outf.write('\n')
329
758
class cmd_mv(Command):
330
"""Move or rename a file.
759
__doc__ = """Move or rename a file.
333
762
bzr mv OLDNAME NEWNAME
334
764
bzr mv SOURCE... DESTINATION
336
766
If the last argument is a versioned directory, all the other names
337
767
are moved into it. Otherwise, there must be exactly two arguments
338
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.
340
776
Files cannot be moved between branches.
342
779
takes_args = ['names*']
343
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:
344
795
if len(names_list) < 2:
345
raise BzrCommandError("missing file argument")
346
b, rel_names = branch_files(names_list)
348
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
349
834
# move into existing directory
350
for pair in b.move(rel_names[:-1], rel_names[-1]):
351
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))
353
842
if len(names_list) != 2:
354
raise BzrCommandError('to mv multiple files the destination '
355
'must be a versioned directory')
356
b.rename_one(rel_names[0], rel_names[1])
357
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))
360
894
class cmd_pull(Command):
361
"""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.
363
910
If there is no default location set, the first pull will set it. After
364
911
that, you can omit the location to use the default. To change the
365
default, use --remember.
367
This command only works on branches that have not diverged. Branches are
368
considered diverged if both branches have had commits without first
369
pulling from the other.
371
If branches have diverged, you can use 'bzr merge' to pull the text changes
372
from one into the other. Once one branch has merged, the other should
373
be able to pull it again.
375
If you want to forget your local changes and just update your branch to
376
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
378
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.")
379
935
takes_args = ['location?']
381
def run(self, location=None, remember=False, overwrite=False, verbose=False):
382
from bzrlib.merge import merge
383
from shutil import rmtree
386
br_to = Branch.open_containing('.')[0]
387
stored_loc = br_to.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()
388
971
if location is None:
389
972
if stored_loc is None:
390
raise BzrCommandError("No pull location known or specified.")
973
raise errors.BzrCommandError("No pull location known or"
392
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)
393
980
location = stored_loc
394
br_from = Branch.open(location)
396
old_rh = br_to.revision_history()
397
br_to.working_tree().pull(br_from, overwrite)
398
except DivergedBranches:
399
raise BzrCommandError("These branches have diverged."
401
if br_to.get_parent() is None or remember:
402
br_to.set_parent(location)
405
new_rh = br_to.revision_history()
408
from bzrlib.log import show_changed_revisions
409
show_changed_revisions(br_to, 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,
412
1022
class cmd_push(Command):
413
"""Push this branch into another branch.
415
The remote branch will not have its working tree populated because this
416
is both expensive, and may not be supported on the remote file system.
418
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'.
420
1042
If there is no default push location set, the first push will set it.
421
1043
After that, you can omit the location to use the default. To change the
422
default, use --remember.
424
This command only works on branches that have not diverged. Branches are
425
considered diverged if the branch being pushed to is not an older version
428
If branches have diverged, you can use 'bzr push --overwrite' to replace
429
the other branch completely.
431
If you want to ensure you have the different changes in the other branch,
432
do a merge (see bzr help merge) from the other branch, and commit that
433
before doing a 'push --overwrite'.
1044
default, use --remember. The value will only be saved if the remote
1045
location can be accessed.
435
takes_options = ['remember', 'overwrite',
436
Option('create-prefix',
437
help='Create the path leading up to the branch '
438
'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."),
439
1076
takes_args = ['location?']
1077
encoding_type = 'replace'
441
1079
def run(self, location=None, remember=False, overwrite=False,
442
create_prefix=False, verbose=False):
444
from shutil import rmtree
445
from bzrlib.transport import get_transport
447
br_from = Branch.open_containing('.')[0]
448
stored_loc = br_from.get_push_location()
1080
create_prefix=False, verbose=False, revision=None,
1081
use_existing_dir=False, directory=None, stacked_on=None,
1082
stacked=False, strict=None, no_tree=False):
1083
from bzrlib.push import _show_push_branch
1085
if directory is None:
1087
# Get the source branch
1089
_unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
1090
# Get the tip's revision_id
1091
revision = _get_one_revision('push', revision)
1092
if revision is not None:
1093
revision_id = revision.in_history(br_from).rev_id
1096
if tree is not None and revision_id is None:
1097
tree.check_changed_or_out_of_date(
1098
strict, 'push_strict',
1099
more_error='Use --no-strict to force the push.',
1100
more_warning='Uncommitted changes will not be pushed.')
1101
# Get the stacked_on branch, if any
1102
if stacked_on is not None:
1103
stacked_on = urlutils.normalize_url(stacked_on)
1105
parent_url = br_from.get_parent()
1107
parent = Branch.open(parent_url)
1108
stacked_on = parent.get_public_branch()
1110
# I considered excluding non-http url's here, thus forcing
1111
# 'public' branches only, but that only works for some
1112
# users, so it's best to just depend on the user spotting an
1113
# error by the feedback given to them. RBC 20080227.
1114
stacked_on = parent_url
1116
raise errors.BzrCommandError(
1117
"Could not determine branch to refer to.")
1119
# Get the destination location
449
1120
if location is None:
1121
stored_loc = br_from.get_push_location()
450
1122
if stored_loc is None:
451
raise BzrCommandError("No push location known or specified.")
1123
raise errors.BzrCommandError(
1124
"No push location known or specified.")
453
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)
454
1129
location = stored_loc
456
br_to = Branch.open(location)
457
except NotBranchError:
459
transport = get_transport(location).clone('..')
460
if not create_prefix:
462
transport.mkdir(transport.relpath(location))
464
raise BzrCommandError("Parent directory of %s "
465
"does not exist." % location)
467
current = transport.base
468
needed = [(transport, transport.relpath(location))]
471
transport, relpath = needed[-1]
472
transport.mkdir(relpath)
475
new_transport = transport.clone('..')
476
needed.append((new_transport,
477
new_transport.relpath(transport.base)))
478
if new_transport.base == transport.base:
479
raise BzrCommandError("Could not creeate "
483
br_to = Branch.initialize(location)
485
old_rh = br_to.revision_history()
486
br_to.pull(br_from, overwrite)
487
except DivergedBranches:
488
raise BzrCommandError("These branches have diverged."
489
" Try a merge then push with overwrite.")
490
if br_from.get_push_location() is None or remember:
491
br_from.set_push_location(location)
494
new_rh = br_to.revision_history()
497
from bzrlib.log import show_changed_revisions
498
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)
500
1137
class cmd_branch(Command):
501
"""Create a new copy of a branch.
1138
__doc__ = """Create a new branch that is a copy of an existing branch.
503
1140
If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
504
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
506
1147
To retrieve the branch as of a particular revision, supply the --revision
507
1148
parameter, as in "branch foo/bar -r 5".
509
--basis is to speed up branching from remote branches. When specified, it
510
copies all the file-contents, inventory and revision data from the basis
511
branch before copying anything from the remote branch.
1151
_see_also = ['checkout']
513
1152
takes_args = ['from_location', 'to_location?']
514
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."),
515
1176
aliases = ['get', 'clone']
517
def run(self, from_location, to_location=None, revision=None, basis=None):
518
from bzrlib.clone import copy_branch
520
from shutil import rmtree
523
elif len(revision) > 1:
524
raise BzrCommandError(
525
'bzr branch --revision takes exactly 1 revision value')
527
br_from = Branch.open(from_location)
529
if e.errno == errno.ENOENT:
530
raise BzrCommandError('Source location "%s" does not'
531
' exist.' % to_location)
536
if basis is not None:
537
basis_branch = Branch.open_containing(basis)[0]
540
if len(revision) == 1 and revision[0] is not None:
541
revision_id = revision[0].in_history(br_from)[1]
544
if to_location is None:
545
to_location = os.path.basename(from_location.rstrip("/\\"))
548
name = os.path.basename(to_location) + '\n'
550
os.mkdir(to_location)
552
if e.errno == errno.EEXIST:
553
raise BzrCommandError('Target directory "%s" already'
554
' exists.' % to_location)
555
if e.errno == errno.ENOENT:
556
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:
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:
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)):
561
copy_branch(br_from, to_location, revision_id, basis_branch)
562
except bzrlib.errors.NoSuchRevision:
564
msg = "The branch %s has no revision %s." % (from_location, revision[0])
565
raise BzrCommandError(msg)
566
except bzrlib.errors.UnlistableBranch:
568
msg = "The branch %s cannot be used as a --basis"
569
raise BzrCommandError(msg)
571
branch = Branch.open(to_location)
572
name = StringIO(name)
573
branch.put_controlfile('branch-name', name)
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)
578
1333
class cmd_renames(Command):
579
"""Show list of renamed files.
1334
__doc__ = """Show list of renamed files.
581
1336
# TODO: Option to show renames between two historical versions.
583
1338
# TODO: Only show renames under dir, rather than in the whole branch.
1339
_see_also = ['status']
584
1340
takes_args = ['dir?']
586
1342
@display_command
587
def run(self, dir='.'):
588
b = Branch.open_containing(dir)[0]
589
old_inv = b.basis_tree().inventory
590
new_inv = b.working_tree().read_working_inventory()
592
renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
1343
def run(self, dir=u'.'):
1344
tree = WorkingTree.open_containing(dir)[0]
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)
594
1359
for old_name, new_name in renames:
595
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'.")
598
1456
class cmd_info(Command):
599
"""Show statistical information about a branch."""
600
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'
602
1489
@display_command
603
def run(self, branch=None):
605
b = Branch.open_containing(branch)[0]
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)
609
1500
class cmd_remove(Command):
610
"""Make a file unversioned.
1501
__doc__ = """Remove files or directories.
612
This makes bzr stop tracking changes to a versioned file. It does
613
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.
615
takes_args = ['file+']
616
takes_options = ['verbose']
619
def run(self, file_list, verbose=False):
620
b, file_list = branch_files(file_list)
621
tree = b.working_tree()
622
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'))
625
1560
class cmd_file_id(Command):
626
"""Print file_id of a particular file or directory.
1561
__doc__ = """Print file_id of a particular file or directory.
628
1563
The file_id is assigned when the file is first added and remains the
629
1564
same through all revisions where the file exists, even when it is
630
1565
moved or renamed.
1569
_see_also = ['inventory', 'ls']
633
1570
takes_args = ['filename']
634
1572
@display_command
635
1573
def run(self, filename):
636
b, relpath = Branch.open_containing(filename)
637
i = b.working_tree().inventory.path2id(relpath)
639
raise BzrError("%r is not a versioned file" % filename)
1574
tree, relpath = WorkingTree.open_containing(filename)
1575
i = tree.path2id(relpath)
1577
raise errors.NotVersionedError(filename)
1579
self.outf.write(i + '\n')
644
1582
class cmd_file_path(Command):
645
"""Print path of file_ids to a file or directory.
1583
__doc__ = """Print path of file_ids to a file or directory.
647
1585
This prints one line for each directory down to the target,
648
starting at the branch root."""
1586
starting at the branch root.
650
1590
takes_args = ['filename']
651
1592
@display_command
652
1593
def run(self, filename):
653
b, relpath = Branch.open_containing(filename)
655
fid = inv.path2id(relpath)
657
raise BzrError("%r is not a versioned file" % filename)
658
for fip in inv.get_idpath(fid):
1594
tree, relpath = WorkingTree.open_containing(filename)
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)
662
1638
class cmd_revision_history(Command):
663
"""Display list of revision ids on this branch."""
1639
__doc__ = """Display the list of revision ids on a branch."""
1642
takes_args = ['location?']
665
1646
@display_command
667
for patchid in Branch.open_containing('.')[0].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')
671
1654
class cmd_ancestry(Command):
672
"""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?']
674
1662
@display_command
676
b = Branch.open_containing('.')[0]
677
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')
681
1679
class cmd_init(Command):
682
"""Make a directory into a versioned branch.
1680
__doc__ = """Make a directory into a versioned branch.
684
1682
Use this to create an empty branch, or before importing an
685
1683
existing project.
687
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::
692
bzr commit -m 'imported project'
1699
bzr commit -m "imported project"
1702
_see_also = ['init-repository', 'branch', 'checkout']
694
1703
takes_args = ['location?']
695
def run(self, location=None):
696
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')
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
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')
697
1842
if location is None:
700
# The path has to exist to initialize a
701
# branch inside of it.
702
# Just using os.mkdir, since I don't
703
# believe that we want to create a bunch of
704
# locations if the user supplies an extended path
705
if not os.path.exists(location):
707
Branch.initialize(location)
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)
710
1856
class cmd_diff(Command):
711
"""Show differences in working tree.
713
If files are listed, only the changes in those files are listed.
714
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".
1871
2 - unrepresentable changes
1876
Shows the difference in the working tree versus the last commit::
1880
Difference between the working tree and revision 1::
1884
Difference between revision 3 and revision 1::
1888
Difference between revision 3 and revision 1 for branch xxx::
1892
To see the changes introduced in revision X::
1896
Note that in the case of a merge, the -c option shows the changes
1897
compared to the left hand parent. To see the changes against
1898
another parent, use::
1900
bzr diff -r<chosen_parent>..X
1902
The changes introduced by revision 2 (equivalent to -r1..2)::
1906
Show just the differences for file NEWS::
1910
Show the differences in working tree xxx for file NEWS::
1914
Show the differences from branch xxx to this working tree:
1918
Show the differences between two branches for file NEWS::
1920
bzr diff --old xxx --new yyy NEWS
1922
Same as 'bzr diff' but prefix paths with old/ and new/::
1924
bzr diff --prefix old/:new/
1926
Show the differences using a custom diff program with options::
1928
bzr diff --using /usr/bin/diff --diff-options -wu
721
# TODO: Allow diff across branches.
722
# TODO: Option to use external diff command; could be GNU diff, wdiff,
723
# or a graphical diff.
725
# TODO: Python difflib is not exactly the same as unidiff; should
726
# either fix it up or prefer to use an external diff.
728
# TODO: If a directory is given, diff everything under that.
730
# TODO: Selected-file diff is inefficient and doesn't show you
733
# TODO: This probably handles non-Unix newlines poorly.
1930
_see_also = ['status']
735
1931
takes_args = ['file*']
736
takes_options = ['revision', 'diff-options']
1933
Option('diff-options', type=str,
1934
help='Pass these options to the external diff program.'),
1935
Option('prefix', type=str,
1937
help='Set prefixes added to old and new filenames, as '
1938
'two values separated by a colon. (eg "old/:new/").'),
1940
help='Branch/tree to compare from.',
1944
help='Branch/tree to compare to.',
1950
help='Use this command to compare files.',
1953
RegistryOption('format',
1954
help='Diff format to use.',
1955
lazy_registry=('bzrlib.diff', 'format_registry'),
1956
value_switches=False, title='Diff format'),
737
1958
aliases = ['di', 'dif']
1959
encoding_type = 'exact'
739
1961
@display_command
740
def run(self, revision=None, file_list=None, diff_options=None):
741
from bzrlib.diff import show_diff
743
b, file_list = inner_branch_files(file_list)
745
except FileInWrongBranch:
746
if len(file_list) != 2:
747
raise BzrCommandError("Files are in different branches")
1962
def run(self, revision=None, file_list=None, diff_options=None,
1963
prefix=None, old=None, new=None, using=None, format=None):
1964
from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
749
b, file1 = Branch.open_containing(file_list[0])
750
b2, file2 = Branch.open_containing(file_list[1])
751
if file1 != "" or file2 != "":
752
raise BzrCommandError("Files are in different branches")
754
if revision is not None:
756
raise BzrCommandError("Can't specify -r with two branches")
757
if len(revision) == 1:
758
return show_diff(b, revision[0], specific_files=file_list,
759
external_diff_options=diff_options)
760
elif len(revision) == 2:
761
return show_diff(b, revision[0], specific_files=file_list,
762
external_diff_options=diff_options,
763
revision2=revision[1])
765
raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1967
if (prefix is None) or (prefix == '0'):
1975
old_label, new_label = prefix.split(":")
767
return show_diff(b, None, specific_files=file_list,
768
external_diff_options=diff_options, b2=b2)
1977
raise errors.BzrCommandError(
1978
'--prefix expects two values separated by a colon'
1979
' (eg "old/:new/")')
1981
if revision and len(revision) > 2:
1982
raise errors.BzrCommandError('bzr diff --revision takes exactly'
1983
' one or two revision specifiers')
1985
if using is not None and format is not None:
1986
raise errors.BzrCommandError('--using and --format are mutually '
1989
(old_tree, new_tree,
1990
old_branch, new_branch,
1991
specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
1992
file_list, revision, old, new, self.add_cleanup, apply_view=True)
1993
# GNU diff on Windows uses ANSI encoding for filenames
1994
path_encoding = osutils.get_diff_header_encoding()
1995
return show_diff_trees(old_tree, new_tree, sys.stdout,
1996
specific_files=specific_files,
1997
external_diff_options=diff_options,
1998
old_label=old_label, new_label=new_label,
1999
extra_trees=extra_trees,
2000
path_encoding=path_encoding,
771
2005
class cmd_deleted(Command):
772
"""List files deleted in the working tree.
2006
__doc__ = """List files deleted in the working tree.
774
2008
# TODO: Show files deleted since a previous revision, or
775
2009
# between two revisions.
777
2011
# directories with readdir, rather than stating each one. Same
778
2012
# level of effort but possibly much less IO. (Or possibly not,
779
2013
# if the directories are very large...)
2014
_see_also = ['status', 'ls']
2015
takes_options = ['directory', 'show-ids']
780
2017
@display_command
781
def run(self, show_ids=False):
782
b = Branch.open_containing('.')[0]
784
new = b.working_tree()
2018
def run(self, show_ids=False, directory=u'.'):
2019
tree = WorkingTree.open_containing(directory)[0]
2020
self.add_cleanup(tree.lock_read().unlock)
2021
old = tree.basis_tree()
2022
self.add_cleanup(old.lock_read().unlock)
785
2023
for path, ie in old.inventory.iter_entries():
786
if not new.has_id(ie.file_id):
2024
if not tree.has_id(ie.file_id):
2025
self.outf.write(path)
788
print '%-50s %s' % (path, ie.file_id)
2027
self.outf.write(' ')
2028
self.outf.write(ie.file_id)
2029
self.outf.write('\n')
793
2032
class cmd_modified(Command):
794
"""List files modified in working tree."""
2033
__doc__ = """List files modified in working tree.
2037
_see_also = ['status', 'ls']
2038
takes_options = ['directory', 'null']
796
2040
@display_command
798
from bzrlib.delta import compare_trees
800
b = Branch.open_containing('.')[0]
801
td = compare_trees(b.basis_tree(), b.working_tree())
2041
def run(self, null=False, directory=u'.'):
2042
tree = WorkingTree.open_containing(directory)[0]
2043
td = tree.changes_from(tree.basis_tree())
803
2044
for path, id, kind, text_modified, meta_modified in td.modified:
2046
self.outf.write(path + '\0')
2048
self.outf.write(osutils.quotefn(path) + '\n')
808
2051
class cmd_added(Command):
809
"""List files added in working tree."""
2052
__doc__ = """List files added in working tree.
2056
_see_also = ['status', 'ls']
2057
takes_options = ['directory', 'null']
811
2059
@display_command
813
b = Branch.open_containing('.')[0]
814
wt = b.working_tree()
815
basis_inv = b.basis_tree().inventory
2060
def run(self, null=False, directory=u'.'):
2061
wt = WorkingTree.open_containing(directory)[0]
2062
self.add_cleanup(wt.lock_read().unlock)
2063
basis = wt.basis_tree()
2064
self.add_cleanup(basis.lock_read().unlock)
2065
basis_inv = basis.inventory
816
2066
inv = wt.inventory
817
2067
for file_id in inv:
818
2068
if file_id in basis_inv:
2070
if inv.is_root(file_id) and len(basis_inv) == 0:
820
2072
path = inv.id2path(file_id)
821
if not os.access(b.abspath(path), os.F_OK):
2073
if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
2076
self.outf.write(path + '\0')
2078
self.outf.write(osutils.quotefn(path) + '\n')
827
2081
class cmd_root(Command):
828
"""Show the tree root directory.
2082
__doc__ = """Show the tree root directory.
830
2084
The root is the nearest enclosing directory with a .bzr control
832
2087
takes_args = ['filename?']
833
2088
@display_command
834
2089
def run(self, filename=None):
835
2090
"""Print the branch root."""
836
b = Branch.open_containing(filename)[0]
2091
tree = WorkingTree.open_containing(filename)[0]
2092
self.outf.write(tree.basedir + '\n')
2095
def _parse_limit(limitstring):
2097
return int(limitstring)
2099
msg = "The limit argument must be an integer."
2100
raise errors.BzrCommandError(msg)
2103
def _parse_levels(s):
2107
msg = "The levels argument must be an integer."
2108
raise errors.BzrCommandError(msg)
840
2111
class cmd_log(Command):
841
"""Show log of this branch.
843
To request a range of logs, you can use the command -r begin..end
844
-r revision requests a specific revision, -r ..end or -r begin.. are
2112
__doc__ = """Show historical log for a branch or subset of a branch.
2114
log is bzr's default tool for exploring the history of a branch.
2115
The branch to use is taken from the first parameter. If no parameters
2116
are given, the branch containing the working directory is logged.
2117
Here are some simple examples::
2119
bzr log log the current branch
2120
bzr log foo.py log a file in its branch
2121
bzr log http://server/branch log a branch on a server
2123
The filtering, ordering and information shown for each revision can
2124
be controlled as explained below. By default, all revisions are
2125
shown sorted (topologically) so that newer revisions appear before
2126
older ones and descendants always appear before ancestors. If displayed,
2127
merged revisions are shown indented under the revision in which they
2132
The log format controls how information about each revision is
2133
displayed. The standard log formats are called ``long``, ``short``
2134
and ``line``. The default is long. See ``bzr help log-formats``
2135
for more details on log formats.
2137
The following options can be used to control what information is
2140
-l N display a maximum of N revisions
2141
-n N display N levels of revisions (0 for all, 1 for collapsed)
2142
-v display a status summary (delta) for each revision
2143
-p display a diff (patch) for each revision
2144
--show-ids display revision-ids (and file-ids), not just revnos
2146
Note that the default number of levels to display is a function of the
2147
log format. If the -n option is not used, the standard log formats show
2148
just the top level (mainline).
2150
Status summaries are shown using status flags like A, M, etc. To see
2151
the changes explained using words like ``added`` and ``modified``
2152
instead, use the -vv option.
2156
To display revisions from oldest to newest, use the --forward option.
2157
In most cases, using this option will have little impact on the total
2158
time taken to produce a log, though --forward does not incrementally
2159
display revisions like --reverse does when it can.
2161
:Revision filtering:
2163
The -r option can be used to specify what revision or range of revisions
2164
to filter against. The various forms are shown below::
2166
-rX display revision X
2167
-rX.. display revision X and later
2168
-r..Y display up to and including revision Y
2169
-rX..Y display from X to Y inclusive
2171
See ``bzr help revisionspec`` for details on how to specify X and Y.
2172
Some common examples are given below::
2174
-r-1 show just the tip
2175
-r-10.. show the last 10 mainline revisions
2176
-rsubmit:.. show what's new on this branch
2177
-rancestor:path.. show changes since the common ancestor of this
2178
branch and the one at location path
2179
-rdate:yesterday.. show changes since yesterday
2181
When logging a range of revisions using -rX..Y, log starts at
2182
revision Y and searches back in history through the primary
2183
("left-hand") parents until it finds X. When logging just the
2184
top level (using -n1), an error is reported if X is not found
2185
along the way. If multi-level logging is used (-n0), X may be
2186
a nested merge revision and the log will be truncated accordingly.
2190
If parameters are given and the first one is not a branch, the log
2191
will be filtered to show only those revisions that changed the
2192
nominated files or directories.
2194
Filenames are interpreted within their historical context. To log a
2195
deleted file, specify a revision range so that the file existed at
2196
the end or start of the range.
2198
Historical context is also important when interpreting pathnames of
2199
renamed files/directories. Consider the following example:
2201
* revision 1: add tutorial.txt
2202
* revision 2: modify tutorial.txt
2203
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2207
* ``bzr log guide.txt`` will log the file added in revision 1
2209
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2211
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2212
the original file in revision 2.
2214
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2215
was no file called guide.txt in revision 2.
2217
Renames are always followed by log. By design, there is no need to
2218
explicitly ask for this (and no way to stop logging a file back
2219
until it was last renamed).
2223
The --message option can be used for finding revisions that match a
2224
regular expression in a commit message.
2228
GUI tools and IDEs are often better at exploring history than command
2229
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2230
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2231
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2232
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2234
You may find it useful to add the aliases below to ``bazaar.conf``::
2238
top = log -l10 --line
2241
``bzr tip`` will then show the latest revision while ``bzr top``
2242
will show the last 10 mainline revisions. To see the details of a
2243
particular revision X, ``bzr show -rX``.
2245
If you are interested in looking deeper into a particular merge X,
2246
use ``bzr log -n0 -rX``.
2248
``bzr log -v`` on a branch with lots of history is currently
2249
very slow. A fix for this issue is currently under development.
2250
With or without that fix, it is recommended that a revision range
2251
be given when using the -v option.
2253
bzr has a generic full-text matching plugin, bzr-search, that can be
2254
used to find revisions matching user names, commit messages, etc.
2255
Among other features, this plugin can find all revisions containing
2256
a list of words but not others.
2258
When exploring non-mainline history on large projects with deep
2259
history, the performance of log can be greatly improved by installing
2260
the historycache plugin. This plugin buffers historical information
2261
trading disk space for faster speed.
848
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
850
takes_args = ['filename?']
851
takes_options = [Option('forward',
852
help='show from oldest to newest'),
853
'timezone', 'verbose',
854
'show-ids', 'revision',
855
Option('line', help='format with one line per revision'),
858
help='show revisions whose message matches this regexp',
860
Option('short', help='use moderately short format'),
2263
takes_args = ['file*']
2264
_see_also = ['log-formats', 'revisionspec']
2267
help='Show from oldest to newest.'),
2269
custom_help('verbose',
2270
help='Show files changed in each revision.'),
2274
type=bzrlib.option._parse_revision_str,
2276
help='Show just the specified revision.'
2277
' See also "help revisionspec".'),
2279
RegistryOption('authors',
2280
'What names to list as authors - first, all or committer.',
2282
lazy_registry=('bzrlib.log', 'author_list_registry'),
2286
help='Number of levels to display - 0 for all, 1 for flat.',
2288
type=_parse_levels),
2291
help='Show revisions whose message matches this '
2292
'regular expression.',
2296
help='Limit the output to the first N revisions.',
2301
help='Show changes made in each revision as a patch.'),
2302
Option('include-merges',
2303
help='Show merged revisions like --levels 0 does.'),
2304
Option('exclude-common-ancestry',
2305
help='Display only the revisions that are not part'
2306
' of both ancestries (require -rX..Y)'
2309
encoding_type = 'replace'
862
2311
@display_command
863
def run(self, filename=None, timezone='original',
2312
def run(self, file_list=None, timezone='original',
872
from bzrlib.log import log_formatter, show_log
874
assert message is None or isinstance(message, basestring), \
875
"invalid message argument %r" % message
2323
include_merges=False,
2325
exclude_common_ancestry=False,
2327
from bzrlib.log import (
2329
make_log_request_dict,
2330
_get_info_for_log_files,
876
2332
direction = (forward and 'forward') or 'reverse'
879
b, fp = Branch.open_containing(filename)
882
inv = b.working_tree().read_working_inventory()
883
except NoWorkingTree:
884
inv = b.get_inventory(b.last_revision())
885
file_id = inv.path2id(fp)
887
file_id = None # points to branch root
889
b, relpath = Branch.open_containing('.')
895
elif len(revision) == 1:
896
rev1 = rev2 = revision[0].in_history(b).revno
897
elif len(revision) == 2:
898
rev1 = revision[0].in_history(b).revno
899
rev2 = revision[1].in_history(b).revno
901
raise BzrCommandError('bzr log --revision takes one or two values.')
903
# By this point, the revision numbers are converted to the +ve
904
# form if they were supplied in the -ve form, so we can do
905
# this comparison in relative safety
907
(rev2, rev1) = (rev1, rev2)
909
mutter('encoding log as %r', bzrlib.user_encoding)
911
# use 'replace' so that we don't abort if trying to write out
912
# in e.g. the default C locale.
913
outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
2333
if (exclude_common_ancestry
2334
and (revision is None or len(revision) != 2)):
2335
raise errors.BzrCommandError(
2336
'--exclude-common-ancestry requires -r with two revisions')
2341
raise errors.BzrCommandError(
2342
'--levels and --include-merges are mutually exclusive')
2344
if change is not None:
2346
raise errors.RangeInChangeOption()
2347
if revision is not None:
2348
raise errors.BzrCommandError(
2349
'--revision and --change are mutually exclusive')
2354
filter_by_dir = False
2356
# find the file ids to log and check for directory filtering
2357
b, file_info_list, rev1, rev2 = _get_info_for_log_files(
2358
revision, file_list, self.add_cleanup)
2359
for relpath, file_id, kind in file_info_list:
2361
raise errors.BzrCommandError(
2362
"Path unknown at end or start of revision range: %s" %
2364
# If the relpath is the top of the tree, we log everything
2369
file_ids.append(file_id)
2370
filter_by_dir = filter_by_dir or (
2371
kind in ['directory', 'tree-reference'])
2374
# FIXME ? log the current subdir only RBC 20060203
2375
if revision is not None \
2376
and len(revision) > 0 and revision[0].get_branch():
2377
location = revision[0].get_branch()
2380
dir, relpath = bzrdir.BzrDir.open_containing(location)
2381
b = dir.open_branch()
2382
self.add_cleanup(b.lock_read().unlock)
2383
rev1, rev2 = _get_revision_range(revision, b, self.name())
2385
# Decide on the type of delta & diff filtering to use
2386
# TODO: add an --all-files option to make this configurable & consistent
2394
diff_type = 'partial'
2398
# Build the log formatter
2399
if log_format is None:
2400
log_format = log.log_formatter_registry.get_default(b)
2401
# Make a non-encoding output to include the diffs - bug 328007
2402
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2403
lf = log_format(show_ids=show_ids, to_file=self.outf,
2404
to_exact_file=unencoded_output,
2405
show_timezone=timezone,
2406
delta_format=get_verbosity_level(),
2408
show_advice=levels is None,
2409
author_list_handler=authors)
2411
# Choose the algorithm for doing the logging. It's annoying
2412
# having multiple code paths like this but necessary until
2413
# the underlying repository format is faster at generating
2414
# deltas or can provide everything we need from the indices.
2415
# The default algorithm - match-using-deltas - works for
2416
# multiple files and directories and is faster for small
2417
# amounts of history (200 revisions say). However, it's too
2418
# slow for logging a single file in a repository with deep
2419
# history, i.e. > 10K revisions. In the spirit of "do no
2420
# evil when adding features", we continue to use the
2421
# original algorithm - per-file-graph - for the "single
2422
# file that isn't a directory without showing a delta" case.
2423
partial_history = revision and b.repository._format.supports_chks
2424
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2425
or delta_type or partial_history)
2427
# Build the LogRequest and execute it
2428
if len(file_ids) == 0:
2430
rqst = make_log_request_dict(
2431
direction=direction, specific_fileids=file_ids,
2432
start_revision=rev1, end_revision=rev2, limit=limit,
2433
message_search=message, delta_type=delta_type,
2434
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2435
exclude_common_ancestry=exclude_common_ancestry,
2437
Logger(b, rqst).show(lf)
2440
def _get_revision_range(revisionspec_list, branch, command_name):
2441
"""Take the input of a revision option and turn it into a revision range.
2443
It returns RevisionInfo objects which can be used to obtain the rev_id's
2444
of the desired revisions. It does some user input validations.
2446
if revisionspec_list is None:
2449
elif len(revisionspec_list) == 1:
2450
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2451
elif len(revisionspec_list) == 2:
2452
start_spec = revisionspec_list[0]
2453
end_spec = revisionspec_list[1]
2454
if end_spec.get_branch() != start_spec.get_branch():
2455
# b is taken from revision[0].get_branch(), and
2456
# show_log will use its revision_history. Having
2457
# different branches will lead to weird behaviors.
2458
raise errors.BzrCommandError(
2459
"bzr %s doesn't accept two revisions in different"
2460
" branches." % command_name)
2461
if start_spec.spec is None:
2462
# Avoid loading all the history.
2463
rev1 = RevisionInfo(branch, None, None)
2465
rev1 = start_spec.in_history(branch)
2466
# Avoid loading all of history when we know a missing
2467
# end of range means the last revision ...
2468
if end_spec.spec is None:
2469
last_revno, last_revision_id = branch.last_revision_info()
2470
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2472
rev2 = end_spec.in_history(branch)
2474
raise errors.BzrCommandError(
2475
'bzr %s --revision takes one or two values.' % command_name)
2479
def _revision_range_to_revid_range(revision_range):
2482
if revision_range[0] is not None:
2483
rev_id1 = revision_range[0].rev_id
2484
if revision_range[1] is not None:
2485
rev_id2 = revision_range[1].rev_id
2486
return rev_id1, rev_id2
2488
def get_log_format(long=False, short=False, line=False, default='long'):
2489
log_format = default
915
2491
log_format = 'long'
920
lf = log_formatter(log_format,
923
show_timezone=timezone)
2493
log_format = 'short'
936
2499
class cmd_touching_revisions(Command):
937
"""Return revision-ids which affected a particular file.
939
A more user-friendly interface is "bzr log FILE"."""
2500
__doc__ = """Return revision-ids which affected a particular file.
2502
A more user-friendly interface is "bzr log FILE".
941
2506
takes_args = ["filename"]
942
2508
@display_command
943
2509
def run(self, filename):
944
b, relpath = Branch.open_containing(filename)[0]
945
inv = b.working_tree().read_working_inventory()
946
file_id = inv.path2id(relpath)
947
for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
948
print "%6d %s" % (revno, what)
2510
tree, relpath = WorkingTree.open_containing(filename)
2511
file_id = tree.path2id(relpath)
2513
self.add_cleanup(b.lock_read().unlock)
2514
touching_revs = log.find_touching_revisions(b, file_id)
2515
for revno, revision_id, what in touching_revs:
2516
self.outf.write("%6d %s\n" % (revno, what))
951
2519
class cmd_ls(Command):
952
"""List files in a tree.
2520
__doc__ = """List files in a tree.
954
# TODO: Take a revision or remote path and list that tree instead.
956
takes_options = ['verbose', 'revision',
957
Option('non-recursive',
958
help='don\'t recurse into sub-directories'),
960
help='Print all paths from the root of the branch.'),
961
Option('unknown', help='Print unknown files'),
962
Option('versioned', help='Print versioned files'),
963
Option('ignored', help='Print ignored files'),
965
Option('null', help='Null separate the files'),
2523
_see_also = ['status', 'cat']
2524
takes_args = ['path?']
2528
Option('recursive', short_name='R',
2529
help='Recurse into subdirectories.'),
2531
help='Print paths relative to the root of the branch.'),
2532
Option('unknown', short_name='u',
2533
help='Print unknown files.'),
2534
Option('versioned', help='Print versioned files.',
2536
Option('ignored', short_name='i',
2537
help='Print ignored files.'),
2538
Option('kind', short_name='k',
2539
help='List entries of a particular kind: file, directory, symlink.',
967
2545
@display_command
968
def run(self, revision=None, verbose=False,
969
non_recursive=False, from_root=False,
2546
def run(self, revision=None, verbose=False,
2547
recursive=False, from_root=False,
970
2548
unknown=False, versioned=False, ignored=False,
2549
null=False, kind=None, show_ids=False, path=None, directory=None):
2551
if kind and kind not in ('file', 'directory', 'symlink'):
2552
raise errors.BzrCommandError('invalid kind specified')
973
2554
if verbose and null:
974
raise BzrCommandError('Cannot set both --verbose and --null')
2555
raise errors.BzrCommandError('Cannot set both --verbose and --null')
975
2556
all = not (unknown or versioned or ignored)
977
2558
selection = {'I':ignored, '?':unknown, 'V':versioned}
979
b, relpath = Branch.open_containing('.')
2564
raise errors.BzrCommandError('cannot specify both --from-root'
2567
tree, branch, relpath = \
2568
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2570
# Calculate the prefix to use
985
tree = b.working_tree()
987
tree = b.revision_tree(revision[0].in_history(b).rev_id)
988
for fp, fc, kind, fid, entry in tree.list_files():
989
if fp.startswith(relpath):
990
fp = fp[len(relpath):]
991
if non_recursive and '/' in fp:
993
if not all and not selection[fc]:
996
kindch = entry.kind_character()
997
print '%-8s %s%s' % (fc, fp, kindch)
1000
sys.stdout.write('\0')
2574
prefix = relpath + '/'
2575
elif fs_path != '.' and not fs_path.endswith('/'):
2576
prefix = fs_path + '/'
2578
if revision is not None or tree is None:
2579
tree = _get_one_revision_tree('ls', revision, branch=branch)
2582
if isinstance(tree, WorkingTree) and tree.supports_views():
2583
view_files = tree.views.lookup_view()
2586
view_str = views.view_display_str(view_files)
2587
note("Ignoring files outside view. View is %s" % view_str)
2589
self.add_cleanup(tree.lock_read().unlock)
2590
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2591
from_dir=relpath, recursive=recursive):
2592
# Apply additional masking
2593
if not all and not selection[fc]:
2595
if kind is not None and fkind != kind:
2600
fullpath = osutils.pathjoin(relpath, fp)
2603
views.check_path_in_view(tree, fullpath)
2604
except errors.FileOutsideView:
2609
fp = osutils.pathjoin(prefix, fp)
2610
kindch = entry.kind_character()
2611
outstring = fp + kindch
2612
ui.ui_factory.clear_term()
2614
outstring = '%-8s %s' % (fc, outstring)
2615
if show_ids and fid is not None:
2616
outstring = "%-50s %s" % (outstring, fid)
2617
self.outf.write(outstring + '\n')
2619
self.outf.write(fp + '\0')
2622
self.outf.write(fid)
2623
self.outf.write('\0')
2631
self.outf.write('%-50s %s\n' % (outstring, my_id))
2633
self.outf.write(outstring + '\n')
1007
2636
class cmd_unknowns(Command):
1008
"""List unknown files."""
2637
__doc__ = """List unknown files.
2642
takes_options = ['directory']
1009
2644
@display_command
1011
from bzrlib.osutils import quotefn
1012
for f in Branch.open_containing('.')[0].unknowns():
2645
def run(self, directory=u'.'):
2646
for f in WorkingTree.open_containing(directory)[0].unknowns():
2647
self.outf.write(osutils.quotefn(f) + '\n')
1017
2650
class cmd_ignore(Command):
1018
"""Ignore a command or pattern.
2651
__doc__ = """Ignore specified files or patterns.
2653
See ``bzr help patterns`` for details on the syntax of patterns.
2655
If a .bzrignore file does not exist, the ignore command
2656
will create one and add the specified files or patterns to the newly
2657
created file. The ignore command will also automatically add the
2658
.bzrignore file to be versioned. Creating a .bzrignore file without
2659
the use of the ignore command will require an explicit add command.
1020
2661
To remove patterns from the ignore list, edit the .bzrignore file.
1022
If the pattern contains a slash, it is compared to the whole path
1023
from the branch root. Otherwise, it is compared to only the last
1024
component of the path. To match a file only in the root directory,
1027
Ignore patterns are case-insensitive on case-insensitive systems.
1029
Note: wildcards must be quoted from the shell on Unix.
1032
bzr ignore ./Makefile
1033
bzr ignore '*.class'
2662
After adding, editing or deleting that file either indirectly by
2663
using this command or directly by using an editor, be sure to commit
2666
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2667
the global ignore file can be found in the application data directory as
2668
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2669
Global ignores are not touched by this command. The global ignore file
2670
can be edited directly using an editor.
2672
Patterns prefixed with '!' are exceptions to ignore patterns and take
2673
precedence over regular ignores. Such exceptions are used to specify
2674
files that should be versioned which would otherwise be ignored.
2676
Patterns prefixed with '!!' act as regular ignore patterns, but have
2677
precedence over the '!' exception patterns.
2679
Note: ignore patterns containing shell wildcards must be quoted from
2683
Ignore the top level Makefile::
2685
bzr ignore ./Makefile
2687
Ignore .class files in all directories...::
2689
bzr ignore "*.class"
2691
...but do not ignore "special.class"::
2693
bzr ignore "!special.class"
2695
Ignore .o files under the lib directory::
2697
bzr ignore "lib/**/*.o"
2699
Ignore .o files under the lib directory::
2701
bzr ignore "RE:lib/.*\.o"
2703
Ignore everything but the "debian" toplevel directory::
2705
bzr ignore "RE:(?!debian/).*"
2707
Ignore everything except the "local" toplevel directory,
2708
but always ignore "*~" autosave files, even under local/::
2711
bzr ignore "!./local"
1035
# TODO: Complain if the filename is absolute
1036
takes_args = ['name_pattern']
1038
def run(self, name_pattern):
1039
from bzrlib.atomicfile import AtomicFile
1042
b, relpath = Branch.open_containing('.')
1043
ifn = b.abspath('.bzrignore')
1045
if os.path.exists(ifn):
1048
igns = f.read().decode('utf-8')
1054
# TODO: If the file already uses crlf-style termination, maybe
1055
# we should use that for the newly added lines?
1057
if igns and igns[-1] != '\n':
1059
igns += name_pattern + '\n'
1062
f = AtomicFile(ifn, 'wt')
1063
f.write(igns.encode('utf-8'))
1068
inv = b.working_tree().inventory
1069
if inv.path2id('.bzrignore'):
1070
mutter('.bzrignore is already versioned')
1072
mutter('need to make new .bzrignore file versioned')
1073
b.add(['.bzrignore'])
2715
_see_also = ['status', 'ignored', 'patterns']
2716
takes_args = ['name_pattern*']
2717
takes_options = ['directory',
2718
Option('default-rules',
2719
help='Display the default ignore rules that bzr uses.')
2722
def run(self, name_pattern_list=None, default_rules=None,
2724
from bzrlib import ignores
2725
if default_rules is not None:
2726
# dump the default rules and exit
2727
for pattern in ignores.USER_DEFAULTS:
2728
self.outf.write("%s\n" % pattern)
2730
if not name_pattern_list:
2731
raise errors.BzrCommandError("ignore requires at least one "
2732
"NAME_PATTERN or --default-rules.")
2733
name_pattern_list = [globbing.normalize_pattern(p)
2734
for p in name_pattern_list]
2736
for p in name_pattern_list:
2737
if not globbing.Globster.is_pattern_valid(p):
2738
bad_patterns += ('\n %s' % p)
2740
msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2741
ui.ui_factory.show_error(msg)
2742
raise errors.InvalidPattern('')
2743
for name_pattern in name_pattern_list:
2744
if (name_pattern[0] == '/' or
2745
(len(name_pattern) > 1 and name_pattern[1] == ':')):
2746
raise errors.BzrCommandError(
2747
"NAME_PATTERN should not be an absolute path")
2748
tree, relpath = WorkingTree.open_containing(directory)
2749
ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2750
ignored = globbing.Globster(name_pattern_list)
2752
self.add_cleanup(tree.lock_read().unlock)
2753
for entry in tree.list_files():
2757
if ignored.match(filename):
2758
matches.append(filename)
2759
if len(matches) > 0:
2760
self.outf.write("Warning: the following files are version controlled and"
2761
" match your ignore pattern:\n%s"
2762
"\nThese files will continue to be version controlled"
2763
" unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1077
2766
class cmd_ignored(Command):
1078
"""List ignored files and the patterns that matched them.
1080
See also: bzr ignore"""
2767
__doc__ = """List ignored files and the patterns that matched them.
2769
List all the ignored files and the ignore pattern that caused the file to
2772
Alternatively, to list just the files::
2777
encoding_type = 'replace'
2778
_see_also = ['ignore', 'ls']
2779
takes_options = ['directory']
1081
2781
@display_command
1083
tree = Branch.open_containing('.')[0].working_tree()
2782
def run(self, directory=u'.'):
2783
tree = WorkingTree.open_containing(directory)[0]
2784
self.add_cleanup(tree.lock_read().unlock)
1084
2785
for path, file_class, kind, file_id, entry in tree.list_files():
1085
2786
if file_class != 'I':
1087
2788
## XXX: Slightly inefficient since this was already calculated
1088
2789
pat = tree.is_ignored(path)
1089
print '%-50s %s' % (path, pat)
2790
self.outf.write('%-50s %s\n' % (path, pat))
1092
2793
class cmd_lookup_revision(Command):
1093
"""Lookup the revision-id from a revision-number
2794
__doc__ = """Lookup the revision-id from a revision-number
1096
2797
bzr lookup-revision 33
1099
2800
takes_args = ['revno']
2801
takes_options = ['directory']
1101
2803
@display_command
1102
def run(self, revno):
2804
def run(self, revno, directory=u'.'):
1104
2806
revno = int(revno)
1105
2807
except ValueError:
1106
raise BzrCommandError("not a valid revision-number: %r" % revno)
1108
print Branch.open_containing('.')[0].get_rev_id(revno)
2808
raise errors.BzrCommandError("not a valid revision-number: %r"
2810
revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
2811
self.outf.write("%s\n" % revid)
1111
2814
class cmd_export(Command):
1112
"""Export past revision to destination directory.
2815
__doc__ = """Export current or past revision to a destination directory or archive.
1114
2817
If no revision is specified this exports the last committed revision.
1200
3050
# XXX: verbose currently does nothing
3052
_see_also = ['add', 'bugs', 'hooks', 'uncommit']
1202
3053
takes_args = ['selected*']
1203
takes_options = ['message', 'verbose',
1205
help='commit even if nothing has changed'),
1206
Option('file', type=str,
1208
help='file containing commit message'),
1210
help="refuse to commit if there are unknown "
1211
"files in the working tree."),
3055
ListOption('exclude', type=str, short_name='x',
3056
help="Do not consider changes made to a given path."),
3057
Option('message', type=unicode,
3059
help="Description of the new revision."),
3062
help='Commit even if nothing has changed.'),
3063
Option('file', type=str,
3066
help='Take commit message from this file.'),
3068
help="Refuse to commit if there are unknown "
3069
"files in the working tree."),
3070
Option('commit-time', type=str,
3071
help="Manually set a commit time using commit date "
3072
"format, e.g. '2009-10-10 08:00:00 +0100'."),
3073
ListOption('fixes', type=str,
3074
help="Mark a bug as being fixed by this revision "
3075
"(see \"bzr help bugs\")."),
3076
ListOption('author', type=unicode,
3077
help="Set the author's name, if it's different "
3078
"from the committer."),
3080
help="Perform a local commit in a bound "
3081
"branch. Local commits are not pushed to "
3082
"the master branch until a normal commit "
3085
Option('show-diff', short_name='p',
3086
help='When no message is supplied, show the diff along'
3087
' with the status summary in the message editor.'),
1213
3089
aliases = ['ci', 'checkin']
1215
def run(self, message=None, file=None, verbose=True, selected_list=None,
1216
unchanged=False, strict=False):
1217
from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1219
from bzrlib.msgeditor import edit_commit_message
1220
from bzrlib.status import show_status
1221
from cStringIO import StringIO
1223
b, selected_list = branch_files(selected_list)
1224
if message is None and not file:
1225
catcher = StringIO()
1226
show_status(b, specific_files=selected_list,
1228
message = edit_commit_message(catcher.getvalue())
1231
raise BzrCommandError("please specify a commit message"
1232
" with either --message or --file")
1233
elif message and file:
1234
raise BzrCommandError("please specify either --message or --file")
1238
message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1241
raise BzrCommandError("empty commit message specified")
3091
def _iter_bug_fix_urls(self, fixes, branch):
3092
# Configure the properties for bug fixing attributes.
3093
for fixed_bug in fixes:
3094
tokens = fixed_bug.split(':')
3095
if len(tokens) != 2:
3096
raise errors.BzrCommandError(
3097
"Invalid bug %s. Must be in the form of 'tracker:id'. "
3098
"See \"bzr help bugs\" for more information on this "
3099
"feature.\nCommit refused." % fixed_bug)
3100
tag, bug_id = tokens
3102
yield bugtracker.get_bug_url(tag, branch, bug_id)
3103
except errors.UnknownBugTrackerAbbreviation:
3104
raise errors.BzrCommandError(
3105
'Unrecognized bug %s. Commit refused.' % fixed_bug)
3106
except errors.MalformedBugIdentifier, e:
3107
raise errors.BzrCommandError(
3108
"%s\nCommit refused." % (str(e),))
3110
def run(self, message=None, file=None, verbose=False, selected_list=None,
3111
unchanged=False, strict=False, local=False, fixes=None,
3112
author=None, show_diff=False, exclude=None, commit_time=None):
3113
from bzrlib.errors import (
3118
from bzrlib.msgeditor import (
3119
edit_commit_message_encoded,
3120
generate_commit_message_template,
3121
make_commit_message_template_encoded
3124
commit_stamp = offset = None
3125
if commit_time is not None:
3127
commit_stamp, offset = timestamp.parse_patch_date(commit_time)
3128
except ValueError, e:
3129
raise errors.BzrCommandError(
3130
"Could not parse --commit-time: " + str(e))
3132
# TODO: Need a blackbox test for invoking the external editor; may be
3133
# slightly problematic to run this cross-platform.
3135
# TODO: do more checks that the commit will succeed before
3136
# spending the user's valuable time typing a commit message.
3140
tree, selected_list = WorkingTree.open_containing_paths(selected_list)
3141
if selected_list == ['']:
3142
# workaround - commit of root of tree should be exactly the same
3143
# as just default commit in that tree, and succeed even though
3144
# selected-file merge commit is not done yet
3149
bug_property = bugtracker.encode_fixes_bug_urls(
3150
self._iter_bug_fix_urls(fixes, tree.branch))
3152
properties['bugs'] = bug_property
3154
if local and not tree.branch.get_bound_location():
3155
raise errors.LocalRequiresBoundBranch()
3157
if message is not None:
3159
file_exists = osutils.lexists(message)
3160
except UnicodeError:
3161
# The commit message contains unicode characters that can't be
3162
# represented in the filesystem encoding, so that can't be a
3167
'The commit message is a file name: "%(f)s".\n'
3168
'(use --file "%(f)s" to take commit message from that file)'
3170
ui.ui_factory.show_warning(warning_msg)
3172
message = message.replace('\r\n', '\n')
3173
message = message.replace('\r', '\n')
3175
raise errors.BzrCommandError(
3176
"please specify either --message or --file")
3178
def get_message(commit_obj):
3179
"""Callback to get commit message"""
3183
my_message = f.read().decode(osutils.get_user_encoding())
3186
elif message is not None:
3187
my_message = message
3189
# No message supplied: make one up.
3190
# text is the status of the tree
3191
text = make_commit_message_template_encoded(tree,
3192
selected_list, diff=show_diff,
3193
output_encoding=osutils.get_user_encoding())
3194
# start_message is the template generated from hooks
3195
# XXX: Warning - looks like hooks return unicode,
3196
# make_commit_message_template_encoded returns user encoding.
3197
# We probably want to be using edit_commit_message instead to
3199
start_message = generate_commit_message_template(commit_obj)
3200
my_message = edit_commit_message_encoded(text,
3201
start_message=start_message)
3202
if my_message is None:
3203
raise errors.BzrCommandError("please specify a commit"
3204
" message with either --message or --file")
3205
if my_message == "":
3206
raise errors.BzrCommandError("empty commit message specified")
3209
# The API permits a commit with a filter of [] to mean 'select nothing'
3210
# but the command line should not do that.
3211
if not selected_list:
3212
selected_list = None
1244
b.working_tree().commit(message, specific_files=selected_list,
1245
allow_pointless=unchanged, strict=strict)
3214
tree.commit(message_callback=get_message,
3215
specific_files=selected_list,
3216
allow_pointless=unchanged, strict=strict, local=local,
3217
reporter=None, verbose=verbose, revprops=properties,
3218
authors=author, timestamp=commit_stamp,
3220
exclude=tree.safe_relpath_files(exclude))
1246
3221
except PointlessCommit:
1247
# FIXME: This should really happen before the file is read in;
1248
# perhaps prepare the commit; get the message; then actually commit
1249
raise BzrCommandError("no changes to commit",
1250
["use --unchanged to commit anyhow"])
3222
raise errors.BzrCommandError("No changes to commit."
3223
" Use --unchanged to commit anyhow.")
1251
3224
except ConflictsInTree:
1252
raise BzrCommandError("Conflicts detected in working tree. "
1253
'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
3225
raise errors.BzrCommandError('Conflicts detected in working '
3226
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
1254
3228
except StrictCommitFailed:
1255
raise BzrCommandError("Commit refused because there are unknown "
1256
"files in the working tree.")
3229
raise errors.BzrCommandError("Commit refused because there are"
3230
" unknown files in the working tree.")
3231
except errors.BoundBranchOutOfDate, e:
3232
e.extra_help = ("\n"
3233
'To commit to master branch, run update and then commit.\n'
3234
'You can also pass --local to commit to continue working '
1259
3239
class cmd_check(Command):
1260
"""Validate consistency of branch history.
1262
This command checks various invariants about the branch storage to
1263
detect data corruption or bzr bugs.
3240
__doc__ = """Validate working tree structure, branch consistency and repository history.
3242
This command checks various invariants about branch and repository storage
3243
to detect data corruption or bzr bugs.
3245
The working tree and branch checks will only give output if a problem is
3246
detected. The output fields of the repository check are:
3249
This is just the number of revisions checked. It doesn't
3253
This is just the number of versionedfiles checked. It
3254
doesn't indicate a problem.
3256
unreferenced ancestors
3257
Texts that are ancestors of other texts, but
3258
are not properly referenced by the revision ancestry. This is a
3259
subtle problem that Bazaar can work around.
3262
This is the total number of unique file contents
3263
seen in the checked revisions. It does not indicate a problem.
3266
This is the total number of repeated texts seen
3267
in the checked revisions. Texts can be repeated when their file
3268
entries are modified, but the file contents are not. It does not
3271
If no restrictions are specified, all Bazaar data that is found at the given
3272
location will be checked.
3276
Check the tree and branch at 'foo'::
3278
bzr check --tree --branch foo
3280
Check only the repository at 'bar'::
3282
bzr check --repo bar
3284
Check everything at 'baz'::
1265
takes_args = ['dir?']
1266
takes_options = ['verbose']
1268
def run(self, dir='.', verbose=False):
1269
from bzrlib.check import check
1270
check(Branch.open_containing(dir)[0], verbose)
1273
class cmd_scan_cache(Command):
1276
from bzrlib.hashcache import HashCache
1282
print '%6d stats' % c.stat_count
1283
print '%6d in hashcache' % len(c._cache)
1284
print '%6d files removed from cache' % c.removed_count
1285
print '%6d hashes updated' % c.update_count
1286
print '%6d files changed too recently to cache' % c.danger_count
3289
_see_also = ['reconcile']
3290
takes_args = ['path?']
3291
takes_options = ['verbose',
3292
Option('branch', help="Check the branch related to the"
3293
" current directory."),
3294
Option('repo', help="Check the repository related to the"
3295
" current directory."),
3296
Option('tree', help="Check the working tree related to"
3297
" the current directory.")]
3299
def run(self, path=None, verbose=False, branch=False, repo=False,
3301
from bzrlib.check import check_dwim
3304
if not branch and not repo and not tree:
3305
branch = repo = tree = True
3306
check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
1293
3309
class cmd_upgrade(Command):
1294
"""Upgrade branch storage to current format.
3310
__doc__ = """Upgrade branch storage to current format.
1296
3312
The check command or bzr developers may sometimes advise you to run
1299
This version of this command upgrades from the full-text storage
1300
used by bzr 0.0.8 and earlier to the weave format (v5).
3313
this command. When the default format has changed you may also be warned
3314
during other operations to upgrade.
1302
takes_args = ['dir?']
1304
def run(self, dir='.'):
3317
_see_also = ['check']
3318
takes_args = ['url?']
3320
RegistryOption('format',
3321
help='Upgrade to a specific format. See "bzr help'
3322
' formats" for details.',
3323
lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3324
converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
3325
value_switches=True, title='Branch format'),
3328
def run(self, url='.', format=None):
1305
3329
from bzrlib.upgrade import upgrade
3330
upgrade(url, format)
1309
3333
class cmd_whoami(Command):
1310
"""Show bzr user id."""
1311
takes_options = ['email']
3334
__doc__ = """Show or set bzr user id.
3337
Show the email of the current user::
3341
Set the current user::
3343
bzr whoami "Frank Chu <fchu@example.com>"
3345
takes_options = [ 'directory',
3347
help='Display email address only.'),
3349
help='Set identity for the current branch instead of '
3352
takes_args = ['name?']
3353
encoding_type = 'replace'
1313
3355
@display_command
1314
def run(self, email=False):
3356
def run(self, email=False, branch=False, name=None, directory=None):
3358
if directory is None:
3359
# use branch if we're inside one; otherwise global config
3361
c = Branch.open_containing(u'.')[0].get_config()
3362
except errors.NotBranchError:
3363
c = _mod_config.GlobalConfig()
3365
c = Branch.open(directory).get_config()
3367
self.outf.write(c.user_email() + '\n')
3369
self.outf.write(c.username() + '\n')
3372
# display a warning if an email address isn't included in the given name.
1316
b = bzrlib.branch.Branch.open_containing('.')[0]
1317
config = bzrlib.config.BranchConfig(b)
1318
except NotBranchError:
1319
config = bzrlib.config.GlobalConfig()
1322
print config.user_email()
3374
_mod_config.extract_email_address(name)
3375
except errors.NoEmailInUsername, e:
3376
warning('"%s" does not seem to contain an email address. '
3377
'This is allowed, but not recommended.', name)
3379
# use global config unless --branch given
3381
if directory is None:
3382
c = Branch.open_containing(u'.')[0].get_config()
3384
c = Branch.open(directory).get_config()
1324
print config.username()
3386
c = _mod_config.GlobalConfig()
3387
c.set_user_option('email', name)
1326
3390
class cmd_nick(Command):
1328
Print or set the branch nickname.
1329
If unset, the tree root directory name is used as the nickname
1330
To print the current nickname, execute with no argument.
3391
__doc__ = """Print or set the branch nickname.
3393
If unset, the tree root directory name is used as the nickname.
3394
To print the current nickname, execute with no argument.
3396
Bound branches use the nickname of its master branch unless it is set
3400
_see_also = ['info']
1332
3401
takes_args = ['nickname?']
1333
def run(self, nickname=None):
1334
branch = Branch.open_containing('.')[0]
3402
takes_options = ['directory']
3403
def run(self, nickname=None, directory=u'.'):
3404
branch = Branch.open_containing(directory)[0]
1335
3405
if nickname is None:
1336
3406
self.printme(branch)
1340
3410
@display_command
1341
3411
def printme(self, branch):
3412
self.outf.write('%s\n' % branch.nick)
3415
class cmd_alias(Command):
3416
__doc__ = """Set/unset and display aliases.
3419
Show the current aliases::
3423
Show the alias specified for 'll'::
3427
Set an alias for 'll'::
3429
bzr alias ll="log --line -r-10..-1"
3431
To remove an alias for 'll'::
3433
bzr alias --remove ll
3436
takes_args = ['name?']
3438
Option('remove', help='Remove the alias.'),
3441
def run(self, name=None, remove=False):
3443
self.remove_alias(name)
3445
self.print_aliases()
3447
equal_pos = name.find('=')
3449
self.print_alias(name)
3451
self.set_alias(name[:equal_pos], name[equal_pos+1:])
3453
def remove_alias(self, alias_name):
3454
if alias_name is None:
3455
raise errors.BzrCommandError(
3456
'bzr alias --remove expects an alias to remove.')
3457
# If alias is not found, print something like:
3458
# unalias: foo: not found
3459
c = _mod_config.GlobalConfig()
3460
c.unset_alias(alias_name)
3463
def print_aliases(self):
3464
"""Print out the defined aliases in a similar format to bash."""
3465
aliases = _mod_config.GlobalConfig().get_aliases()
3466
for key, value in sorted(aliases.iteritems()):
3467
self.outf.write('bzr alias %s="%s"\n' % (key, value))
3470
def print_alias(self, alias_name):
3471
from bzrlib.commands import get_alias
3472
alias = get_alias(alias_name)
3474
self.outf.write("bzr alias: %s: not found\n" % alias_name)
3477
'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
3479
def set_alias(self, alias_name, alias_command):
3480
"""Save the alias in the global config."""
3481
c = _mod_config.GlobalConfig()
3482
c.set_alias(alias_name, alias_command)
1344
3485
class cmd_selftest(Command):
1345
"""Run internal test suite.
1347
This creates temporary test directories in the working directory,
1348
but not existing data is affected. These directories are deleted
1349
if the tests pass, or left behind to help in debugging if they
1350
fail and --keep-output is specified.
1352
If arguments are given, they are regular expressions that say
1353
which tests should run.
3486
__doc__ = """Run internal test suite.
3488
If arguments are given, they are regular expressions that say which tests
3489
should run. Tests matching any expression are run, and other tests are
3492
Alternatively if --first is given, matching tests are run first and then
3493
all other tests are run. This is useful if you have been working in a
3494
particular area, but want to make sure nothing else was broken.
3496
If --exclude is given, tests that match that regular expression are
3497
excluded, regardless of whether they match --first or not.
3499
To help catch accidential dependencies between tests, the --randomize
3500
option is useful. In most cases, the argument used is the word 'now'.
3501
Note that the seed used for the random number generator is displayed
3502
when this option is used. The seed can be explicitly passed as the
3503
argument to this option if required. This enables reproduction of the
3504
actual ordering used if and when an order sensitive problem is encountered.
3506
If --list-only is given, the tests that would be run are listed. This is
3507
useful when combined with --first, --exclude and/or --randomize to
3508
understand their impact. The test harness reports "Listed nn tests in ..."
3509
instead of "Ran nn tests in ..." when list mode is enabled.
3511
If the global option '--no-plugins' is given, plugins are not loaded
3512
before running the selftests. This has two effects: features provided or
3513
modified by plugins will not be tested, and tests provided by plugins will
3516
Tests that need working space on disk use a common temporary directory,
3517
typically inside $TMPDIR or /tmp.
3519
If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3520
into a pdb postmortem session.
3522
The --coverage=DIRNAME global option produces a report with covered code
3526
Run only tests relating to 'ignore'::
3530
Disable plugins and list tests as they're run::
3532
bzr --no-plugins selftest -v
1355
# TODO: --list should give a list of all available tests
3534
# NB: this is used from the class without creating an instance, which is
3535
# why it does not have a self parameter.
3536
def get_transport_type(typestring):
3537
"""Parse and return a transport specifier."""
3538
if typestring == "sftp":
3539
from bzrlib.tests import stub_sftp
3540
return stub_sftp.SFTPAbsoluteServer
3541
if typestring == "memory":
3542
from bzrlib.tests import test_server
3543
return memory.MemoryServer
3544
if typestring == "fakenfs":
3545
from bzrlib.tests import test_server
3546
return test_server.FakeNFSServer
3547
msg = "No known transport type %s. Supported types are: sftp\n" %\
3549
raise errors.BzrCommandError(msg)
1357
3552
takes_args = ['testspecs*']
1358
takes_options = ['verbose',
1359
Option('one', help='stop when one test fails'),
1360
Option('keep-output',
1361
help='keep output directories when tests fail')
3553
takes_options = ['verbose',
3555
help='Stop when one test fails.',
3559
help='Use a different transport by default '
3560
'throughout the test suite.',
3561
type=get_transport_type),
3563
help='Run the benchmarks rather than selftests.',
3565
Option('lsprof-timed',
3566
help='Generate lsprof output for benchmarked'
3567
' sections of code.'),
3568
Option('lsprof-tests',
3569
help='Generate lsprof output for each test.'),
3571
help='Run all tests, but run specified tests first.',
3575
help='List the tests instead of running them.'),
3576
RegistryOption('parallel',
3577
help="Run the test suite in parallel.",
3578
lazy_registry=('bzrlib.tests', 'parallel_registry'),
3579
value_switches=False,
3581
Option('randomize', type=str, argname="SEED",
3582
help='Randomize the order of tests using the given'
3583
' seed or "now" for the current time.'),
3584
Option('exclude', type=str, argname="PATTERN",
3586
help='Exclude tests that match this regular'
3589
help='Output test progress via subunit.'),
3590
Option('strict', help='Fail on missing dependencies or '
3592
Option('load-list', type=str, argname='TESTLISTFILE',
3593
help='Load a test id list from a text file.'),
3594
ListOption('debugflag', type=str, short_name='E',
3595
help='Turn on a selftest debug flag.'),
3596
ListOption('starting-with', type=str, argname='TESTID',
3597
param_name='starting_with', short_name='s',
3599
'Load only the tests starting with TESTID.'),
3601
encoding_type = 'replace'
3604
Command.__init__(self)
3605
self.additional_selftest_args = {}
1364
3607
def run(self, testspecs_list=None, verbose=False, one=False,
1367
from bzrlib.selftest import selftest
1368
# we don't want progress meters from the tests to go to the
1369
# real output; and we don't want log messages cluttering up
1371
save_ui = bzrlib.ui.ui_factory
1372
bzrlib.trace.info('running tests...')
3608
transport=None, benchmark=None,
3610
first=False, list_only=False,
3611
randomize=None, exclude=None, strict=False,
3612
load_list=None, debugflag=None, starting_with=None, subunit=False,
3613
parallel=None, lsprof_tests=False):
3614
from bzrlib import tests
3616
if testspecs_list is not None:
3617
pattern = '|'.join(testspecs_list)
3622
from bzrlib.tests import SubUnitBzrRunner
3624
raise errors.BzrCommandError("subunit not available. subunit "
3625
"needs to be installed to use --subunit.")
3626
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3627
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3628
# stdout, which would corrupt the subunit stream.
3629
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3630
# following code can be deleted when it's sufficiently deployed
3631
# -- vila/mgz 20100514
3632
if (sys.platform == "win32"
3633
and getattr(sys.stdout, 'fileno', None) is not None):
3635
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3637
self.additional_selftest_args.setdefault(
3638
'suite_decorators', []).append(parallel)
3640
raise errors.BzrCommandError(
3641
"--benchmark is no longer supported from bzr 2.2; "
3642
"use bzr-usertest instead")
3643
test_suite_factory = None
3644
selftest_kwargs = {"verbose": verbose,
3646
"stop_on_failure": one,
3647
"transport": transport,
3648
"test_suite_factory": test_suite_factory,
3649
"lsprof_timed": lsprof_timed,
3650
"lsprof_tests": lsprof_tests,
3651
"matching_tests_first": first,
3652
"list_only": list_only,
3653
"random_seed": randomize,
3654
"exclude_pattern": exclude,
3656
"load_list": load_list,
3657
"debug_flags": debugflag,
3658
"starting_with": starting_with
3660
selftest_kwargs.update(self.additional_selftest_args)
3662
# Make deprecation warnings visible, unless -Werror is set
3663
cleanup = symbol_versioning.activate_deprecation_warnings(
1374
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1375
if testspecs_list is not None:
1376
pattern = '|'.join(testspecs_list)
1379
result = selftest(verbose=verbose,
1381
stop_on_failure=one,
1382
keep_output=keep_output)
1384
bzrlib.trace.info('tests passed')
1386
bzrlib.trace.info('tests failed')
1387
return int(not result)
3666
result = tests.selftest(**selftest_kwargs)
1389
bzrlib.ui.ui_factory = save_ui
1393
print "bzr (bazaar-ng) %s" % bzrlib.__version__
1394
# is bzrlib itself in a branch?
1395
bzrrev = bzrlib.get_bzr_revision()
1397
print " (bzr checkout, revision %d {%s})" % bzrrev
1398
print bzrlib.__copyright__
1399
print "http://bazaar-ng.org/"
1401
print "bzr comes with ABSOLUTELY NO WARRANTY. bzr is free software, and"
1402
print "you may use, modify and redistribute it under the terms of the GNU"
1403
print "General Public License version 2 or later."
3669
return int(not result)
1406
3672
class cmd_version(Command):
1407
"""Show version of bzr."""
3673
__doc__ = """Show version of bzr."""
3675
encoding_type = 'replace'
3677
Option("short", help="Print just the version number."),
1408
3680
@display_command
3681
def run(self, short=False):
3682
from bzrlib.version import show_version
3684
self.outf.write(bzrlib.version_string + '\n')
3686
show_version(to_file=self.outf)
1412
3689
class cmd_rocks(Command):
1413
"""Statement of optimism."""
3690
__doc__ = """Statement of optimism."""
1415
3694
@display_command
1417
print "it sure does!"
3696
self.outf.write("It sure does!\n")
1420
3699
class cmd_find_merge_base(Command):
1421
"""Find and print a base revision for merging two branches.
3700
__doc__ = """Find and print a base revision for merging two branches."""
1423
3701
# TODO: Options to specify revisions on either side, as if
1424
3702
# merging only part of the history.
1425
3703
takes_args = ['branch', 'other']
1428
3706
@display_command
1429
3707
def run(self, branch, other):
1430
from bzrlib.revision import common_ancestor, MultipleRevisionSources
3708
from bzrlib.revision import ensure_null
1432
3710
branch1 = Branch.open_containing(branch)[0]
1433
3711
branch2 = Branch.open_containing(other)[0]
1435
history_1 = branch1.revision_history()
1436
history_2 = branch2.revision_history()
1438
last1 = branch1.last_revision()
1439
last2 = branch2.last_revision()
1441
source = MultipleRevisionSources(branch1, branch2)
1443
base_rev_id = common_ancestor(last1, last2, source)
1445
print 'merge base is revision %s' % base_rev_id
1449
if base_revno is None:
1450
raise bzrlib.errors.UnrelatedBranches()
1452
print ' r%-6d in %s' % (base_revno, branch)
1454
other_revno = branch2.revision_id_to_revno(base_revid)
1456
print ' r%-6d in %s' % (other_revno, other)
3712
self.add_cleanup(branch1.lock_read().unlock)
3713
self.add_cleanup(branch2.lock_read().unlock)
3714
last1 = ensure_null(branch1.last_revision())
3715
last2 = ensure_null(branch2.last_revision())
3717
graph = branch1.repository.get_graph(branch2.repository)
3718
base_rev_id = graph.find_unique_lca(last1, last2)
3720
self.outf.write('merge base is revision %s\n' % base_rev_id)
1460
3723
class cmd_merge(Command):
1461
"""Perform a three-way merge.
1463
The branch is the branch you will merge from. By default, it will
1464
merge the latest revision. If you specify a revision, that
1465
revision will be merged. If you specify two revisions, the first
1466
will be used as a BASE, and the second one as OTHER. Revision
1467
numbers are always relative to the specified branch.
1469
By default bzr will try to merge in all new work from the other
3724
__doc__ = """Perform a three-way merge.
3726
The source of the merge can be specified either in the form of a branch,
3727
or in the form of a path to a file containing a merge directive generated
3728
with bzr send. If neither is specified, the default is the upstream branch
3729
or the branch most recently merged using --remember.
3731
When merging a branch, by default the tip will be merged. To pick a different
3732
revision, pass --revision. If you specify two values, the first will be used as
3733
BASE and the second one as OTHER. Merging individual revisions, or a subset of
3734
available revisions, like this is commonly referred to as "cherrypicking".
3736
Revision numbers are always relative to the branch being merged.
3738
By default, bzr will try to merge in all new work from the other
1470
3739
branch, automatically determining an appropriate base. If this
1471
3740
fails, you may need to give an explicit base.
1475
To merge the latest revision from bzr.dev
1476
bzr merge ../bzr.dev
1478
To merge changes up to and including revision 82 from bzr.dev
1479
bzr merge -r 82 ../bzr.dev
1481
To merge the changes introduced by 82, without previous changes:
1482
bzr merge -r 81..82 ../bzr.dev
3742
Merge will do its best to combine the changes in two branches, but there
3743
are some kinds of problems only a human can fix. When it encounters those,
3744
it will mark a conflict. A conflict means that you need to fix something,
3745
before you should commit.
3747
Use bzr resolve when you have fixed a problem. See also bzr conflicts.
3749
If there is no default branch set, the first merge will set it. After
3750
that, you can omit the branch to use the default. To change the
3751
default, use --remember. The value will only be saved if the remote
3752
location can be accessed.
3754
The results of the merge are placed into the destination working
3755
directory, where they can be reviewed (with bzr diff), tested, and then
3756
committed to record the result of the merge.
1484
3758
merge refuses to run if there are any uncommitted changes, unless
3759
--force is given. The --force option can also be used to create a
3760
merge revision which has more than two parents.
3762
If one would like to merge changes from the working tree of the other
3763
branch without merging any committed revisions, the --uncommitted option
3766
To select only some changes to merge, use "merge -i", which will prompt
3767
you to apply each diff hunk and file change, similar to "shelve".
3770
To merge the latest revision from bzr.dev::
3772
bzr merge ../bzr.dev
3774
To merge changes up to and including revision 82 from bzr.dev::
3776
bzr merge -r 82 ../bzr.dev
3778
To merge the changes introduced by 82, without previous changes::
3780
bzr merge -r 81..82 ../bzr.dev
3782
To apply a merge directive contained in /tmp/merge::
3784
bzr merge /tmp/merge
3786
To create a merge revision with three parents from two branches
3787
feature1a and feature1b:
3789
bzr merge ../feature1a
3790
bzr merge ../feature1b --force
3791
bzr commit -m 'revision with three parents'
1487
takes_args = ['branch?']
1488
takes_options = ['revision', 'force', 'merge-type', 'reprocess',
1489
Option('show-base', help="Show base revision text in "
1492
def run(self, branch=None, revision=None, force=False, merge_type=None,
1493
show_base=False, reprocess=False):
1494
from bzrlib.merge import merge
1495
from bzrlib.merge_core import ApplyMerge3
3794
encoding_type = 'exact'
3795
_see_also = ['update', 'remerge', 'status-flags', 'send']
3796
takes_args = ['location?']
3801
help='Merge even if the destination tree has uncommitted changes.'),
3805
Option('show-base', help="Show base revision text in "
3807
Option('uncommitted', help='Apply uncommitted changes'
3808
' from a working copy, instead of branch changes.'),
3809
Option('pull', help='If the destination is already'
3810
' completely merged into the source, pull from the'
3811
' source rather than merging. When this happens,'
3812
' you do not need to commit the result.'),
3813
custom_help('directory',
3814
help='Branch to merge into, '
3815
'rather than the one containing the working directory.'),
3816
Option('preview', help='Instead of merging, show a diff of the'
3818
Option('interactive', help='Select changes interactively.',
3822
def run(self, location=None, revision=None, force=False,
3823
merge_type=None, show_base=False, reprocess=None, remember=False,
3824
uncommitted=False, pull=False,
1496
3829
if merge_type is None:
1497
merge_type = ApplyMerge3
1499
branch = Branch.open_containing('.')[0].get_parent()
1501
raise BzrCommandError("No merge location known or specified.")
1503
print "Using saved location: %s" % branch
1504
if revision is None or len(revision) < 1:
1506
other = [branch, -1]
1508
if len(revision) == 1:
1510
other_branch = Branch.open_containing(branch)[0]
1511
revno = revision[0].in_history(other_branch).revno
1512
other = [branch, revno]
1514
assert len(revision) == 2
1515
if None in revision:
1516
raise BzrCommandError(
1517
"Merge doesn't permit that revision specifier.")
1518
b = Branch.open_containing(branch)[0]
3830
merge_type = _mod_merge.Merge3Merger
1520
base = [branch, revision[0].in_history(b).revno]
1521
other = [branch, revision[1].in_history(b).revno]
3832
if directory is None: directory = u'.'
3833
possible_transports = []
3835
allow_pending = True
3836
verified = 'inapplicable'
3837
tree = WorkingTree.open_containing(directory)[0]
1524
conflict_count = merge(other, base, check_clean=(not force),
1525
merge_type=merge_type, reprocess=reprocess,
1526
show_base=show_base)
1527
if conflict_count != 0:
3840
basis_tree = tree.revision_tree(tree.last_revision())
3841
except errors.NoSuchRevision:
3842
basis_tree = tree.basis_tree()
3844
# die as quickly as possible if there are uncommitted changes
3846
if tree.has_changes():
3847
raise errors.UncommittedChanges(tree)
3849
view_info = _get_view_info_for_change_reporter(tree)
3850
change_reporter = delta._ChangeReporter(
3851
unversioned_filter=tree.is_ignored, view_info=view_info)
3852
pb = ui.ui_factory.nested_progress_bar()
3853
self.add_cleanup(pb.finished)
3854
self.add_cleanup(tree.lock_write().unlock)
3855
if location is not None:
3857
mergeable = bundle.read_mergeable_from_url(location,
3858
possible_transports=possible_transports)
3859
except errors.NotABundle:
3863
raise errors.BzrCommandError('Cannot use --uncommitted'
3864
' with bundles or merge directives.')
3866
if revision is not None:
3867
raise errors.BzrCommandError(
3868
'Cannot use -r with merge directives or bundles')
3869
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3872
if merger is None and uncommitted:
3873
if revision is not None and len(revision) > 0:
3874
raise errors.BzrCommandError('Cannot use --uncommitted and'
3875
' --revision at the same time.')
3876
merger = self.get_merger_from_uncommitted(tree, location, None)
3877
allow_pending = False
3880
merger, allow_pending = self._get_merger_from_branch(tree,
3881
location, revision, remember, possible_transports, None)
3883
merger.merge_type = merge_type
3884
merger.reprocess = reprocess
3885
merger.show_base = show_base
3886
self.sanity_check_merger(merger)
3887
if (merger.base_rev_id == merger.other_rev_id and
3888
merger.other_rev_id is not None):
3889
note('Nothing to do.')
3892
if merger.interesting_files is not None:
3893
raise errors.BzrCommandError('Cannot pull individual files')
3894
if (merger.base_rev_id == tree.last_revision()):
3895
result = tree.pull(merger.other_branch, False,
3896
merger.other_rev_id)
3897
result.report(self.outf)
1531
except bzrlib.errors.AmbiguousBase, e:
1532
m = ("sorry, bzr can't determine the right merge base yet\n"
1533
"candidates are:\n "
1534
+ "\n ".join(e.bases)
1536
"please specify an explicit base with -r,\n"
1537
"and (if you want) report this to the bzr developers\n")
3899
if merger.this_basis is None:
3900
raise errors.BzrCommandError(
3901
"This branch has no commits."
3902
" (perhaps you would prefer 'bzr pull')")
3904
return self._do_preview(merger)
3906
return self._do_interactive(merger)
3908
return self._do_merge(merger, change_reporter, allow_pending,
3911
def _get_preview(self, merger):
3912
tree_merger = merger.make_merger()
3913
tt = tree_merger.make_preview_transform()
3914
self.add_cleanup(tt.finalize)
3915
result_tree = tt.get_preview_tree()
3918
def _do_preview(self, merger):
3919
from bzrlib.diff import show_diff_trees
3920
result_tree = self._get_preview(merger)
3921
path_encoding = osutils.get_diff_header_encoding()
3922
show_diff_trees(merger.this_tree, result_tree, self.outf,
3923
old_label='', new_label='',
3924
path_encoding=path_encoding)
3926
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3927
merger.change_reporter = change_reporter
3928
conflict_count = merger.do_merge()
3930
merger.set_pending()
3931
if verified == 'failed':
3932
warning('Preview patch does not match changes')
3933
if conflict_count != 0:
3938
def _do_interactive(self, merger):
3939
"""Perform an interactive merge.
3941
This works by generating a preview tree of the merge, then using
3942
Shelver to selectively remove the differences between the working tree
3943
and the preview tree.
3945
from bzrlib import shelf_ui
3946
result_tree = self._get_preview(merger)
3947
writer = bzrlib.option.diff_writer_registry.get()
3948
shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
3949
reporter=shelf_ui.ApplyReporter(),
3950
diff_writer=writer(sys.stdout))
3956
def sanity_check_merger(self, merger):
3957
if (merger.show_base and
3958
not merger.merge_type is _mod_merge.Merge3Merger):
3959
raise errors.BzrCommandError("Show-base is not supported for this"
3960
" merge type. %s" % merger.merge_type)
3961
if merger.reprocess is None:
3962
if merger.show_base:
3963
merger.reprocess = False
3965
# Use reprocess if the merger supports it
3966
merger.reprocess = merger.merge_type.supports_reprocess
3967
if merger.reprocess and not merger.merge_type.supports_reprocess:
3968
raise errors.BzrCommandError("Conflict reduction is not supported"
3969
" for merge type %s." %
3971
if merger.reprocess and merger.show_base:
3972
raise errors.BzrCommandError("Cannot do conflict reduction and"
3975
def _get_merger_from_branch(self, tree, location, revision, remember,
3976
possible_transports, pb):
3977
"""Produce a merger from a location, assuming it refers to a branch."""
3978
from bzrlib.tag import _merge_tags_if_possible
3979
# find the branch locations
3980
other_loc, user_location = self._select_branch_location(tree, location,
3982
if revision is not None and len(revision) == 2:
3983
base_loc, _unused = self._select_branch_location(tree,
3984
location, revision, 0)
3986
base_loc = other_loc
3988
other_branch, other_path = Branch.open_containing(other_loc,
3989
possible_transports)
3990
if base_loc == other_loc:
3991
base_branch = other_branch
3993
base_branch, base_path = Branch.open_containing(base_loc,
3994
possible_transports)
3995
# Find the revision ids
3996
other_revision_id = None
3997
base_revision_id = None
3998
if revision is not None:
3999
if len(revision) >= 1:
4000
other_revision_id = revision[-1].as_revision_id(other_branch)
4001
if len(revision) == 2:
4002
base_revision_id = revision[0].as_revision_id(base_branch)
4003
if other_revision_id is None:
4004
other_revision_id = _mod_revision.ensure_null(
4005
other_branch.last_revision())
4006
# Remember where we merge from
4007
if ((remember or tree.branch.get_submit_branch() is None) and
4008
user_location is not None):
4009
tree.branch.set_submit_branch(other_branch.base)
4010
_merge_tags_if_possible(other_branch, tree.branch)
4011
merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4012
other_revision_id, base_revision_id, other_branch, base_branch)
4013
if other_path != '':
4014
allow_pending = False
4015
merger.interesting_files = [other_path]
4017
allow_pending = True
4018
return merger, allow_pending
4020
def get_merger_from_uncommitted(self, tree, location, pb):
4021
"""Get a merger for uncommitted changes.
4023
:param tree: The tree the merger should apply to.
4024
:param location: The location containing uncommitted changes.
4025
:param pb: The progress bar to use for showing progress.
4027
location = self._select_branch_location(tree, location)[0]
4028
other_tree, other_path = WorkingTree.open_containing(location)
4029
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
4030
if other_path != '':
4031
merger.interesting_files = [other_path]
4034
def _select_branch_location(self, tree, user_location, revision=None,
4036
"""Select a branch location, according to possible inputs.
4038
If provided, branches from ``revision`` are preferred. (Both
4039
``revision`` and ``index`` must be supplied.)
4041
Otherwise, the ``location`` parameter is used. If it is None, then the
4042
``submit`` or ``parent`` location is used, and a note is printed.
4044
:param tree: The working tree to select a branch for merging into
4045
:param location: The location entered by the user
4046
:param revision: The revision parameter to the command
4047
:param index: The index to use for the revision parameter. Negative
4048
indices are permitted.
4049
:return: (selected_location, user_location). The default location
4050
will be the user-entered location.
4052
if (revision is not None and index is not None
4053
and revision[index] is not None):
4054
branch = revision[index].get_branch()
4055
if branch is not None:
4056
return branch, branch
4057
if user_location is None:
4058
location = self._get_remembered(tree, 'Merging from')
4060
location = user_location
4061
return location, user_location
4063
def _get_remembered(self, tree, verb_string):
4064
"""Use tree.branch's parent if none was supplied.
4066
Report if the remembered location was used.
4068
stored_location = tree.branch.get_submit_branch()
4069
stored_location_type = "submit"
4070
if stored_location is None:
4071
stored_location = tree.branch.get_parent()
4072
stored_location_type = "parent"
4073
mutter("%s", stored_location)
4074
if stored_location is None:
4075
raise errors.BzrCommandError("No location specified or remembered")
4076
display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
4077
note(u"%s remembered %s location %s", verb_string,
4078
stored_location_type, display_url)
4079
return stored_location
1541
4082
class cmd_remerge(Command):
4083
__doc__ = """Redo a merge.
4085
Use this if you want to try a different merge technique while resolving
4086
conflicts. Some merge techniques are better than others, and remerge
4087
lets you try different ones on different files.
4089
The options for remerge have the same meaning and defaults as the ones for
4090
merge. The difference is that remerge can (only) be run when there is a
4091
pending merge, and it lets you specify particular files.
4094
Re-do the merge of all conflicted files, and show the base text in
4095
conflict regions, in addition to the usual THIS and OTHER texts::
4097
bzr remerge --show-base
4099
Re-do the merge of "foobar", using the weave merge algorithm, with
4100
additional processing to reduce the size of conflict regions::
4102
bzr remerge --merge-type weave --reprocess foobar
1544
4104
takes_args = ['file*']
1545
takes_options = ['merge-type', 'reprocess',
1546
Option('show-base', help="Show base revision text in "
4109
help="Show base revision text in conflicts."),
1549
4112
def run(self, file_list=None, merge_type=None, show_base=False,
1550
4113
reprocess=False):
1551
from bzrlib.merge import merge_inner, transform_tree
1552
from bzrlib.merge_core import ApplyMerge3
4114
from bzrlib.conflicts import restore
1553
4115
if merge_type is None:
1554
merge_type = ApplyMerge3
1555
b, file_list = branch_files(file_list)
4116
merge_type = _mod_merge.Merge3Merger
4117
tree, file_list = WorkingTree.open_containing_paths(file_list)
4118
self.add_cleanup(tree.lock_write().unlock)
4119
parents = tree.get_parent_ids()
4120
if len(parents) != 2:
4121
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4122
" merges. Not cherrypicking or"
4124
repository = tree.branch.repository
4125
interesting_ids = None
4127
conflicts = tree.conflicts()
4128
if file_list is not None:
4129
interesting_ids = set()
4130
for filename in file_list:
4131
file_id = tree.path2id(filename)
4133
raise errors.NotVersionedError(filename)
4134
interesting_ids.add(file_id)
4135
if tree.kind(file_id) != "directory":
4138
for name, ie in tree.inventory.iter_entries(file_id):
4139
interesting_ids.add(ie.file_id)
4140
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4142
# Remerge only supports resolving contents conflicts
4143
allowed_conflicts = ('text conflict', 'contents conflict')
4144
restore_files = [c.path for c in conflicts
4145
if c.typestring in allowed_conflicts]
4146
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4147
tree.set_conflicts(ConflictList(new_conflicts))
4148
if file_list is not None:
4149
restore_files = file_list
4150
for filename in restore_files:
4152
restore(tree.abspath(filename))
4153
except errors.NotConflicted:
4155
# Disable pending merges, because the file texts we are remerging
4156
# have not had those merges performed. If we use the wrong parents
4157
# list, we imply that the working tree text has seen and rejected
4158
# all the changes from the other tree, when in fact those changes
4159
# have not yet been seen.
4160
tree.set_parent_ids(parents[:1])
1558
pending_merges = b.working_tree().pending_merges()
1559
if len(pending_merges) != 1:
1560
raise BzrCommandError("Sorry, remerge only works after normal"
1561
+ " merges. Not cherrypicking or"
1563
this_tree = b.working_tree()
1564
base_revision = common_ancestor(b.last_revision(),
1565
pending_merges[0], b)
1566
base_tree = b.revision_tree(base_revision)
1567
other_tree = b.revision_tree(pending_merges[0])
1568
interesting_ids = None
1569
if file_list is not None:
1570
interesting_ids = set()
1571
for filename in file_list:
1572
file_id = this_tree.path2id(filename)
1573
interesting_ids.add(file_id)
1574
if this_tree.kind(file_id) != "directory":
1577
for name, ie in this_tree.inventory.iter_entries(file_id):
1578
interesting_ids.add(ie.file_id)
1579
transform_tree(this_tree, b.basis_tree(), interesting_ids)
1580
if file_list is None:
1581
restore_files = list(this_tree.iter_conflicts())
1583
restore_files = file_list
1584
for filename in restore_files:
1586
restore(this_tree.abspath(filename))
1587
except NotConflicted:
1589
conflicts = merge_inner(b, other_tree, base_tree,
1590
interesting_ids = interesting_ids,
1591
other_rev_id=pending_merges[0],
1592
merge_type=merge_type,
1593
show_base=show_base,
1594
reprocess=reprocess)
4162
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4163
merger.interesting_ids = interesting_ids
4164
merger.merge_type = merge_type
4165
merger.show_base = show_base
4166
merger.reprocess = reprocess
4167
conflicts = merger.do_merge()
4169
tree.set_parent_ids(parents)
1597
4170
if conflicts > 0:
1602
4176
class cmd_revert(Command):
1603
"""Reverse all changes since the last commit.
1605
Only versioned files are affected. Specify filenames to revert only
1606
those files. By default, any files that are changed will be backed up
1607
first. Backup files have a '~' appended to their name.
4177
__doc__ = """Revert files to a previous revision.
4179
Giving a list of files will revert only those files. Otherwise, all files
4180
will be reverted. If the revision is not specified with '--revision', the
4181
last committed revision is used.
4183
To remove only some changes, without reverting to a prior version, use
4184
merge instead. For example, "merge . --revision -2..-3" will remove the
4185
changes introduced by -2, without affecting the changes introduced by -1.
4186
Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
4188
By default, any files that have been manually changed will be backed up
4189
first. (Files changed only by merge are not backed up.) Backup files have
4190
'.~#~' appended to their name, where # is a number.
4192
When you provide files, you can use their current pathname or the pathname
4193
from the target revision. So you can use revert to "undelete" a file by
4194
name. If you name a directory, all the contents of that directory will be
4197
If you have newly added files since the target revision, they will be
4198
removed. If the files to be removed have been changed, backups will be
4199
created as above. Directories containing unknown files will not be
4202
The working tree contains a list of revisions that have been merged but
4203
not yet committed. These revisions will be included as additional parents
4204
of the next commit. Normally, using revert clears that list as well as
4205
reverting the files. If any files are specified, revert leaves the list
4206
of uncommitted merges alone and reverts only the files. Use ``bzr revert
4207
.`` in the tree root to revert all files but keep the recorded merges,
4208
and ``bzr revert --forget-merges`` to clear the pending merge list without
4209
reverting any files.
4211
Using "bzr revert --forget-merges", it is possible to apply all of the
4212
changes from a branch in a single revision. To do this, perform the merge
4213
as desired. Then doing revert with the "--forget-merges" option will keep
4214
the content of the tree as it was, but it will clear the list of pending
4215
merges. The next commit will then contain all of the changes that are
4216
present in the other branch, but without any other parent revisions.
4217
Because this technique forgets where these changes originated, it may
4218
cause additional conflicts on later merges involving the same source and
1609
takes_options = ['revision', 'no-backup']
4222
_see_also = ['cat', 'export']
4225
Option('no-backup', "Do not save backups of reverted files."),
4226
Option('forget-merges',
4227
'Remove pending merge marker, without changing any files.'),
1610
4229
takes_args = ['file*']
1611
aliases = ['merge-revert']
1613
def run(self, revision=None, no_backup=False, file_list=None):
1614
from bzrlib.merge import merge_inner
1615
from bzrlib.commands import parse_spec
1616
if file_list is not None:
1617
if len(file_list) == 0:
1618
raise BzrCommandError("No files specified")
1621
if revision is None:
1623
b = Branch.open_containing('.')[0]
1624
rev_id = b.last_revision()
1625
elif len(revision) != 1:
1626
raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1628
b, file_list = branch_files(file_list)
1629
rev_id = revision[0].in_history(b).rev_id
1630
b.working_tree().revert(file_list, b.revision_tree(rev_id),
4231
def run(self, revision=None, no_backup=False, file_list=None,
4232
forget_merges=None):
4233
tree, file_list = WorkingTree.open_containing_paths(file_list)
4234
self.add_cleanup(tree.lock_tree_write().unlock)
4236
tree.set_parent_ids(tree.get_parent_ids()[:1])
4238
self._revert_tree_to_revision(tree, revision, file_list, no_backup)
4241
def _revert_tree_to_revision(tree, revision, file_list, no_backup):
4242
rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4243
tree.revert(file_list, rev_tree, not no_backup, None,
4244
report_changes=True)
1634
4247
class cmd_assert_fail(Command):
1635
"""Test reporting of assertion failures"""
4248
__doc__ = """Test reporting of assertion failures"""
4249
# intended just for use in testing
1638
assert False, "always fails"
4254
raise AssertionError("always fails")
1641
4257
class cmd_help(Command):
1642
"""Show help on a command or other topic.
4258
__doc__ = """Show help on a command or other topic.
1644
For a list of all available commands, say 'bzr help commands'."""
1645
takes_options = ['long']
4261
_see_also = ['topics']
4263
Option('long', 'Show help on all commands.'),
1646
4265
takes_args = ['topic?']
4266
aliases = ['?', '--help', '-?', '-h']
1649
4268
@display_command
1650
4269
def run(self, topic=None, long=False):
1652
4271
if topic is None and long:
1653
4272
topic = "commands"
4273
bzrlib.help.help(topic)
1657
4276
class cmd_shell_complete(Command):
1658
"""Show appropriate completions for context.
4277
__doc__ = """Show appropriate completions for context.
1660
For a list of all available commands, say 'bzr shell-complete'."""
4279
For a list of all available commands, say 'bzr shell-complete'.
1661
4281
takes_args = ['context?']
1662
4282
aliases = ['s-c']
1665
4285
@display_command
1666
4286
def run(self, context=None):
1667
4287
import shellcomplete
1668
4288
shellcomplete.shellcomplete(context)
1671
class cmd_fetch(Command):
1672
"""Copy in history from another branch but don't merge it.
1674
This is an internal method used for pull and merge."""
1676
takes_args = ['from_branch', 'to_branch']
1677
def run(self, from_branch, to_branch):
1678
from bzrlib.fetch import Fetcher
1679
from bzrlib.branch import Branch
1680
from_b = Branch.open(from_branch)
1681
to_b = Branch.open(to_branch)
1686
Fetcher(to_b, from_b)
1693
4291
class cmd_missing(Command):
1694
"""What is missing in this branch relative to other branch.
4292
__doc__ = """Show unmerged/unpulled revisions between two branches.
4294
OTHER_BRANCH may be local or remote.
4296
To filter on a range of revisions, you can use the command -r begin..end
4297
-r revision requests a specific revision, -r ..end or -r begin.. are
4301
1 - some missing revisions
4302
0 - no missing revisions
4306
Determine the missing revisions between this and the branch at the
4307
remembered pull location::
4311
Determine the missing revisions between this and another branch::
4313
bzr missing http://server/branch
4315
Determine the missing revisions up to a specific revision on the other
4318
bzr missing -r ..-10
4320
Determine the missing revisions up to a specific revision on this
4323
bzr missing --my-revision ..-10
1696
# TODO: rewrite this in terms of ancestry so that it shows only
1699
takes_args = ['remote?']
1700
aliases = ['mis', 'miss']
1701
# We don't have to add quiet to the list, because
1702
# unknown options are parsed as booleans
1703
takes_options = ['verbose', 'quiet']
4326
_see_also = ['merge', 'pull']
4327
takes_args = ['other_branch?']
4330
Option('reverse', 'Reverse the order of revisions.'),
4332
'Display changes in the local branch only.'),
4333
Option('this' , 'Same as --mine-only.'),
4334
Option('theirs-only',
4335
'Display changes in the remote branch only.'),
4336
Option('other', 'Same as --theirs-only.'),
4340
custom_help('revision',
4341
help='Filter on other branch revisions (inclusive). '
4342
'See "help revisionspec" for details.'),
4343
Option('my-revision',
4344
type=_parse_revision_str,
4345
help='Filter on local branch revisions (inclusive). '
4346
'See "help revisionspec" for details.'),
4347
Option('include-merges',
4348
'Show all revisions in addition to the mainline ones.'),
4350
encoding_type = 'replace'
1705
4352
@display_command
1706
def run(self, remote=None, verbose=False, quiet=False):
1707
from bzrlib.errors import BzrCommandError
1708
from bzrlib.missing import show_missing
1710
if verbose and quiet:
1711
raise BzrCommandError('Cannot pass both quiet and verbose')
1713
b = Branch.open_containing('.')[0]
1714
parent = b.get_parent()
1717
raise BzrCommandError("No missing location known or specified.")
1720
print "Using last location: %s" % parent
1722
elif parent is None:
1723
# We only update parent if it did not exist, missing
1724
# should not change the parent
1725
b.set_parent(remote)
1726
br_remote = Branch.open_containing(remote)[0]
1727
return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
4353
def run(self, other_branch=None, reverse=False, mine_only=False,
4355
log_format=None, long=False, short=False, line=False,
4356
show_ids=False, verbose=False, this=False, other=False,
4357
include_merges=False, revision=None, my_revision=None,
4359
from bzrlib.missing import find_unmerged, iter_log_revisions
4368
# TODO: We should probably check that we don't have mine-only and
4369
# theirs-only set, but it gets complicated because we also have
4370
# this and other which could be used.
4377
local_branch = Branch.open_containing(directory)[0]
4378
self.add_cleanup(local_branch.lock_read().unlock)
4380
parent = local_branch.get_parent()
4381
if other_branch is None:
4382
other_branch = parent
4383
if other_branch is None:
4384
raise errors.BzrCommandError("No peer location known"
4386
display_url = urlutils.unescape_for_display(parent,
4388
message("Using saved parent location: "
4389
+ display_url + "\n")
4391
remote_branch = Branch.open(other_branch)
4392
if remote_branch.base == local_branch.base:
4393
remote_branch = local_branch
4395
self.add_cleanup(remote_branch.lock_read().unlock)
4397
local_revid_range = _revision_range_to_revid_range(
4398
_get_revision_range(my_revision, local_branch,
4401
remote_revid_range = _revision_range_to_revid_range(
4402
_get_revision_range(revision,
4403
remote_branch, self.name()))
4405
local_extra, remote_extra = find_unmerged(
4406
local_branch, remote_branch, restrict,
4407
backward=not reverse,
4408
include_merges=include_merges,
4409
local_revid_range=local_revid_range,
4410
remote_revid_range=remote_revid_range)
4412
if log_format is None:
4413
registry = log.log_formatter_registry
4414
log_format = registry.get_default(local_branch)
4415
lf = log_format(to_file=self.outf,
4417
show_timezone='original')
4420
if local_extra and not theirs_only:
4421
message("You have %d extra revision(s):\n" %
4423
for revision in iter_log_revisions(local_extra,
4424
local_branch.repository,
4426
lf.log_revision(revision)
4427
printed_local = True
4430
printed_local = False
4432
if remote_extra and not mine_only:
4433
if printed_local is True:
4435
message("You are missing %d revision(s):\n" %
4437
for revision in iter_log_revisions(remote_extra,
4438
remote_branch.repository,
4440
lf.log_revision(revision)
4443
if mine_only and not local_extra:
4444
# We checked local, and found nothing extra
4445
message('This branch is up to date.\n')
4446
elif theirs_only and not remote_extra:
4447
# We checked remote, and found nothing extra
4448
message('Other branch is up to date.\n')
4449
elif not (mine_only or theirs_only or local_extra or
4451
# We checked both branches, and neither one had extra
4453
message("Branches are up to date.\n")
4455
if not status_code and parent is None and other_branch is not None:
4456
self.add_cleanup(local_branch.lock_write().unlock)
4457
# handle race conditions - a parent might be set while we run.
4458
if local_branch.get_parent() is None:
4459
local_branch.set_parent(remote_branch.base)
4463
class cmd_pack(Command):
4464
__doc__ = """Compress the data within a repository.
4466
This operation compresses the data within a bazaar repository. As
4467
bazaar supports automatic packing of repository, this operation is
4468
normally not required to be done manually.
4470
During the pack operation, bazaar takes a backup of existing repository
4471
data, i.e. pack files. This backup is eventually removed by bazaar
4472
automatically when it is safe to do so. To save disk space by removing
4473
the backed up pack files, the --clean-obsolete-packs option may be
4476
Warning: If you use --clean-obsolete-packs and your machine crashes
4477
during or immediately after repacking, you may be left with a state
4478
where the deletion has been written to disk but the new packs have not
4479
been. In this case the repository may be unusable.
4482
_see_also = ['repositories']
4483
takes_args = ['branch_or_repo?']
4485
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4488
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
4489
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4491
branch = dir.open_branch()
4492
repository = branch.repository
4493
except errors.NotBranchError:
4494
repository = dir.open_repository()
4495
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
1730
4498
class cmd_plugins(Command):
4499
__doc__ = """List the installed plugins.
4501
This command displays the list of installed plugins including
4502
version of plugin and a short description of each.
4504
--verbose shows the path where each plugin is located.
4506
A plugin is an external component for Bazaar that extends the
4507
revision control system, by adding or replacing code in Bazaar.
4508
Plugins can do a variety of things, including overriding commands,
4509
adding new commands, providing additional network transports and
4510
customizing log output.
4512
See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4513
for further information on plugins including where to find them and how to
4514
install them. Instructions are also provided there on how to write new
4515
plugins using the Python programming language.
4517
takes_options = ['verbose']
1733
4519
@display_command
4520
def run(self, verbose=False):
1735
4521
import bzrlib.plugin
1736
4522
from inspect import getdoc
1737
for plugin in bzrlib.plugin.all_plugins:
1738
if hasattr(plugin, '__path__'):
1739
print plugin.__path__[0]
1740
elif hasattr(plugin, '__file__'):
1741
print plugin.__file__
4524
for name, plugin in bzrlib.plugin.plugins().items():
4525
version = plugin.__version__
4526
if version == 'unknown':
4528
name_ver = '%s %s' % (name, version)
4529
d = getdoc(plugin.module)
1747
print '\t', d.split('\n')[0]
4531
doc = d.split('\n')[0]
4533
doc = '(no description)'
4534
result.append((name_ver, doc, plugin.path()))
4535
for name_ver, doc, path in sorted(result):
4536
self.outf.write("%s\n" % name_ver)
4537
self.outf.write(" %s\n" % doc)
4539
self.outf.write(" %s\n" % path)
4540
self.outf.write("\n")
1750
4543
class cmd_testament(Command):
1751
"""Show testament (signing-form) of a revision."""
1752
takes_options = ['revision', 'long']
4544
__doc__ = """Show testament (signing-form) of a revision."""
4547
Option('long', help='Produce long-format testament.'),
4549
help='Produce a strict-format testament.')]
1753
4550
takes_args = ['branch?']
1754
4551
@display_command
1755
def run(self, branch='.', revision=None, long=False):
1756
from bzrlib.testament import Testament
1757
b = Branch.open_containing(branch)[0]
1760
if revision is None:
1761
rev_id = b.last_revision()
1763
rev_id = revision[0].in_history(b).rev_id
1764
t = Testament.from_revision(b, rev_id)
1766
sys.stdout.writelines(t.as_text_lines())
1768
sys.stdout.write(t.as_short_text())
4552
def run(self, branch=u'.', revision=None, long=False, strict=False):
4553
from bzrlib.testament import Testament, StrictTestament
4555
testament_class = StrictTestament
4557
testament_class = Testament
4559
b = Branch.open_containing(branch)[0]
4561
b = Branch.open(branch)
4562
self.add_cleanup(b.lock_read().unlock)
4563
if revision is None:
4564
rev_id = b.last_revision()
4566
rev_id = revision[0].as_revision_id(b)
4567
t = testament_class.from_revision(b.repository, rev_id)
4569
sys.stdout.writelines(t.as_text_lines())
4571
sys.stdout.write(t.as_short_text())
1773
4574
class cmd_annotate(Command):
1774
"""Show the origin of each line in a file.
4575
__doc__ = """Show the origin of each line in a file.
1776
4577
This prints out the given file with an annotation on the left side
1777
4578
indicating which revision, author and date introduced the change.
1779
If the origin is the same for a run of consecutive lines, it is
4580
If the origin is the same for a run of consecutive lines, it is
1780
4581
shown only at the top, unless the --all option is given.
1782
4583
# TODO: annotate directories; showing when each file was last changed
1783
# TODO: annotate a previous version of a file
1784
# TODO: if the working copy is modified, show annotations on that
4584
# TODO: if the working copy is modified, show annotations on that
1785
4585
# with new uncommitted lines marked
1786
aliases = ['blame', 'praise']
4586
aliases = ['ann', 'blame', 'praise']
1787
4587
takes_args = ['filename']
1788
takes_options = [Option('all', help='show annotations on all lines'),
1789
Option('long', help='show date in annotations'),
4588
takes_options = [Option('all', help='Show annotations on all lines.'),
4589
Option('long', help='Show commit date in annotations.'),
4594
encoding_type = 'exact'
1792
4596
@display_command
1793
def run(self, filename, all=False, long=False):
1794
from bzrlib.annotate import annotate_file
1795
b, relpath = Branch.open_containing(filename)
1798
tree = WorkingTree(b.base, b)
1799
tree = b.revision_tree(b.last_revision())
1800
file_id = tree.inventory.path2id(relpath)
1801
file_version = tree.inventory[file_id].revision
1802
annotate_file(b, file_version, file_id, long, all, sys.stdout)
4597
def run(self, filename, all=False, long=False, revision=None,
4598
show_ids=False, directory=None):
4599
from bzrlib.annotate import annotate_file, annotate_file_tree
4600
wt, branch, relpath = \
4601
_open_directory_or_containing_tree_or_branch(filename, directory)
4603
self.add_cleanup(wt.lock_read().unlock)
4605
self.add_cleanup(branch.lock_read().unlock)
4606
tree = _get_one_revision_tree('annotate', revision, branch=branch)
4607
self.add_cleanup(tree.lock_read().unlock)
4609
file_id = wt.path2id(relpath)
4611
file_id = tree.path2id(relpath)
4613
raise errors.NotVersionedError(filename)
4614
file_version = tree.inventory[file_id].revision
4615
if wt is not None and revision is None:
4616
# If there is a tree and we're not annotating historical
4617
# versions, annotate the working tree's content.
4618
annotate_file_tree(wt, file_id, self.outf, long, all,
4621
annotate_file(branch, file_version, file_id, long, all, self.outf,
1807
4625
class cmd_re_sign(Command):
1808
"""Create a digital signature for an existing revision."""
4626
__doc__ = """Create a digital signature for an existing revision."""
1809
4627
# TODO be able to replace existing ones.
1811
4629
hidden = True # is this right ?
1812
takes_args = ['revision_id?']
1813
takes_options = ['revision']
1815
def run(self, revision_id=None, revision=None):
1816
import bzrlib.config as config
4630
takes_args = ['revision_id*']
4631
takes_options = ['directory', 'revision']
4633
def run(self, revision_id_list=None, revision=None, directory=u'.'):
4634
if revision_id_list is not None and revision is not None:
4635
raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4636
if revision_id_list is None and revision is None:
4637
raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4638
b = WorkingTree.open_containing(directory)[0].branch
4639
self.add_cleanup(b.lock_write().unlock)
4640
return self._run(b, revision_id_list, revision)
4642
def _run(self, b, revision_id_list, revision):
1817
4643
import bzrlib.gpg as gpg
1818
if revision_id is not None and revision is not None:
1819
raise BzrCommandError('You can only supply one of revision_id or --revision')
1820
if revision_id is None and revision is None:
1821
raise BzrCommandError('You must supply either --revision or a revision_id')
1822
b = Branch.open_containing('.')[0]
1823
gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1824
if revision_id is not None:
1825
b.sign_revision(revision_id, gpg_strategy)
4644
gpg_strategy = gpg.GPGStrategy(b.get_config())
4645
if revision_id_list is not None:
4646
b.repository.start_write_group()
4648
for revision_id in revision_id_list:
4649
b.repository.sign_revision(revision_id, gpg_strategy)
4651
b.repository.abort_write_group()
4654
b.repository.commit_write_group()
1826
4655
elif revision is not None:
1827
4656
if len(revision) == 1:
1828
4657
revno, rev_id = revision[0].in_history(b)
1829
b.sign_revision(rev_id, gpg_strategy)
4658
b.repository.start_write_group()
4660
b.repository.sign_revision(rev_id, gpg_strategy)
4662
b.repository.abort_write_group()
4665
b.repository.commit_write_group()
1830
4666
elif len(revision) == 2:
1831
4667
# are they both on rh- if so we can walk between them
1832
4668
# might be nice to have a range helper for arbitrary
1836
4672
if to_revid is None:
1837
4673
to_revno = b.revno()
1838
4674
if from_revno is None or to_revno is None:
1839
raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
1840
for revno in range(from_revno, to_revno + 1):
1841
b.sign_revision(b.get_rev_id(revno), gpg_strategy)
1843
raise BzrCommandError('Please supply either one revision, or a range.')
1846
# these get imported and then picked up by the scan for cmd_*
1847
# TODO: Some more consistent way to split command definitions across files;
1848
# we do need to load at least some information about them to know of
1850
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4675
raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
4676
b.repository.start_write_group()
4678
for revno in range(from_revno, to_revno + 1):
4679
b.repository.sign_revision(b.get_rev_id(revno),
4682
b.repository.abort_write_group()
4685
b.repository.commit_write_group()
4687
raise errors.BzrCommandError('Please supply either one revision, or a range.')
4690
class cmd_bind(Command):
4691
__doc__ = """Convert the current branch into a checkout of the supplied branch.
4692
If no branch is supplied, rebind to the last bound location.
4694
Once converted into a checkout, commits must succeed on the master branch
4695
before they will be applied to the local branch.
4697
Bound branches use the nickname of its master branch unless it is set
4698
locally, in which case binding will update the local nickname to be
4702
_see_also = ['checkouts', 'unbind']
4703
takes_args = ['location?']
4704
takes_options = ['directory']
4706
def run(self, location=None, directory=u'.'):
4707
b, relpath = Branch.open_containing(directory)
4708
if location is None:
4710
location = b.get_old_bound_location()
4711
except errors.UpgradeRequired:
4712
raise errors.BzrCommandError('No location supplied. '
4713
'This format does not remember old locations.')
4715
if location is None:
4716
if b.get_bound_location() is not None:
4717
raise errors.BzrCommandError('Branch is already bound')
4719
raise errors.BzrCommandError('No location supplied '
4720
'and no previous location known')
4721
b_other = Branch.open(location)
4724
except errors.DivergedBranches:
4725
raise errors.BzrCommandError('These branches have diverged.'
4726
' Try merging, and then bind again.')
4727
if b.get_config().has_explicit_nickname():
4728
b.nick = b_other.nick
4731
class cmd_unbind(Command):
4732
__doc__ = """Convert the current checkout into a regular branch.
4734
After unbinding, the local branch is considered independent and subsequent
4735
commits will be local only.
4738
_see_also = ['checkouts', 'bind']
4740
takes_options = ['directory']
4742
def run(self, directory=u'.'):
4743
b, relpath = Branch.open_containing(directory)
4745
raise errors.BzrCommandError('Local branch is not bound')
4748
class cmd_uncommit(Command):
4749
__doc__ = """Remove the last committed revision.
4751
--verbose will print out what is being removed.
4752
--dry-run will go through all the motions, but not actually
4755
If --revision is specified, uncommit revisions to leave the branch at the
4756
specified revision. For example, "bzr uncommit -r 15" will leave the
4757
branch at revision 15.
4759
Uncommit leaves the working tree ready for a new commit. The only change
4760
it may make is to restore any pending merges that were present before
4764
# TODO: jam 20060108 Add an option to allow uncommit to remove
4765
# unreferenced information in 'branch-as-repository' branches.
4766
# TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
4767
# information in shared branches as well.
4768
_see_also = ['commit']
4769
takes_options = ['verbose', 'revision',
4770
Option('dry-run', help='Don\'t actually make changes.'),
4771
Option('force', help='Say yes to all questions.'),
4773
help="Only remove the commits from the local branch"
4774
" when in a checkout."
4777
takes_args = ['location?']
4779
encoding_type = 'replace'
4781
def run(self, location=None,
4782
dry_run=False, verbose=False,
4783
revision=None, force=False, local=False):
4784
if location is None:
4786
control, relpath = bzrdir.BzrDir.open_containing(location)
4788
tree = control.open_workingtree()
4790
except (errors.NoWorkingTree, errors.NotLocalUrl):
4792
b = control.open_branch()
4794
if tree is not None:
4795
self.add_cleanup(tree.lock_write().unlock)
4797
self.add_cleanup(b.lock_write().unlock)
4798
return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4800
def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4801
from bzrlib.log import log_formatter, show_log
4802
from bzrlib.uncommit import uncommit
4804
last_revno, last_rev_id = b.last_revision_info()
4807
if revision is None:
4809
rev_id = last_rev_id
4811
# 'bzr uncommit -r 10' actually means uncommit
4812
# so that the final tree is at revno 10.
4813
# but bzrlib.uncommit.uncommit() actually uncommits
4814
# the revisions that are supplied.
4815
# So we need to offset it by one
4816
revno = revision[0].in_history(b).revno + 1
4817
if revno <= last_revno:
4818
rev_id = b.get_rev_id(revno)
4820
if rev_id is None or _mod_revision.is_null(rev_id):
4821
self.outf.write('No revisions to uncommit.\n')
4824
lf = log_formatter('short',
4826
show_timezone='original')
4831
direction='forward',
4832
start_revision=revno,
4833
end_revision=last_revno)
4836
self.outf.write('Dry-run, pretending to remove'
4837
' the above revisions.\n')
4839
self.outf.write('The above revision(s) will be removed.\n')
4842
if not ui.ui_factory.confirm_action(
4843
'Uncommit these revisions',
4844
'bzrlib.builtins.uncommit',
4846
self.outf.write('Canceled\n')
4849
mutter('Uncommitting from {%s} to {%s}',
4850
last_rev_id, rev_id)
4851
uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4852
revno=revno, local=local)
4853
self.outf.write('You can restore the old tip by running:\n'
4854
' bzr pull . -r revid:%s\n' % last_rev_id)
4857
class cmd_break_lock(Command):
4858
__doc__ = """Break a dead lock.
4860
This command breaks a lock on a repository, branch, working directory or
4863
CAUTION: Locks should only be broken when you are sure that the process
4864
holding the lock has been stopped.
4866
You can get information on what locks are open via the 'bzr info
4867
[location]' command.
4871
bzr break-lock bzr+ssh://example.com/bzr/foo
4872
bzr break-lock --conf ~/.bazaar
4875
takes_args = ['location?']
4878
help='LOCATION is the directory where the config lock is.'),
4880
help='Do not ask for confirmation before breaking the lock.'),
4883
def run(self, location=None, config=False, force=False):
4884
if location is None:
4887
ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
4889
{'bzrlib.lockdir.break': True})
4891
conf = _mod_config.LockableConfig(file_name=location)
4894
control, relpath = bzrdir.BzrDir.open_containing(location)
4896
control.break_lock()
4897
except NotImplementedError:
4901
class cmd_wait_until_signalled(Command):
4902
__doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4904
This just prints a line to signal when it is ready, then blocks on stdin.
4910
sys.stdout.write("running\n")
4912
sys.stdin.readline()
4915
class cmd_serve(Command):
4916
__doc__ = """Run the bzr server."""
4918
aliases = ['server']
4922
help='Serve on stdin/out for use from inetd or sshd.'),
4923
RegistryOption('protocol',
4924
help="Protocol to serve.",
4925
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4926
value_switches=True),
4928
help='Listen for connections on nominated port of the form '
4929
'[hostname:]portnumber. Passing 0 as the port number will '
4930
'result in a dynamically allocated port. The default port '
4931
'depends on the protocol.',
4933
custom_help('directory',
4934
help='Serve contents of this directory.'),
4935
Option('allow-writes',
4936
help='By default the server is a readonly server. Supplying '
4937
'--allow-writes enables write access to the contents of '
4938
'the served directory and below. Note that ``bzr serve`` '
4939
'does not perform authentication, so unless some form of '
4940
'external authentication is arranged supplying this '
4941
'option leads to global uncontrolled write access to your '
4946
def get_host_and_port(self, port):
4947
"""Return the host and port to run the smart server on.
4949
If 'port' is None, None will be returned for the host and port.
4951
If 'port' has a colon in it, the string before the colon will be
4952
interpreted as the host.
4954
:param port: A string of the port to run the server on.
4955
:return: A tuple of (host, port), where 'host' is a host name or IP,
4956
and port is an integer TCP/IP port.
4959
if port is not None:
4961
host, port = port.split(':')
4965
def run(self, port=None, inet=False, directory=None, allow_writes=False,
4967
from bzrlib import transport
4968
if directory is None:
4969
directory = os.getcwd()
4970
if protocol is None:
4971
protocol = transport.transport_server_registry.get()
4972
host, port = self.get_host_and_port(port)
4973
url = urlutils.local_path_to_url(directory)
4974
if not allow_writes:
4975
url = 'readonly+' + url
4976
t = transport.get_transport(url)
4977
protocol(t, host, port, inet)
4980
class cmd_join(Command):
4981
__doc__ = """Combine a tree into its containing tree.
4983
This command requires the target tree to be in a rich-root format.
4985
The TREE argument should be an independent tree, inside another tree, but
4986
not part of it. (Such trees can be produced by "bzr split", but also by
4987
running "bzr branch" with the target inside a tree.)
4989
The result is a combined tree, with the subtree no longer an independent
4990
part. This is marked as a merge of the subtree into the containing tree,
4991
and all history is preserved.
4994
_see_also = ['split']
4995
takes_args = ['tree']
4997
Option('reference', help='Join by reference.', hidden=True),
5000
def run(self, tree, reference=False):
5001
sub_tree = WorkingTree.open(tree)
5002
parent_dir = osutils.dirname(sub_tree.basedir)
5003
containing_tree = WorkingTree.open_containing(parent_dir)[0]
5004
repo = containing_tree.branch.repository
5005
if not repo.supports_rich_root():
5006
raise errors.BzrCommandError(
5007
"Can't join trees because %s doesn't support rich root data.\n"
5008
"You can use bzr upgrade on the repository."
5012
containing_tree.add_reference(sub_tree)
5013
except errors.BadReferenceTarget, e:
5014
# XXX: Would be better to just raise a nicely printable
5015
# exception from the real origin. Also below. mbp 20070306
5016
raise errors.BzrCommandError("Cannot join %s. %s" %
5020
containing_tree.subsume(sub_tree)
5021
except errors.BadSubsumeSource, e:
5022
raise errors.BzrCommandError("Cannot join %s. %s" %
5026
class cmd_split(Command):
5027
__doc__ = """Split a subdirectory of a tree into a separate tree.
5029
This command will produce a target tree in a format that supports
5030
rich roots, like 'rich-root' or 'rich-root-pack'. These formats cannot be
5031
converted into earlier formats like 'dirstate-tags'.
5033
The TREE argument should be a subdirectory of a working tree. That
5034
subdirectory will be converted into an independent tree, with its own
5035
branch. Commits in the top-level tree will not apply to the new subtree.
5038
_see_also = ['join']
5039
takes_args = ['tree']
5041
def run(self, tree):
5042
containing_tree, subdir = WorkingTree.open_containing(tree)
5043
sub_id = containing_tree.path2id(subdir)
5045
raise errors.NotVersionedError(subdir)
5047
containing_tree.extract(sub_id)
5048
except errors.RootNotRich:
5049
raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
5052
class cmd_merge_directive(Command):
5053
__doc__ = """Generate a merge directive for auto-merge tools.
5055
A directive requests a merge to be performed, and also provides all the
5056
information necessary to do so. This means it must either include a
5057
revision bundle, or the location of a branch containing the desired
5060
A submit branch (the location to merge into) must be supplied the first
5061
time the command is issued. After it has been supplied once, it will
5062
be remembered as the default.
5064
A public branch is optional if a revision bundle is supplied, but required
5065
if --diff or --plain is specified. It will be remembered as the default
5066
after the first use.
5069
takes_args = ['submit_branch?', 'public_branch?']
5073
_see_also = ['send']
5077
RegistryOption.from_kwargs('patch-type',
5078
'The type of patch to include in the directive.',
5080
value_switches=True,
5082
bundle='Bazaar revision bundle (default).',
5083
diff='Normal unified diff.',
5084
plain='No patch, just directive.'),
5085
Option('sign', help='GPG-sign the directive.'), 'revision',
5086
Option('mail-to', type=str,
5087
help='Instead of printing the directive, email to this address.'),
5088
Option('message', type=str, short_name='m',
5089
help='Message to use when committing this merge.')
5092
encoding_type = 'exact'
5094
def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5095
sign=False, revision=None, mail_to=None, message=None,
5097
from bzrlib.revision import ensure_null, NULL_REVISION
5098
include_patch, include_bundle = {
5099
'plain': (False, False),
5100
'diff': (True, False),
5101
'bundle': (True, True),
5103
branch = Branch.open(directory)
5104
stored_submit_branch = branch.get_submit_branch()
5105
if submit_branch is None:
5106
submit_branch = stored_submit_branch
5108
if stored_submit_branch is None:
5109
branch.set_submit_branch(submit_branch)
5110
if submit_branch is None:
5111
submit_branch = branch.get_parent()
5112
if submit_branch is None:
5113
raise errors.BzrCommandError('No submit branch specified or known')
5115
stored_public_branch = branch.get_public_branch()
5116
if public_branch is None:
5117
public_branch = stored_public_branch
5118
elif stored_public_branch is None:
5119
branch.set_public_branch(public_branch)
5120
if not include_bundle and public_branch is None:
5121
raise errors.BzrCommandError('No public branch specified or'
5123
base_revision_id = None
5124
if revision is not None:
5125
if len(revision) > 2:
5126
raise errors.BzrCommandError('bzr merge-directive takes '
5127
'at most two one revision identifiers')
5128
revision_id = revision[-1].as_revision_id(branch)
5129
if len(revision) == 2:
5130
base_revision_id = revision[0].as_revision_id(branch)
5132
revision_id = branch.last_revision()
5133
revision_id = ensure_null(revision_id)
5134
if revision_id == NULL_REVISION:
5135
raise errors.BzrCommandError('No revisions to bundle.')
5136
directive = merge_directive.MergeDirective2.from_objects(
5137
branch.repository, revision_id, time.time(),
5138
osutils.local_time_offset(), submit_branch,
5139
public_branch=public_branch, include_patch=include_patch,
5140
include_bundle=include_bundle, message=message,
5141
base_revision_id=base_revision_id)
5144
self.outf.write(directive.to_signed(branch))
5146
self.outf.writelines(directive.to_lines())
5148
message = directive.to_email(mail_to, branch, sign)
5149
s = SMTPConnection(branch.get_config())
5150
s.send_email(message)
5153
class cmd_send(Command):
5154
__doc__ = """Mail or create a merge-directive for submitting changes.
5156
A merge directive provides many things needed for requesting merges:
5158
* A machine-readable description of the merge to perform
5160
* An optional patch that is a preview of the changes requested
5162
* An optional bundle of revision data, so that the changes can be applied
5163
directly from the merge directive, without retrieving data from a
5166
`bzr send` creates a compact data set that, when applied using bzr
5167
merge, has the same effect as merging from the source branch.
5169
By default the merge directive is self-contained and can be applied to any
5170
branch containing submit_branch in its ancestory without needing access to
5173
If --no-bundle is specified, then Bazaar doesn't send the contents of the
5174
revisions, but only a structured request to merge from the
5175
public_location. In that case the public_branch is needed and it must be
5176
up-to-date and accessible to the recipient. The public_branch is always
5177
included if known, so that people can check it later.
5179
The submit branch defaults to the parent of the source branch, but can be
5180
overridden. Both submit branch and public branch will be remembered in
5181
branch.conf the first time they are used for a particular branch. The
5182
source branch defaults to that containing the working directory, but can
5183
be changed using --from.
5185
In order to calculate those changes, bzr must analyse the submit branch.
5186
Therefore it is most efficient for the submit branch to be a local mirror.
5187
If a public location is known for the submit_branch, that location is used
5188
in the merge directive.
5190
The default behaviour is to send the merge directive by mail, unless -o is
5191
given, in which case it is sent to a file.
5193
Mail is sent using your preferred mail program. This should be transparent
5194
on Windows (it uses MAPI). On Unix, it requires the xdg-email utility.
5195
If the preferred client can't be found (or used), your editor will be used.
5197
To use a specific mail program, set the mail_client configuration option.
5198
(For Thunderbird 1.5, this works around some bugs.) Supported values for
5199
specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5200
Mail.app), "mutt", and "thunderbird"; generic options are "default",
5201
"editor", "emacsclient", "mapi", and "xdg-email". Plugins may also add
5204
If mail is being sent, a to address is required. This can be supplied
5205
either on the commandline, by setting the submit_to configuration
5206
option in the branch itself or the child_submit_to configuration option
5207
in the submit branch.
5209
Two formats are currently supported: "4" uses revision bundle format 4 and
5210
merge directive format 2. It is significantly faster and smaller than
5211
older formats. It is compatible with Bazaar 0.19 and later. It is the
5212
default. "0.9" uses revision bundle format 0.9 and merge directive
5213
format 1. It is compatible with Bazaar 0.12 - 0.18.
5215
The merge directives created by bzr send may be applied using bzr merge or
5216
bzr pull by specifying a file containing a merge directive as the location.
5218
bzr send makes extensive use of public locations to map local locations into
5219
URLs that can be used by other people. See `bzr help configuration` to
5220
set them, and use `bzr info` to display them.
5223
encoding_type = 'exact'
5225
_see_also = ['merge', 'pull']
5227
takes_args = ['submit_branch?', 'public_branch?']
5231
help='Do not include a bundle in the merge directive.'),
5232
Option('no-patch', help='Do not include a preview patch in the merge'
5235
help='Remember submit and public branch.'),
5237
help='Branch to generate the submission from, '
5238
'rather than the one containing the working directory.',
5241
Option('output', short_name='o',
5242
help='Write merge directive to this file or directory; '
5243
'use - for stdout.',
5246
help='Refuse to send if there are uncommitted changes in'
5247
' the working tree, --no-strict disables the check.'),
5248
Option('mail-to', help='Mail the request to this address.',
5252
Option('body', help='Body for the email.', type=unicode),
5253
RegistryOption('format',
5254
help='Use the specified output format.',
5255
lazy_registry=('bzrlib.send', 'format_registry')),
5258
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5259
no_patch=False, revision=None, remember=False, output=None,
5260
format=None, mail_to=None, message=None, body=None,
5261
strict=None, **kwargs):
5262
from bzrlib.send import send
5263
return send(submit_branch, revision, public_branch, remember,
5264
format, no_bundle, no_patch, output,
5265
kwargs.get('from', '.'), mail_to, message, body,
5270
class cmd_bundle_revisions(cmd_send):
5271
__doc__ = """Create a merge-directive for submitting changes.
5273
A merge directive provides many things needed for requesting merges:
5275
* A machine-readable description of the merge to perform
5277
* An optional patch that is a preview of the changes requested
5279
* An optional bundle of revision data, so that the changes can be applied
5280
directly from the merge directive, without retrieving data from a
5283
If --no-bundle is specified, then public_branch is needed (and must be
5284
up-to-date), so that the receiver can perform the merge using the
5285
public_branch. The public_branch is always included if known, so that
5286
people can check it later.
5288
The submit branch defaults to the parent, but can be overridden. Both
5289
submit branch and public branch will be remembered if supplied.
5291
If a public_branch is known for the submit_branch, that public submit
5292
branch is used in the merge instructions. This means that a local mirror
5293
can be used as your actual submit branch, once you have set public_branch
5296
Two formats are currently supported: "4" uses revision bundle format 4 and
5297
merge directive format 2. It is significantly faster and smaller than
5298
older formats. It is compatible with Bazaar 0.19 and later. It is the
5299
default. "0.9" uses revision bundle format 0.9 and merge directive
5300
format 1. It is compatible with Bazaar 0.12 - 0.18.
5305
help='Do not include a bundle in the merge directive.'),
5306
Option('no-patch', help='Do not include a preview patch in the merge'
5309
help='Remember submit and public branch.'),
5311
help='Branch to generate the submission from, '
5312
'rather than the one containing the working directory.',
5315
Option('output', short_name='o', help='Write directive to this file.',
5318
help='Refuse to bundle revisions if there are uncommitted'
5319
' changes in the working tree, --no-strict disables the check.'),
5321
RegistryOption('format',
5322
help='Use the specified output format.',
5323
lazy_registry=('bzrlib.send', 'format_registry')),
5325
aliases = ['bundle']
5327
_see_also = ['send', 'merge']
5331
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5332
no_patch=False, revision=None, remember=False, output=None,
5333
format=None, strict=None, **kwargs):
5336
from bzrlib.send import send
5337
return send(submit_branch, revision, public_branch, remember,
5338
format, no_bundle, no_patch, output,
5339
kwargs.get('from', '.'), None, None, None,
5340
self.outf, strict=strict)
5343
class cmd_tag(Command):
5344
__doc__ = """Create, remove or modify a tag naming a revision.
5346
Tags give human-meaningful names to revisions. Commands that take a -r
5347
(--revision) option can be given -rtag:X, where X is any previously
5350
Tags are stored in the branch. Tags are copied from one branch to another
5351
along when you branch, push, pull or merge.
5353
It is an error to give a tag name that already exists unless you pass
5354
--force, in which case the tag is moved to point to the new revision.
5356
To rename a tag (change the name but keep it on the same revsion), run ``bzr
5357
tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5359
If no tag name is specified it will be determined through the
5360
'automatic_tag_name' hook. This can e.g. be used to automatically tag
5361
upstream releases by reading configure.ac. See ``bzr help hooks`` for
5365
_see_also = ['commit', 'tags']
5366
takes_args = ['tag_name?']
5369
help='Delete this tag rather than placing it.',
5371
custom_help('directory',
5372
help='Branch in which to place the tag.'),
5374
help='Replace existing tags.',
5379
def run(self, tag_name=None,
5385
branch, relpath = Branch.open_containing(directory)
5386
self.add_cleanup(branch.lock_write().unlock)
5388
if tag_name is None:
5389
raise errors.BzrCommandError("No tag specified to delete.")
5390
branch.tags.delete_tag(tag_name)
5391
note('Deleted tag %s.' % tag_name)
5394
if len(revision) != 1:
5395
raise errors.BzrCommandError(
5396
"Tags can only be placed on a single revision, "
5398
revision_id = revision[0].as_revision_id(branch)
5400
revision_id = branch.last_revision()
5401
if tag_name is None:
5402
tag_name = branch.automatic_tag_name(revision_id)
5403
if tag_name is None:
5404
raise errors.BzrCommandError(
5405
"Please specify a tag name.")
5406
if (not force) and branch.tags.has_tag(tag_name):
5407
raise errors.TagAlreadyExists(tag_name)
5408
branch.tags.set_tag(tag_name, revision_id)
5409
note('Created tag %s.' % tag_name)
5412
class cmd_tags(Command):
5413
__doc__ = """List tags.
5415
This command shows a table of tag names and the revisions they reference.
5420
custom_help('directory',
5421
help='Branch whose tags should be displayed.'),
5422
RegistryOption.from_kwargs('sort',
5423
'Sort tags by different criteria.', title='Sorting',
5424
natural='Sort numeric substrings as numbers:'
5425
' suitable for version numbers. (default)',
5426
alpha='Sort tags lexicographically.',
5427
time='Sort tags chronologically.',
5440
branch, relpath = Branch.open_containing(directory)
5442
tags = branch.tags.get_tag_dict().items()
5446
self.add_cleanup(branch.lock_read().unlock)
5448
graph = branch.repository.get_graph()
5449
rev1, rev2 = _get_revision_range(revision, branch, self.name())
5450
revid1, revid2 = rev1.rev_id, rev2.rev_id
5451
# only show revisions between revid1 and revid2 (inclusive)
5452
tags = [(tag, revid) for tag, revid in tags if
5453
graph.is_between(revid, revid1, revid2)]
5454
if sort == 'natural':
5455
def natural_sort_key(tag):
5456
return [f(s) for f,s in
5457
zip(itertools.cycle((unicode.lower,int)),
5458
re.split('([0-9]+)', tag[0]))]
5459
tags.sort(key=natural_sort_key)
5460
elif sort == 'alpha':
5462
elif sort == 'time':
5464
for tag, revid in tags:
5466
revobj = branch.repository.get_revision(revid)
5467
except errors.NoSuchRevision:
5468
timestamp = sys.maxint # place them at the end
5470
timestamp = revobj.timestamp
5471
timestamps[revid] = timestamp
5472
tags.sort(key=lambda x: timestamps[x[1]])
5474
# [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5475
for index, (tag, revid) in enumerate(tags):
5477
revno = branch.revision_id_to_dotted_revno(revid)
5478
if isinstance(revno, tuple):
5479
revno = '.'.join(map(str, revno))
5480
except errors.NoSuchRevision:
5481
# Bad tag data/merges can lead to tagged revisions
5482
# which are not in this branch. Fail gracefully ...
5484
tags[index] = (tag, revno)
5486
for tag, revspec in tags:
5487
self.outf.write('%-20s %s\n' % (tag, revspec))
5490
class cmd_reconfigure(Command):
5491
__doc__ = """Reconfigure the type of a bzr directory.
5493
A target configuration must be specified.
5495
For checkouts, the bind-to location will be auto-detected if not specified.
5496
The order of preference is
5497
1. For a lightweight checkout, the current bound location.
5498
2. For branches that used to be checkouts, the previously-bound location.
5499
3. The push location.
5500
4. The parent location.
5501
If none of these is available, --bind-to must be specified.
5504
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5505
takes_args = ['location?']
5507
RegistryOption.from_kwargs(
5509
title='Target type',
5510
help='The type to reconfigure the directory to.',
5511
value_switches=True, enum_switch=False,
5512
branch='Reconfigure to be an unbound branch with no working tree.',
5513
tree='Reconfigure to be an unbound branch with a working tree.',
5514
checkout='Reconfigure to be a bound branch with a working tree.',
5515
lightweight_checkout='Reconfigure to be a lightweight'
5516
' checkout (with no local history).',
5517
standalone='Reconfigure to be a standalone branch '
5518
'(i.e. stop using shared repository).',
5519
use_shared='Reconfigure to use a shared repository.',
5520
with_trees='Reconfigure repository to create '
5521
'working trees on branches by default.',
5522
with_no_trees='Reconfigure repository to not create '
5523
'working trees on branches by default.'
5525
Option('bind-to', help='Branch to bind checkout to.', type=str),
5527
help='Perform reconfiguration even if local changes'
5529
Option('stacked-on',
5530
help='Reconfigure a branch to be stacked on another branch.',
5534
help='Reconfigure a branch to be unstacked. This '
5535
'may require copying substantial data into it.',
5539
def run(self, location=None, target_type=None, bind_to=None, force=False,
5542
directory = bzrdir.BzrDir.open(location)
5543
if stacked_on and unstacked:
5544
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5545
elif stacked_on is not None:
5546
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5548
reconfigure.ReconfigureUnstacked().apply(directory)
5549
# At the moment you can use --stacked-on and a different
5550
# reconfiguration shape at the same time; there seems no good reason
5552
if target_type is None:
5553
if stacked_on or unstacked:
5556
raise errors.BzrCommandError('No target configuration '
5558
elif target_type == 'branch':
5559
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5560
elif target_type == 'tree':
5561
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5562
elif target_type == 'checkout':
5563
reconfiguration = reconfigure.Reconfigure.to_checkout(
5565
elif target_type == 'lightweight-checkout':
5566
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5568
elif target_type == 'use-shared':
5569
reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
5570
elif target_type == 'standalone':
5571
reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
5572
elif target_type == 'with-trees':
5573
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5575
elif target_type == 'with-no-trees':
5576
reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5578
reconfiguration.apply(force)
5581
class cmd_switch(Command):
5582
__doc__ = """Set the branch of a checkout and update.
5584
For lightweight checkouts, this changes the branch being referenced.
5585
For heavyweight checkouts, this checks that there are no local commits
5586
versus the current bound branch, then it makes the local branch a mirror
5587
of the new location and binds to it.
5589
In both cases, the working tree is updated and uncommitted changes
5590
are merged. The user can commit or revert these as they desire.
5592
Pending merges need to be committed or reverted before using switch.
5594
The path to the branch to switch to can be specified relative to the parent
5595
directory of the current branch. For example, if you are currently in a
5596
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5599
Bound branches use the nickname of its master branch unless it is set
5600
locally, in which case switching will update the local nickname to be
5604
takes_args = ['to_location?']
5605
takes_options = ['directory',
5607
help='Switch even if local commits will be lost.'),
5609
Option('create-branch', short_name='b',
5610
help='Create the target branch from this one before'
5611
' switching to it.'),
5614
def run(self, to_location=None, force=False, create_branch=False,
5615
revision=None, directory=u'.'):
5616
from bzrlib import switch
5617
tree_location = directory
5618
revision = _get_one_revision('switch', revision)
5619
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5620
if to_location is None:
5621
if revision is None:
5622
raise errors.BzrCommandError('You must supply either a'
5623
' revision or a location')
5624
to_location = tree_location
5626
branch = control_dir.open_branch()
5627
had_explicit_nick = branch.get_config().has_explicit_nickname()
5628
except errors.NotBranchError:
5630
had_explicit_nick = False
5633
raise errors.BzrCommandError('cannot create branch without'
5635
to_location = directory_service.directories.dereference(
5637
if '/' not in to_location and '\\' not in to_location:
5638
# This path is meant to be relative to the existing branch
5639
this_url = self._get_branch_location(control_dir)
5640
to_location = urlutils.join(this_url, '..', to_location)
5641
to_branch = branch.bzrdir.sprout(to_location,
5642
possible_transports=[branch.bzrdir.root_transport],
5643
source_branch=branch).open_branch()
5646
to_branch = Branch.open(to_location)
5647
except errors.NotBranchError:
5648
this_url = self._get_branch_location(control_dir)
5649
to_branch = Branch.open(
5650
urlutils.join(this_url, '..', to_location))
5651
if revision is not None:
5652
revision = revision.as_revision_id(to_branch)
5653
switch.switch(control_dir, to_branch, force, revision_id=revision)
5654
if had_explicit_nick:
5655
branch = control_dir.open_branch() #get the new branch!
5656
branch.nick = to_branch.nick
5657
note('Switched to branch: %s',
5658
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5660
def _get_branch_location(self, control_dir):
5661
"""Return location of branch for this control dir."""
5663
this_branch = control_dir.open_branch()
5664
# This may be a heavy checkout, where we want the master branch
5665
master_location = this_branch.get_bound_location()
5666
if master_location is not None:
5667
return master_location
5668
# If not, use a local sibling
5669
return this_branch.base
5670
except errors.NotBranchError:
5671
format = control_dir.find_branch_format()
5672
if getattr(format, 'get_reference', None) is not None:
5673
return format.get_reference(control_dir)
5675
return control_dir.root_transport.base
5678
class cmd_view(Command):
5679
__doc__ = """Manage filtered views.
5681
Views provide a mask over the tree so that users can focus on
5682
a subset of a tree when doing their work. After creating a view,
5683
commands that support a list of files - status, diff, commit, etc -
5684
effectively have that list of files implicitly given each time.
5685
An explicit list of files can still be given but those files
5686
must be within the current view.
5688
In most cases, a view has a short life-span: it is created to make
5689
a selected change and is deleted once that change is committed.
5690
At other times, you may wish to create one or more named views
5691
and switch between them.
5693
To disable the current view without deleting it, you can switch to
5694
the pseudo view called ``off``. This can be useful when you need
5695
to see the whole tree for an operation or two (e.g. merge) but
5696
want to switch back to your view after that.
5699
To define the current view::
5701
bzr view file1 dir1 ...
5703
To list the current view::
5707
To delete the current view::
5711
To disable the current view without deleting it::
5713
bzr view --switch off
5715
To define a named view and switch to it::
5717
bzr view --name view-name file1 dir1 ...
5719
To list a named view::
5721
bzr view --name view-name
5723
To delete a named view::
5725
bzr view --name view-name --delete
5727
To switch to a named view::
5729
bzr view --switch view-name
5731
To list all views defined::
5735
To delete all views::
5737
bzr view --delete --all
5741
takes_args = ['file*']
5744
help='Apply list or delete action to all views.',
5747
help='Delete the view.',
5750
help='Name of the view to define, list or delete.',
5754
help='Name of the view to switch to.',
5759
def run(self, file_list,
5765
tree, file_list = WorkingTree.open_containing_paths(file_list,
5767
current_view, view_dict = tree.views.get_view_info()
5772
raise errors.BzrCommandError(
5773
"Both --delete and a file list specified")
5775
raise errors.BzrCommandError(
5776
"Both --delete and --switch specified")
5778
tree.views.set_view_info(None, {})
5779
self.outf.write("Deleted all views.\n")
5781
raise errors.BzrCommandError("No current view to delete")
5783
tree.views.delete_view(name)
5784
self.outf.write("Deleted '%s' view.\n" % name)
5787
raise errors.BzrCommandError(
5788
"Both --switch and a file list specified")
5790
raise errors.BzrCommandError(
5791
"Both --switch and --all specified")
5792
elif switch == 'off':
5793
if current_view is None:
5794
raise errors.BzrCommandError("No current view to disable")
5795
tree.views.set_view_info(None, view_dict)
5796
self.outf.write("Disabled '%s' view.\n" % (current_view))
5798
tree.views.set_view_info(switch, view_dict)
5799
view_str = views.view_display_str(tree.views.lookup_view())
5800
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5803
self.outf.write('Views defined:\n')
5804
for view in sorted(view_dict):
5805
if view == current_view:
5809
view_str = views.view_display_str(view_dict[view])
5810
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5812
self.outf.write('No views defined.\n')
5815
# No name given and no current view set
5818
raise errors.BzrCommandError(
5819
"Cannot change the 'off' pseudo view")
5820
tree.views.set_view(name, sorted(file_list))
5821
view_str = views.view_display_str(tree.views.lookup_view())
5822
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5826
# No name given and no current view set
5827
self.outf.write('No current view.\n')
5829
view_str = views.view_display_str(tree.views.lookup_view(name))
5830
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5833
class cmd_hooks(Command):
5834
__doc__ = """Show hooks."""
5839
for hook_key in sorted(hooks.known_hooks.keys()):
5840
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5841
self.outf.write("%s:\n" % type(some_hooks).__name__)
5842
for hook_name, hook_point in sorted(some_hooks.items()):
5843
self.outf.write(" %s:\n" % (hook_name,))
5844
found_hooks = list(hook_point)
5846
for hook in found_hooks:
5847
self.outf.write(" %s\n" %
5848
(some_hooks.get_hook_name(hook),))
5850
self.outf.write(" <no hooks installed>\n")
5853
class cmd_remove_branch(Command):
5854
__doc__ = """Remove a branch.
5856
This will remove the branch from the specified location but
5857
will keep any working tree or repository in place.
5861
Remove the branch at repo/trunk::
5863
bzr remove-branch repo/trunk
5867
takes_args = ["location?"]
5869
aliases = ["rmbranch"]
5871
def run(self, location=None):
5872
if location is None:
5874
branch = Branch.open_containing(location)[0]
5875
branch.bzrdir.destroy_branch()
5878
class cmd_shelve(Command):
5879
__doc__ = """Temporarily set aside some changes from the current tree.
5881
Shelve allows you to temporarily put changes you've made "on the shelf",
5882
ie. out of the way, until a later time when you can bring them back from
5883
the shelf with the 'unshelve' command. The changes are stored alongside
5884
your working tree, and so they aren't propagated along with your branch nor
5885
will they survive its deletion.
5887
If shelve --list is specified, previously-shelved changes are listed.
5889
Shelve is intended to help separate several sets of changes that have
5890
been inappropriately mingled. If you just want to get rid of all changes
5891
and you don't need to restore them later, use revert. If you want to
5892
shelve all text changes at once, use shelve --all.
5894
If filenames are specified, only the changes to those files will be
5895
shelved. Other files will be left untouched.
5897
If a revision is specified, changes since that revision will be shelved.
5899
You can put multiple items on the shelf, and by default, 'unshelve' will
5900
restore the most recently shelved changes.
5903
takes_args = ['file*']
5908
Option('all', help='Shelve all changes.'),
5910
RegistryOption('writer', 'Method to use for writing diffs.',
5911
bzrlib.option.diff_writer_registry,
5912
value_switches=True, enum_switch=False),
5914
Option('list', help='List shelved changes.'),
5916
help='Destroy removed changes instead of shelving them.'),
5918
_see_also = ['unshelve']
5920
def run(self, revision=None, all=False, file_list=None, message=None,
5921
writer=None, list=False, destroy=False, directory=u'.'):
5923
return self.run_for_list()
5924
from bzrlib.shelf_ui import Shelver
5926
writer = bzrlib.option.diff_writer_registry.get()
5928
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5929
file_list, message, destroy=destroy, directory=directory)
5934
except errors.UserAbort:
5937
def run_for_list(self):
5938
tree = WorkingTree.open_containing('.')[0]
5939
self.add_cleanup(tree.lock_read().unlock)
5940
manager = tree.get_shelf_manager()
5941
shelves = manager.active_shelves()
5942
if len(shelves) == 0:
5943
note('No shelved changes.')
5945
for shelf_id in reversed(shelves):
5946
message = manager.get_metadata(shelf_id).get('message')
5948
message = '<no message>'
5949
self.outf.write('%3d: %s\n' % (shelf_id, message))
5953
class cmd_unshelve(Command):
5954
__doc__ = """Restore shelved changes.
5956
By default, the most recently shelved changes are restored. However if you
5957
specify a shelf by id those changes will be restored instead. This works
5958
best when the changes don't depend on each other.
5961
takes_args = ['shelf_id?']
5964
RegistryOption.from_kwargs(
5965
'action', help="The action to perform.",
5966
enum_switch=False, value_switches=True,
5967
apply="Apply changes and remove from the shelf.",
5968
dry_run="Show changes, but do not apply or remove them.",
5969
preview="Instead of unshelving the changes, show the diff that "
5970
"would result from unshelving.",
5971
delete_only="Delete changes without applying them.",
5972
keep="Apply changes but don't delete them.",
5975
_see_also = ['shelve']
5977
def run(self, shelf_id=None, action='apply', directory=u'.'):
5978
from bzrlib.shelf_ui import Unshelver
5979
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5983
unshelver.tree.unlock()
5986
class cmd_clean_tree(Command):
5987
__doc__ = """Remove unwanted files from working tree.
5989
By default, only unknown files, not ignored files, are deleted. Versioned
5990
files are never deleted.
5992
Another class is 'detritus', which includes files emitted by bzr during
5993
normal operations and selftests. (The value of these files decreases with
5996
If no options are specified, unknown files are deleted. Otherwise, option
5997
flags are respected, and may be combined.
5999
To check what clean-tree will do, use --dry-run.
6001
takes_options = ['directory',
6002
Option('ignored', help='Delete all ignored files.'),
6003
Option('detritus', help='Delete conflict files, merge'
6004
' backups, and failed selftest dirs.'),
6006
help='Delete files unknown to bzr (default).'),
6007
Option('dry-run', help='Show files to delete instead of'
6009
Option('force', help='Do not prompt before deleting.')]
6010
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
6011
force=False, directory=u'.'):
6012
from bzrlib.clean_tree import clean_tree
6013
if not (unknown or ignored or detritus):
6017
clean_tree(directory, unknown=unknown, ignored=ignored,
6018
detritus=detritus, dry_run=dry_run, no_prompt=force)
6021
class cmd_reference(Command):
6022
__doc__ = """list, view and set branch locations for nested trees.
6024
If no arguments are provided, lists the branch locations for nested trees.
6025
If one argument is provided, display the branch location for that tree.
6026
If two arguments are provided, set the branch location for that tree.
6031
takes_args = ['path?', 'location?']
6033
def run(self, path=None, location=None):
6035
if path is not None:
6037
tree, branch, relpath =(
6038
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
6039
if path is not None:
6042
tree = branch.basis_tree()
6044
info = branch._get_all_reference_info().iteritems()
6045
self._display_reference_info(tree, branch, info)
6047
file_id = tree.path2id(path)
6049
raise errors.NotVersionedError(path)
6050
if location is None:
6051
info = [(file_id, branch.get_reference_info(file_id))]
6052
self._display_reference_info(tree, branch, info)
6054
branch.set_reference_info(file_id, path, location)
6056
def _display_reference_info(self, tree, branch, info):
6058
for file_id, (path, location) in info:
6060
path = tree.id2path(file_id)
6061
except errors.NoSuchId:
6063
ref_list.append((path, location))
6064
for path, location in sorted(ref_list):
6065
self.outf.write('%s %s\n' % (path, location))
6068
def _register_lazy_builtins():
6069
# register lazy builtins from other modules; called at startup and should
6070
# be only called once.
6071
for (name, aliases, module_name) in [
6072
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6073
('cmd_dpush', [], 'bzrlib.foreign'),
6074
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6075
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6076
('cmd_conflicts', [], 'bzrlib.conflicts'),
6077
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6079
builtin_command_registry.register_lazy(name, aliases, module_name)