29
29
from bzrlib import (
41
39
merge as _mod_merge,
46
43
revision as _mod_revision,
55
50
from bzrlib.branch import Branch
56
51
from bzrlib.conflicts import ConflictList
57
from bzrlib.transport import memory
58
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
52
from bzrlib.revisionspec import RevisionSpec
59
53
from bzrlib.smtp_connection import SMTPConnection
60
54
from bzrlib.workingtree import WorkingTree
63
from bzrlib.commands import (
65
builtin_command_registry,
68
from bzrlib.option import (
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
57
from bzrlib.commands import Command, display_command
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
59
from bzrlib.trace import mutter, note, warning, is_quiet, info
62
def tree_files(file_list, default_branch=u'.'):
81
return internal_tree_files(file_list, default_branch, canonicalize,
64
return internal_tree_files(file_list, default_branch)
83
65
except errors.FileInWrongBranch, e:
84
66
raise errors.BzrCommandError("%s is not in the same branch as %s" %
85
67
(e.path, file_list[0]))
88
def tree_files_for_add(file_list):
90
Return a tree and list of absolute paths from a file list.
92
Similar to tree_files, but add handles files a bit differently, so it a
93
custom implementation. In particular, MutableTreeTree.smart_add expects
94
absolute paths, which it immediately converts to relative paths.
96
# FIXME Would be nice to just return the relative paths like
97
# internal_tree_files does, but there are a large number of unit tests
98
# that assume the current interface to mutabletree.smart_add
100
tree, relpath = WorkingTree.open_containing(file_list[0])
101
if tree.supports_views():
102
view_files = tree.views.lookup_view()
104
for filename in file_list:
105
if not osutils.is_inside_any(view_files, filename):
106
raise errors.FileOutsideView(filename, view_files)
107
file_list = file_list[:]
108
file_list[0] = tree.abspath(relpath)
110
tree = WorkingTree.open_containing(u'.')[0]
111
if tree.supports_views():
112
view_files = tree.views.lookup_view()
114
file_list = view_files
115
view_str = views.view_display_str(view_files)
116
note("Ignoring files outside view. View is %s" % view_str)
117
return tree, file_list
120
def _get_one_revision(command_name, revisions):
121
if revisions is None:
123
if len(revisions) != 1:
124
raise errors.BzrCommandError(
125
'bzr %s --revision takes exactly one revision identifier' % (
130
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
131
"""Get a revision tree. Not suitable for commands that change the tree.
133
Specifically, the basis tree in dirstate trees is coupled to the dirstate
134
and doing a commit/uncommit/pull will at best fail due to changing the
137
If tree is passed in, it should be already locked, for lifetime management
138
of the trees internal cached state.
142
if revisions is None:
144
rev_tree = tree.basis_tree()
146
rev_tree = branch.basis_tree()
148
revision = _get_one_revision(command_name, revisions)
149
rev_tree = revision.as_tree(branch)
153
70
# XXX: Bad function name; should possibly also be a class method of
154
71
# WorkingTree rather than a function.
155
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
72
def internal_tree_files(file_list, default_branch=u'.'):
157
73
"""Convert command-line paths to a WorkingTree and relative paths.
159
75
This is typically used for command-line processors that take one or
314
175
encoding_type = 'replace'
315
176
_see_also = ['diff', 'revert', 'status-flags']
318
179
def run(self, show_ids=False, file_list=None, revision=None, short=False,
319
versioned=False, no_pending=False, verbose=False):
180
versioned=False, no_pending=False):
320
181
from bzrlib.status import show_tree_status
322
183
if revision and len(revision) > 2:
323
184
raise errors.BzrCommandError('bzr status --revision takes exactly'
324
185
' one or two revision specifiers')
326
tree, relfile_list = tree_files(file_list)
327
# Avoid asking for specific files when that is not needed.
328
if relfile_list == ['']:
330
# Don't disable pending merges for full trees other than '.'.
331
if file_list == ['.']:
333
# A specific path within a tree was given.
334
elif relfile_list is not None:
187
tree, file_list = tree_files(file_list)
336
189
show_tree_status(tree, show_ids=show_ids,
337
specific_files=relfile_list, revision=revision,
190
specific_files=file_list, revision=revision,
338
191
to_file=self.outf, short=short, versioned=versioned,
339
show_pending=(not no_pending), verbose=verbose)
192
show_pending=not no_pending)
342
195
class cmd_cat_revision(Command):
343
__doc__ = """Write out metadata for a revision.
196
"""Write out metadata for a revision.
345
198
The revision to print can either be specified by a specific
346
199
revision identifier, or you can use --revision.
350
203
takes_args = ['revision_id?']
351
takes_options = ['directory', 'revision']
204
takes_options = ['revision']
352
205
# cat-revision is more for frontends so should be exact
353
206
encoding = 'strict'
355
def print_revision(self, revisions, revid):
356
stream = revisions.get_record_stream([(revid,)], 'unordered', True)
357
record = stream.next()
358
if record.storage_kind == 'absent':
359
raise errors.NoSuchRevision(revisions, revid)
360
revtext = record.get_bytes_as('fulltext')
361
self.outf.write(revtext.decode('utf-8'))
364
def run(self, revision_id=None, revision=None, directory=u'.'):
209
def run(self, revision_id=None, revision=None):
365
210
if revision_id is not None and revision is not None:
366
211
raise errors.BzrCommandError('You can only supply one of'
367
212
' revision_id or --revision')
368
213
if revision_id is None and revision is None:
369
214
raise errors.BzrCommandError('You must supply either'
370
215
' --revision or a revision_id')
371
b = WorkingTree.open_containing(directory)[0].branch
373
revisions = b.repository.revisions
374
if revisions is None:
375
raise errors.BzrCommandError('Repository %r does not support '
376
'access to raw revision texts')
378
b.repository.lock_read()
380
# TODO: jam 20060112 should cat-revision always output utf-8?
381
if revision_id is not None:
382
revision_id = osutils.safe_revision_id(revision_id, warn=False)
384
self.print_revision(revisions, revision_id)
385
except errors.NoSuchRevision:
386
msg = "The repository %s contains no revision %s." % (
387
b.repository.base, revision_id)
388
raise errors.BzrCommandError(msg)
389
elif revision is not None:
392
raise errors.BzrCommandError(
393
'You cannot specify a NULL revision.')
394
rev_id = rev.as_revision_id(b)
395
self.print_revision(revisions, rev_id)
397
b.repository.unlock()
400
class cmd_dump_btree(Command):
401
__doc__ = """Dump the contents of a btree index file to stdout.
403
PATH is a btree index file, it can be any URL. This includes things like
404
.bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
406
By default, the tuples stored in the index file will be displayed. With
407
--raw, we will uncompress the pages, but otherwise display the raw bytes
411
# TODO: Do we want to dump the internal nodes as well?
412
# TODO: It would be nice to be able to dump the un-parsed information,
413
# rather than only going through iter_all_entries. However, this is
414
# good enough for a start
416
encoding_type = 'exact'
417
takes_args = ['path']
418
takes_options = [Option('raw', help='Write the uncompressed bytes out,'
419
' rather than the parsed tuples.'),
422
def run(self, path, raw=False):
423
dirname, basename = osutils.split(path)
424
t = transport.get_transport(dirname)
426
self._dump_raw_bytes(t, basename)
428
self._dump_entries(t, basename)
430
def _get_index_and_bytes(self, trans, basename):
431
"""Create a BTreeGraphIndex and raw bytes."""
432
bt = btree_index.BTreeGraphIndex(trans, basename, None)
433
bytes = trans.get_bytes(basename)
434
bt._file = cStringIO.StringIO(bytes)
435
bt._size = len(bytes)
438
def _dump_raw_bytes(self, trans, basename):
441
# We need to parse at least the root node.
442
# This is because the first page of every row starts with an
443
# uncompressed header.
444
bt, bytes = self._get_index_and_bytes(trans, basename)
445
for page_idx, page_start in enumerate(xrange(0, len(bytes),
446
btree_index._PAGE_SIZE)):
447
page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
448
page_bytes = bytes[page_start:page_end]
450
self.outf.write('Root node:\n')
451
header_end, data = bt._parse_header_from_bytes(page_bytes)
452
self.outf.write(page_bytes[:header_end])
454
self.outf.write('\nPage %d\n' % (page_idx,))
455
decomp_bytes = zlib.decompress(page_bytes)
456
self.outf.write(decomp_bytes)
457
self.outf.write('\n')
459
def _dump_entries(self, trans, basename):
461
st = trans.stat(basename)
462
except errors.TransportNotPossible:
463
# We can't stat, so we'll fake it because we have to do the 'get()'
465
bt, _ = self._get_index_and_bytes(trans, basename)
467
bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
468
for node in bt.iter_all_entries():
469
# Node is made up of:
470
# (index, key, value, [references])
474
refs_as_tuples = None
476
refs_as_tuples = static_tuple.as_tuples(refs)
477
as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
478
self.outf.write('%s\n' % (as_tuple,))
216
b = WorkingTree.open_containing(u'.')[0].branch
218
# TODO: jam 20060112 should cat-revision always output utf-8?
219
if revision_id is not None:
220
revision_id = osutils.safe_revision_id(revision_id, warn=False)
221
self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
222
elif revision is not None:
225
raise errors.BzrCommandError('You cannot specify a NULL'
227
rev_id = rev.as_revision_id(b)
228
self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
481
231
class cmd_remove_tree(Command):
482
__doc__ = """Remove the working tree from a given branch/checkout.
232
"""Remove the working tree from a given branch/checkout.
484
234
Since a lightweight checkout is little more than a working tree
485
235
this will refuse to run against one.
487
237
To re-create the working tree, use "bzr checkout".
489
239
_see_also = ['checkout', 'working-trees']
490
takes_args = ['location*']
493
help='Remove the working tree even if it has '
494
'uncommitted or shelved changes.'),
497
def run(self, location_list, force=False):
498
if not location_list:
501
for location in location_list:
502
d = bzrdir.BzrDir.open(location)
505
working = d.open_workingtree()
506
except errors.NoWorkingTree:
507
raise errors.BzrCommandError("No working tree to remove")
508
except errors.NotLocalUrl:
509
raise errors.BzrCommandError("You cannot remove the working tree"
512
if (working.has_changes()):
513
raise errors.UncommittedChanges(working)
514
if working.get_shelf_manager().last_shelf() is not None:
515
raise errors.ShelvedChanges(working)
517
if working.user_url != working.branch.user_url:
518
raise errors.BzrCommandError("You cannot remove the working tree"
519
" from a lightweight checkout")
521
d.destroy_workingtree()
241
takes_args = ['location?']
243
def run(self, location='.'):
244
d = bzrdir.BzrDir.open(location)
247
working = d.open_workingtree()
248
except errors.NoWorkingTree:
249
raise errors.BzrCommandError("No working tree to remove")
250
except errors.NotLocalUrl:
251
raise errors.BzrCommandError("You cannot remove the working tree of a "
254
working_path = working.bzrdir.root_transport.base
255
branch_path = working.branch.bzrdir.root_transport.base
256
if working_path != branch_path:
257
raise errors.BzrCommandError("You cannot remove the working tree from "
258
"a lightweight checkout")
260
d.destroy_workingtree()
524
263
class cmd_revno(Command):
525
__doc__ = """Show current revision number.
264
"""Show current revision number.
527
266
This is equal to the number of revisions on this branch.
530
269
_see_also = ['info']
531
270
takes_args = ['location?']
533
Option('tree', help='Show revno of working tree'),
537
def run(self, tree=False, location=u'.'):
540
wt = WorkingTree.open_containing(location)[0]
541
self.add_cleanup(wt.lock_read().unlock)
542
except (errors.NoWorkingTree, errors.NotLocalUrl):
543
raise errors.NoWorkingTree(location)
544
revid = wt.last_revision()
546
revno_t = wt.branch.revision_id_to_dotted_revno(revid)
547
except errors.NoSuchRevision:
549
revno = ".".join(str(n) for n in revno_t)
551
b = Branch.open_containing(location)[0]
552
self.add_cleanup(b.lock_read().unlock)
555
self.outf.write(str(revno) + '\n')
273
def run(self, location=u'.'):
274
self.outf.write(str(Branch.open_containing(location)[0].revno()))
275
self.outf.write('\n')
558
278
class cmd_revision_info(Command):
559
__doc__ = """Show revision number and revision id for a given revision identifier.
279
"""Show revision number and revision id for a given revision identifier.
562
282
takes_args = ['revision_info*']
565
custom_help('directory',
566
help='Branch to examine, '
567
'rather than the one containing the working directory.'),
568
Option('tree', help='Show revno of working tree'),
283
takes_options = ['revision']
572
def run(self, revision=None, directory=u'.', tree=False,
573
revision_info_list=[]):
286
def run(self, revision=None, revision_info_list=[]):
576
wt = WorkingTree.open_containing(directory)[0]
578
self.add_cleanup(wt.lock_read().unlock)
579
except (errors.NoWorkingTree, errors.NotLocalUrl):
581
b = Branch.open_containing(directory)[0]
582
self.add_cleanup(b.lock_read().unlock)
584
289
if revision is not None:
585
revision_ids.extend(rev.as_revision_id(b) for rev in revision)
290
revs.extend(revision)
586
291
if revision_info_list is not None:
587
for rev_str in revision_info_list:
588
rev_spec = RevisionSpec.from_string(rev_str)
589
revision_ids.append(rev_spec.as_revision_id(b))
590
# No arguments supplied, default to the last revision
591
if len(revision_ids) == 0:
594
raise errors.NoWorkingTree(directory)
595
revision_ids.append(wt.last_revision())
597
revision_ids.append(b.last_revision())
601
for revision_id in revision_ids:
292
for rev in revision_info_list:
293
revs.append(RevisionSpec.from_string(rev))
295
b = Branch.open_containing(u'.')[0]
298
revs.append(RevisionSpec.from_string('-1'))
301
revision_id = rev.as_revision_id(b)
603
dotted_revno = b.revision_id_to_dotted_revno(revision_id)
604
revno = '.'.join(str(i) for i in dotted_revno)
303
revno = '%4d' % (b.revision_id_to_revno(revision_id))
605
304
except errors.NoSuchRevision:
607
maxlen = max(maxlen, len(revno))
608
revinfos.append([revno, revision_id])
612
self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
305
dotted_map = b.get_revision_id_to_revno_map()
306
revno = '.'.join(str(i) for i in dotted_map[revision_id])
307
print '%s %s' % (revno, revision_id)
615
310
class cmd_add(Command):
616
__doc__ = """Add specified files or directories.
311
"""Add specified files or directories.
618
313
In non-recursive mode, all the named items are added, regardless
619
314
of whether they were previously ignored. A warning is given if
860
556
into_existing = False
862
558
inv = tree.inventory
863
# 'fix' the case of a potential 'from'
864
from_id = tree.path2id(
865
tree.get_canonical_inventory_path(rel_names[0]))
559
from_id = tree.path2id(rel_names[0])
866
560
if (not osutils.lexists(names_list[0]) and
867
561
from_id and inv.get_file_kind(from_id) == "directory"):
868
562
into_existing = False
870
564
if into_existing:
871
565
# move into existing directory
872
# All entries reference existing inventory items, so fix them up
873
# for cicp file-systems.
874
rel_names = tree.get_canonical_inventory_paths(rel_names)
875
for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
877
self.outf.write("%s => %s\n" % (src, dest))
566
for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
567
self.outf.write("%s => %s\n" % pair)
879
569
if len(names_list) != 2:
880
570
raise errors.BzrCommandError('to mv multiple files the'
881
571
' destination must be a versioned'
884
# for cicp file-systems: the src references an existing inventory
886
src = tree.get_canonical_inventory_path(rel_names[0])
887
# Find the canonical version of the destination: In all cases, the
888
# parent of the target must be in the inventory, so we fetch the
889
# canonical version from there (we do not always *use* the
890
# canonicalized tail portion - we may be attempting to rename the
892
canon_dest = tree.get_canonical_inventory_path(rel_names[1])
893
dest_parent = osutils.dirname(canon_dest)
894
spec_tail = osutils.basename(rel_names[1])
895
# For a CICP file-system, we need to avoid creating 2 inventory
896
# entries that differ only by case. So regardless of the case
897
# we *want* to use (ie, specified by the user or the file-system),
898
# we must always choose to use the case of any existing inventory
899
# items. The only exception to this is when we are attempting a
900
# case-only rename (ie, canonical versions of src and dest are
902
dest_id = tree.path2id(canon_dest)
903
if dest_id is None or tree.path2id(src) == dest_id:
904
# No existing item we care about, so work out what case we
905
# are actually going to use.
907
# If 'after' is specified, the tail must refer to a file on disk.
909
dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
911
# pathjoin with an empty tail adds a slash, which breaks
913
dest_parent_fq = tree.basedir
915
dest_tail = osutils.canonical_relpath(
917
osutils.pathjoin(dest_parent_fq, spec_tail))
919
# not 'after', so case as specified is used
920
dest_tail = spec_tail
922
# Use the existing item so 'mv' fails with AlreadyVersioned.
923
dest_tail = os.path.basename(canon_dest)
924
dest = osutils.pathjoin(dest_parent, dest_tail)
925
mutter("attempting to move %s => %s", src, dest)
926
tree.rename_one(src, dest, after=after)
928
self.outf.write("%s => %s\n" % (src, dest))
573
tree.rename_one(rel_names[0], rel_names[1], after=after)
574
self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
931
577
class cmd_pull(Command):
932
__doc__ = """Turn this branch into a mirror of another branch.
578
"""Turn this branch into a mirror of another branch.
934
By default, this command only works on branches that have not diverged.
935
Branches are considered diverged if the destination branch's most recent
936
commit is one that has not been merged (directly or indirectly) into the
580
This command only works on branches that have not diverged. Branches are
581
considered diverged if the destination branch's most recent commit is one
582
that has not been merged (directly or indirectly) into the parent.
939
584
If branches have diverged, you can use 'bzr merge' to integrate the changes
940
585
from one into the other. Once one branch has merged, the other should
941
586
be able to pull it again.
943
If you want to replace your local changes and just want your branch to
944
match the remote one, use pull --overwrite. This will work even if the two
945
branches have diverged.
588
If you want to forget your local changes and just update your branch to
589
match the remote one, use pull --overwrite.
947
591
If there is no default location set, the first pull will set it. After
948
592
that, you can omit the location to use the default. To change the
1179
820
takes_args = ['from_location', 'to_location?']
1180
821
takes_options = ['revision', Option('hardlink',
1181
822
help='Hard-link working tree files where possible.'),
1183
help="Create a branch without a working-tree."),
1185
help="Switch the checkout in the current directory "
1186
"to the new branch."),
1187
823
Option('stacked',
1188
824
help='Create a stacked branch referring to the source branch. '
1189
825
'The new branch will depend on the availability of the source '
1190
826
'branch for all operations.'),
1191
Option('standalone',
1192
help='Do not use a shared repository, even if available.'),
1193
Option('use-existing-dir',
1194
help='By default branch will fail if the target'
1195
' directory exists, but does not already'
1196
' have a control directory. This flag will'
1197
' allow branch to proceed.'),
1199
help="Bind new branch to from location."),
1201
828
aliases = ['get', 'clone']
1203
830
def run(self, from_location, to_location=None, revision=None,
1204
hardlink=False, stacked=False, standalone=False, no_tree=False,
1205
use_existing_dir=False, switch=False, bind=False):
1206
from bzrlib import switch as _mod_switch
831
hardlink=False, stacked=False):
1207
832
from bzrlib.tag import _merge_tags_if_possible
835
elif len(revision) > 1:
836
raise errors.BzrCommandError(
837
'bzr branch --revision takes exactly 1 revision value')
1208
839
accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1210
revision = _get_one_revision('branch', revision)
1211
self.add_cleanup(br_from.lock_read().unlock)
1212
if revision is not None:
1213
revision_id = revision.as_revision_id(br_from)
1215
# FIXME - wt.last_revision, fallback to branch, fall back to
1216
# None or perhaps NULL_REVISION to mean copy nothing
1218
revision_id = br_from.last_revision()
1219
if to_location is None:
1220
to_location = urlutils.derive_to_location(from_location)
1221
to_transport = transport.get_transport(to_location)
1223
to_transport.mkdir('.')
1224
except errors.FileExists:
1225
if not use_existing_dir:
1226
raise errors.BzrCommandError('Target directory "%s" '
1227
'already exists.' % to_location)
843
if len(revision) == 1 and revision[0] is not None:
844
revision_id = revision[0].as_revision_id(br_from)
1230
bzrdir.BzrDir.open_from_transport(to_transport)
1231
except errors.NotBranchError:
1234
raise errors.AlreadyBranchError(to_location)
1235
except errors.NoSuchFile:
1236
raise errors.BzrCommandError('Parent of "%s" does not exist.'
1239
# preserve whatever source format we have.
1240
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1241
possible_transports=[to_transport],
1242
accelerator_tree=accelerator_tree,
1243
hardlink=hardlink, stacked=stacked,
1244
force_new_repo=standalone,
1245
create_tree_if_local=not no_tree,
1246
source_branch=br_from)
1247
branch = dir.open_branch()
1248
except errors.NoSuchRevision:
1249
to_transport.delete_tree('.')
1250
msg = "The branch %s has no revision %s." % (from_location,
1252
raise errors.BzrCommandError(msg)
1253
_merge_tags_if_possible(br_from, branch)
1254
# If the source branch is stacked, the new branch may
1255
# be stacked whether we asked for that explicitly or not.
1256
# We therefore need a try/except here and not just 'if stacked:'
1258
note('Created new stacked branch referring to %s.' %
1259
branch.get_stacked_on_url())
1260
except (errors.NotStacked, errors.UnstackableBranchFormat,
1261
errors.UnstackableRepositoryFormat), e:
1262
note('Branched %d revision(s).' % branch.revno())
1264
# Bind to the parent
1265
parent_branch = Branch.open(from_location)
1266
branch.bind(parent_branch)
1267
note('New branch bound to %s' % from_location)
1269
# Switch to the new branch
1270
wt, _ = WorkingTree.open_containing('.')
1271
_mod_switch.switch(wt.bzrdir, branch)
1272
note('Switched to branch: %s',
1273
urlutils.unescape_for_display(branch.base, 'utf-8'))
846
# FIXME - wt.last_revision, fallback to branch, fall back to
847
# None or perhaps NULL_REVISION to mean copy nothing
849
revision_id = br_from.last_revision()
850
if to_location is None:
851
to_location = urlutils.derive_to_location(from_location)
852
to_transport = transport.get_transport(to_location)
854
to_transport.mkdir('.')
855
except errors.FileExists:
856
raise errors.BzrCommandError('Target directory "%s" already'
857
' exists.' % to_location)
858
except errors.NoSuchFile:
859
raise errors.BzrCommandError('Parent of "%s" does not exist.'
862
# preserve whatever source format we have.
863
dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
864
possible_transports=[to_transport],
865
accelerator_tree=accelerator_tree,
866
hardlink=hardlink, stacked=stacked)
867
branch = dir.open_branch()
868
except errors.NoSuchRevision:
869
to_transport.delete_tree('.')
870
msg = "The branch %s has no revision %s." % (from_location,
872
raise errors.BzrCommandError(msg)
873
_merge_tags_if_possible(br_from, branch)
874
# If the source branch is stacked, the new branch may
875
# be stacked whether we asked for that explicitly or not.
876
# We therefore need a try/except here and not just 'if stacked:'
878
note('Created new stacked branch referring to %s.' %
879
branch.get_stacked_on_url())
880
except (errors.NotStacked, errors.UnstackableBranchFormat,
881
errors.UnstackableRepositoryFormat), e:
882
note('Branched %d revision(s).' % branch.revno())
1276
887
class cmd_checkout(Command):
1277
__doc__ = """Create a new checkout of an existing branch.
888
"""Create a new checkout of an existing branch.
1279
890
If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1280
891
the branch found in '.'. This is useful if you have removed the working tree
1281
892
or if it was never created - i.e. if you pushed the branch to its current
1282
893
location using SFTP.
1284
895
If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1285
896
be used. In other words, "checkout ../foo/bar" will attempt to create ./bar.
1286
897
If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1354
969
@display_command
1355
970
def run(self, dir=u'.'):
1356
971
tree = WorkingTree.open_containing(dir)[0]
1357
self.add_cleanup(tree.lock_read().unlock)
1358
new_inv = tree.inventory
1359
old_tree = tree.basis_tree()
1360
self.add_cleanup(old_tree.lock_read().unlock)
1361
old_inv = old_tree.inventory
1363
iterator = tree.iter_changes(old_tree, include_unchanged=True)
1364
for f, paths, c, v, p, n, k, e in iterator:
1365
if paths[0] == paths[1]:
1369
renames.append(paths)
1371
for old_name, new_name in renames:
1372
self.outf.write("%s => %s\n" % (old_name, new_name))
974
new_inv = tree.inventory
975
old_tree = tree.basis_tree()
978
old_inv = old_tree.inventory
979
renames = list(_mod_tree.find_renames(old_inv, new_inv))
981
for old_name, new_name in renames:
982
self.outf.write("%s => %s\n" % (old_name, new_name))
1375
989
class cmd_update(Command):
1376
__doc__ = """Update a tree to have the latest code committed to its branch.
990
"""Update a tree to have the latest code committed to its branch.
1378
992
This will perform a merge into the working tree, and may generate
1379
conflicts. If you have any local changes, you will still
993
conflicts. If you have any local changes, you will still
1380
994
need to commit them after the update for the update to be complete.
1382
If you want to discard your local changes, you can just do a
996
If you want to discard your local changes, you can just do a
1383
997
'bzr revert' instead of 'bzr commit' after the update.
1385
If the tree's branch is bound to a master branch, it will also update
1386
the branch from the master.
1389
1000
_see_also = ['pull', 'working-trees', 'status-flags']
1390
1001
takes_args = ['dir?']
1391
takes_options = ['revision']
1392
1002
aliases = ['up']
1394
def run(self, dir='.', revision=None):
1395
if revision is not None and len(revision) != 1:
1396
raise errors.BzrCommandError(
1397
"bzr update --revision takes exactly one revision")
1004
def run(self, dir='.'):
1398
1005
tree = WorkingTree.open_containing(dir)[0]
1399
branch = tree.branch
1400
1006
possible_transports = []
1401
master = branch.get_master_branch(
1007
master = tree.branch.get_master_branch(
1402
1008
possible_transports=possible_transports)
1403
1009
if master is not None:
1404
branch_location = master.base
1405
1010
tree.lock_write()
1407
branch_location = tree.branch.base
1408
1012
tree.lock_tree_write()
1409
self.add_cleanup(tree.unlock)
1410
# get rid of the final '/' and be ready for display
1411
branch_location = urlutils.unescape_for_display(
1412
branch_location.rstrip('/'),
1414
existing_pending_merges = tree.get_parent_ids()[1:]
1418
# may need to fetch data into a heavyweight checkout
1419
# XXX: this may take some time, maybe we should display a
1421
old_tip = branch.update(possible_transports)
1422
if revision is not None:
1423
revision_id = revision[0].as_revision_id(branch)
1425
revision_id = branch.last_revision()
1426
if revision_id == _mod_revision.ensure_null(tree.last_revision()):
1427
revno = branch.revision_id_to_dotted_revno(revision_id)
1428
note("Tree is up to date at revision %s of branch %s" %
1429
('.'.join(map(str, revno)), branch_location))
1431
view_info = _get_view_info_for_change_reporter(tree)
1432
change_reporter = delta._ChangeReporter(
1433
unversioned_filter=tree.is_ignored,
1434
view_info=view_info)
1014
existing_pending_merges = tree.get_parent_ids()[1:]
1015
last_rev = _mod_revision.ensure_null(tree.last_revision())
1016
if last_rev == _mod_revision.ensure_null(
1017
tree.branch.last_revision()):
1018
# may be up to date, check master too.
1019
if master is None or last_rev == _mod_revision.ensure_null(
1020
master.last_revision()):
1021
revno = tree.branch.revision_id_to_revno(last_rev)
1022
note("Tree is up to date at revision %d." % (revno,))
1436
1024
conflicts = tree.update(
1438
possible_transports=possible_transports,
1439
revision=revision_id,
1441
except errors.NoSuchRevision, e:
1442
raise errors.BzrCommandError(
1443
"branch has no revision %s\n"
1444
"bzr update --revision only works"
1445
" for a revision in the branch history"
1447
revno = tree.branch.revision_id_to_dotted_revno(
1448
_mod_revision.ensure_null(tree.last_revision()))
1449
note('Updated to revision %s of branch %s' %
1450
('.'.join(map(str, revno)), branch_location))
1451
parent_ids = tree.get_parent_ids()
1452
if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
1453
note('Your local commits will now show as pending merges with '
1454
"'bzr status', and can be committed with 'bzr commit'.")
1025
delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1026
possible_transports=possible_transports)
1027
revno = tree.branch.revision_id_to_revno(
1028
_mod_revision.ensure_null(tree.last_revision()))
1029
note('Updated to revision %d.' % (revno,))
1030
if tree.get_parent_ids()[1:] != existing_pending_merges:
1031
note('Your local commits will now show as pending merges with '
1032
"'bzr status', and can be committed with 'bzr commit'.")
1461
1041
class cmd_info(Command):
1462
__doc__ = """Show information about a working tree, branch or repository.
1042
"""Show information about a working tree, branch or repository.
1464
1044
This command will show all known locations and formats associated to the
1465
tree, branch or repository.
1467
In verbose mode, statistical information is included with each report.
1468
To see extended statistic information, use a verbosity level of 2 or
1469
higher by specifying the verbose option multiple times, e.g. -vv.
1045
tree, branch or repository. Statistical information is included with
1471
1048
Branches and working trees will also report any missing revisions.
1475
Display information on the format and related locations:
1479
Display the above together with extended format information and
1480
basic statistics (like the number of files in the working tree and
1481
number of revisions in the branch and repository):
1485
Display the above together with number of committers to the branch:
1489
1050
_see_also = ['revno', 'working-trees', 'repositories']
1490
1051
takes_args = ['location?']
1732
1296
"\nYou may supply --create-prefix to create all"
1733
1297
" leading parent directories."
1735
to_transport.create_prefix()
1299
_create_prefix(to_transport)
1738
a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1302
existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1739
1303
except errors.NotBranchError:
1740
1304
# really a NotBzrDir error...
1741
1305
create_branch = bzrdir.BzrDir.create_branch_convenience
1742
1306
branch = create_branch(to_transport.base, format=format,
1743
1307
possible_transports=[to_transport])
1744
a_bzrdir = branch.bzrdir
1746
1309
from bzrlib.transport.local import LocalTransport
1747
if a_bzrdir.has_branch():
1310
if existing_bzrdir.has_branch():
1748
1311
if (isinstance(to_transport, LocalTransport)
1749
and not a_bzrdir.has_workingtree()):
1312
and not existing_bzrdir.has_workingtree()):
1750
1313
raise errors.BranchExistsWithoutWorkingTree(location)
1751
1314
raise errors.AlreadyBranchError(location)
1752
branch = a_bzrdir.create_branch()
1753
a_bzrdir.create_workingtree()
1316
branch = existing_bzrdir.create_branch()
1317
existing_bzrdir.create_workingtree()
1754
1318
if append_revisions_only:
1756
1320
branch.set_append_revisions_only(True)
1757
1321
except errors.UpgradeRequired:
1758
1322
raise errors.BzrCommandError('This branch format cannot be set'
1759
' to append-revisions-only. Try --default.')
1323
' to append-revisions-only. Try --experimental-branch6')
1760
1324
if not is_quiet():
1761
from bzrlib.info import describe_layout, describe_format
1763
tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
1764
except (errors.NoWorkingTree, errors.NotLocalUrl):
1766
repository = branch.repository
1767
layout = describe_layout(repository, branch, tree).lower()
1768
format = describe_format(a_bzrdir, repository, branch, tree)
1769
self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1770
if repository.is_shared():
1771
#XXX: maybe this can be refactored into transport.path_or_url()
1772
url = repository.bzrdir.root_transport.external_url()
1774
url = urlutils.local_path_from_url(url)
1775
except errors.InvalidURL:
1777
self.outf.write("Using shared repository: %s\n" % url)
1325
from bzrlib.info import show_bzrdir_info
1326
show_bzrdir_info(bzrdir.BzrDir.open_containing_from_transport(
1327
to_transport)[0], verbose=0, outfile=self.outf)
1780
1330
class cmd_init_repository(Command):
1781
__doc__ = """Create a shared repository for branches to share storage space.
1331
"""Create a shared repository to hold branches.
1783
1333
New branches created under the repository directory will store their
1784
revisions in the repository, not in the branch directory. For branches
1785
with shared history, this reduces the amount of storage needed and
1786
speeds up the creation of new branches.
1334
revisions in the repository, not in the branch directory.
1788
If the --no-trees option is given then the branches in the repository
1789
will not have working trees by default. They will still exist as
1790
directories on disk, but they will not have separate copies of the
1791
files at a certain revision. This can be useful for repositories that
1792
store branches which are interacted with through checkouts or remote
1793
branches, such as on a server.
1336
If the --no-trees option is used then the branches in the repository
1337
will not have working trees by default.
1796
Create a shared repository holding just branches::
1340
Create a shared repositories holding just branches::
1798
1342
bzr init-repo --no-trees repo
1799
1343
bzr init repo/trunk
2080
1615
raise errors.BzrCommandError(msg)
2083
def _parse_levels(s):
2087
msg = "The levels argument must be an integer."
2088
raise errors.BzrCommandError(msg)
2091
1618
class cmd_log(Command):
2092
__doc__ = """Show historical log for a branch or subset of a branch.
2094
log is bzr's default tool for exploring the history of a branch.
2095
The branch to use is taken from the first parameter. If no parameters
2096
are given, the branch containing the working directory is logged.
2097
Here are some simple examples::
2099
bzr log log the current branch
2100
bzr log foo.py log a file in its branch
2101
bzr log http://server/branch log a branch on a server
2103
The filtering, ordering and information shown for each revision can
2104
be controlled as explained below. By default, all revisions are
2105
shown sorted (topologically) so that newer revisions appear before
2106
older ones and descendants always appear before ancestors. If displayed,
2107
merged revisions are shown indented under the revision in which they
2112
The log format controls how information about each revision is
2113
displayed. The standard log formats are called ``long``, ``short``
2114
and ``line``. The default is long. See ``bzr help log-formats``
2115
for more details on log formats.
2117
The following options can be used to control what information is
2120
-l N display a maximum of N revisions
2121
-n N display N levels of revisions (0 for all, 1 for collapsed)
2122
-v display a status summary (delta) for each revision
2123
-p display a diff (patch) for each revision
2124
--show-ids display revision-ids (and file-ids), not just revnos
2126
Note that the default number of levels to display is a function of the
2127
log format. If the -n option is not used, the standard log formats show
2128
just the top level (mainline).
2130
Status summaries are shown using status flags like A, M, etc. To see
2131
the changes explained using words like ``added`` and ``modified``
2132
instead, use the -vv option.
2136
To display revisions from oldest to newest, use the --forward option.
2137
In most cases, using this option will have little impact on the total
2138
time taken to produce a log, though --forward does not incrementally
2139
display revisions like --reverse does when it can.
2141
:Revision filtering:
2143
The -r option can be used to specify what revision or range of revisions
2144
to filter against. The various forms are shown below::
2146
-rX display revision X
2147
-rX.. display revision X and later
2148
-r..Y display up to and including revision Y
2149
-rX..Y display from X to Y inclusive
2151
See ``bzr help revisionspec`` for details on how to specify X and Y.
2152
Some common examples are given below::
2154
-r-1 show just the tip
2155
-r-10.. show the last 10 mainline revisions
2156
-rsubmit:.. show what's new on this branch
2157
-rancestor:path.. show changes since the common ancestor of this
2158
branch and the one at location path
2159
-rdate:yesterday.. show changes since yesterday
2161
When logging a range of revisions using -rX..Y, log starts at
2162
revision Y and searches back in history through the primary
2163
("left-hand") parents until it finds X. When logging just the
2164
top level (using -n1), an error is reported if X is not found
2165
along the way. If multi-level logging is used (-n0), X may be
2166
a nested merge revision and the log will be truncated accordingly.
2170
If parameters are given and the first one is not a branch, the log
2171
will be filtered to show only those revisions that changed the
2172
nominated files or directories.
2174
Filenames are interpreted within their historical context. To log a
2175
deleted file, specify a revision range so that the file existed at
2176
the end or start of the range.
2178
Historical context is also important when interpreting pathnames of
2179
renamed files/directories. Consider the following example:
2181
* revision 1: add tutorial.txt
2182
* revision 2: modify tutorial.txt
2183
* revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
2187
* ``bzr log guide.txt`` will log the file added in revision 1
2189
* ``bzr log tutorial.txt`` will log the new file added in revision 3
2191
* ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2192
the original file in revision 2.
2194
* ``bzr log -r2 -p guide.txt`` will display an error message as there
2195
was no file called guide.txt in revision 2.
2197
Renames are always followed by log. By design, there is no need to
2198
explicitly ask for this (and no way to stop logging a file back
2199
until it was last renamed).
2203
The --message option can be used for finding revisions that match a
2204
regular expression in a commit message.
2208
GUI tools and IDEs are often better at exploring history than command
2209
line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2210
bzr-explorer shell, or the Loggerhead web interface. See the Plugin
2211
Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2212
<http://wiki.bazaar.canonical.com/IDEIntegration>.
2214
You may find it useful to add the aliases below to ``bazaar.conf``::
2218
top = log -l10 --line
2221
``bzr tip`` will then show the latest revision while ``bzr top``
2222
will show the last 10 mainline revisions. To see the details of a
2223
particular revision X, ``bzr show -rX``.
2225
If you are interested in looking deeper into a particular merge X,
2226
use ``bzr log -n0 -rX``.
2228
``bzr log -v`` on a branch with lots of history is currently
2229
very slow. A fix for this issue is currently under development.
2230
With or without that fix, it is recommended that a revision range
2231
be given when using the -v option.
2233
bzr has a generic full-text matching plugin, bzr-search, that can be
2234
used to find revisions matching user names, commit messages, etc.
2235
Among other features, this plugin can find all revisions containing
2236
a list of words but not others.
2238
When exploring non-mainline history on large projects with deep
2239
history, the performance of log can be greatly improved by installing
2240
the historycache plugin. This plugin buffers historical information
2241
trading disk space for faster speed.
1619
"""Show log of a branch, file, or directory.
1621
By default show the log of the branch containing the working directory.
1623
To request a range of logs, you can use the command -r begin..end
1624
-r revision requests a specific revision, -r ..end or -r begin.. are
1628
Log the current branch::
1636
Log the last 10 revisions of a branch::
1638
bzr log -r -10.. http://server/branch
2243
takes_args = ['file*']
2244
_see_also = ['log-formats', 'revisionspec']
1641
# TODO: Make --revision support uuid: and hash: [future tag:] notation.
1643
takes_args = ['location?']
2245
1644
takes_options = [
2246
1645
Option('forward',
2247
1646
help='Show from oldest to newest.'),
1649
help='Display timezone as local, original, or utc.'),
2249
1650
custom_help('verbose',
2250
1651
help='Show files changed in each revision.'),
2254
type=bzrlib.option._parse_revision_str,
2256
help='Show just the specified revision.'
2257
' See also "help revisionspec".'),
2259
RegistryOption('authors',
2260
'What names to list as authors - first, all or committer.',
2262
lazy_registry=('bzrlib.log', 'author_list_registry'),
2266
help='Number of levels to display - 0 for all, 1 for flat.',
2268
type=_parse_levels),
2269
1655
Option('message',
2270
1656
short_name='m',
2271
1657
help='Show revisions whose message matches this '
2360
1703
dir, relpath = bzrdir.BzrDir.open_containing(location)
2361
1704
b = dir.open_branch()
2362
self.add_cleanup(b.lock_read().unlock)
2363
rev1, rev2 = _get_revision_range(revision, b, self.name())
2365
# Decide on the type of delta & diff filtering to use
2366
# TODO: add an --all-files option to make this configurable & consistent
2374
diff_type = 'partial'
2378
# Build the log formatter
2379
if log_format is None:
2380
log_format = log.log_formatter_registry.get_default(b)
2381
# Make a non-encoding output to include the diffs - bug 328007
2382
unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2383
lf = log_format(show_ids=show_ids, to_file=self.outf,
2384
to_exact_file=unencoded_output,
2385
show_timezone=timezone,
2386
delta_format=get_verbosity_level(),
2388
show_advice=levels is None,
2389
author_list_handler=authors)
2391
# Choose the algorithm for doing the logging. It's annoying
2392
# having multiple code paths like this but necessary until
2393
# the underlying repository format is faster at generating
2394
# deltas or can provide everything we need from the indices.
2395
# The default algorithm - match-using-deltas - works for
2396
# multiple files and directories and is faster for small
2397
# amounts of history (200 revisions say). However, it's too
2398
# slow for logging a single file in a repository with deep
2399
# history, i.e. > 10K revisions. In the spirit of "do no
2400
# evil when adding features", we continue to use the
2401
# original algorithm - per-file-graph - for the "single
2402
# file that isn't a directory without showing a delta" case.
2403
partial_history = revision and b.repository._format.supports_chks
2404
match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2405
or delta_type or partial_history)
2407
# Build the LogRequest and execute it
2408
if len(file_ids) == 0:
2410
rqst = make_log_request_dict(
2411
direction=direction, specific_fileids=file_ids,
2412
start_revision=rev1, end_revision=rev2, limit=limit,
2413
message_search=message, delta_type=delta_type,
2414
diff_type=diff_type, _match_using_deltas=match_using_deltas,
2415
exclude_common_ancestry=exclude_common_ancestry,
2417
Logger(b, rqst).show(lf)
2420
def _get_revision_range(revisionspec_list, branch, command_name):
2421
"""Take the input of a revision option and turn it into a revision range.
2423
It returns RevisionInfo objects which can be used to obtain the rev_id's
2424
of the desired revisions. It does some user input validations.
2426
if revisionspec_list is None:
2429
elif len(revisionspec_list) == 1:
2430
rev1 = rev2 = revisionspec_list[0].in_history(branch)
2431
elif len(revisionspec_list) == 2:
2432
start_spec = revisionspec_list[0]
2433
end_spec = revisionspec_list[1]
2434
if end_spec.get_branch() != start_spec.get_branch():
2435
# b is taken from revision[0].get_branch(), and
2436
# show_log will use its revision_history. Having
2437
# different branches will lead to weird behaviors.
2438
raise errors.BzrCommandError(
2439
"bzr %s doesn't accept two revisions in different"
2440
" branches." % command_name)
2441
if start_spec.spec is None:
2442
# Avoid loading all the history.
2443
rev1 = RevisionInfo(branch, None, None)
2445
rev1 = start_spec.in_history(branch)
2446
# Avoid loading all of history when we know a missing
2447
# end of range means the last revision ...
2448
if end_spec.spec is None:
2449
last_revno, last_revision_id = branch.last_revision_info()
2450
rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2452
rev2 = end_spec.in_history(branch)
2454
raise errors.BzrCommandError(
2455
'bzr %s --revision takes one or two values.' % command_name)
2459
def _revision_range_to_revid_range(revision_range):
2462
if revision_range[0] is not None:
2463
rev_id1 = revision_range[0].rev_id
2464
if revision_range[1] is not None:
2465
rev_id2 = revision_range[1].rev_id
2466
return rev_id1, rev_id2
1708
if revision is None:
1711
elif len(revision) == 1:
1712
rev1 = rev2 = revision[0].in_history(b)
1713
elif len(revision) == 2:
1714
if revision[1].get_branch() != revision[0].get_branch():
1715
# b is taken from revision[0].get_branch(), and
1716
# show_log will use its revision_history. Having
1717
# different branches will lead to weird behaviors.
1718
raise errors.BzrCommandError(
1719
"Log doesn't accept two revisions in different"
1721
rev1 = revision[0].in_history(b)
1722
rev2 = revision[1].in_history(b)
1724
raise errors.BzrCommandError(
1725
'bzr log --revision takes one or two values.')
1727
if log_format is None:
1728
log_format = log.log_formatter_registry.get_default(b)
1730
lf = log_format(show_ids=show_ids, to_file=self.outf,
1731
show_timezone=timezone)
1737
direction=direction,
1738
start_revision=rev1,
2468
1746
def get_log_format(long=False, short=False, line=False, default='long'):
2469
1747
log_format = default
2540
1816
if path is None:
2544
1821
raise errors.BzrCommandError('cannot specify both --from-root'
2547
tree, branch, relpath = \
2548
_open_directory_or_containing_tree_or_branch(fs_path, directory)
2550
# Calculate the prefix to use
1825
tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2554
prefix = relpath + '/'
2555
elif fs_path != '.' and not fs_path.endswith('/'):
2556
prefix = fs_path + '/'
2558
if revision is not None or tree is None:
2559
tree = _get_one_revision_tree('ls', revision, branch=branch)
2562
if isinstance(tree, WorkingTree) and tree.supports_views():
2563
view_files = tree.views.lookup_view()
2566
view_str = views.view_display_str(view_files)
2567
note("Ignoring files outside view. View is %s" % view_str)
2569
self.add_cleanup(tree.lock_read().unlock)
2570
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2571
from_dir=relpath, recursive=recursive):
2572
# Apply additional masking
2573
if not all and not selection[fc]:
2575
if kind is not None and fkind != kind:
2580
fullpath = osutils.pathjoin(relpath, fp)
2583
views.check_path_in_view(tree, fullpath)
2584
except errors.FileOutsideView:
2589
fp = osutils.pathjoin(prefix, fp)
2590
kindch = entry.kind_character()
2591
outstring = fp + kindch
2592
ui.ui_factory.clear_term()
2594
outstring = '%-8s %s' % (fc, outstring)
2595
if show_ids and fid is not None:
2596
outstring = "%-50s %s" % (outstring, fid)
2597
self.outf.write(outstring + '\n')
2599
self.outf.write(fp + '\0')
2602
self.outf.write(fid)
2603
self.outf.write('\0')
2611
self.outf.write('%-50s %s\n' % (outstring, my_id))
2613
self.outf.write(outstring + '\n')
1831
if revision is not None:
1832
tree = branch.repository.revision_tree(
1833
revision[0].as_revision_id(branch))
1835
tree = branch.basis_tree()
1839
for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1840
if fp.startswith(relpath):
1841
fp = osutils.pathjoin(prefix, fp[len(relpath):])
1842
if non_recursive and '/' in fp:
1844
if not all and not selection[fc]:
1846
if kind is not None and fkind != kind:
1849
kindch = entry.kind_character()
1850
outstring = '%-8s %s%s' % (fc, fp, kindch)
1851
if show_ids and fid is not None:
1852
outstring = "%-50s %s" % (outstring, fid)
1853
self.outf.write(outstring + '\n')
1855
self.outf.write(fp + '\0')
1858
self.outf.write(fid)
1859
self.outf.write('\0')
1867
self.outf.write('%-50s %s\n' % (fp, my_id))
1869
self.outf.write(fp + '\n')
2616
1874
class cmd_unknowns(Command):
2617
__doc__ = """List unknown files.
1875
"""List unknown files.
2621
1879
_see_also = ['ls']
2622
takes_options = ['directory']
2624
1881
@display_command
2625
def run(self, directory=u'.'):
2626
for f in WorkingTree.open_containing(directory)[0].unknowns():
1883
for f in WorkingTree.open_containing(u'.')[0].unknowns():
2627
1884
self.outf.write(osutils.quotefn(f) + '\n')
2630
1887
class cmd_ignore(Command):
2631
__doc__ = """Ignore specified files or patterns.
1888
"""Ignore specified files or patterns.
2633
1890
See ``bzr help patterns`` for details on the syntax of patterns.
2635
If a .bzrignore file does not exist, the ignore command
2636
will create one and add the specified files or patterns to the newly
2637
created file. The ignore command will also automatically add the
2638
.bzrignore file to be versioned. Creating a .bzrignore file without
2639
the use of the ignore command will require an explicit add command.
2641
1892
To remove patterns from the ignore list, edit the .bzrignore file.
2642
1893
After adding, editing or deleting that file either indirectly by
2643
1894
using this command or directly by using an editor, be sure to commit
2646
Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2647
the global ignore file can be found in the application data directory as
2648
C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
2649
Global ignores are not touched by this command. The global ignore file
2650
can be edited directly using an editor.
2652
Patterns prefixed with '!' are exceptions to ignore patterns and take
2653
precedence over regular ignores. Such exceptions are used to specify
2654
files that should be versioned which would otherwise be ignored.
2656
Patterns prefixed with '!!' act as regular ignore patterns, but have
2657
precedence over the '!' exception patterns.
2659
Note: ignore patterns containing shell wildcards must be quoted from
1897
Note: ignore patterns containing shell wildcards must be quoted from
2660
1898
the shell on Unix.
2820
2037
================= =========================
2822
2039
takes_args = ['dest', 'branch_or_subdir?']
2823
takes_options = ['directory',
2824
2041
Option('format',
2825
2042
help="Type of file to export to.",
2828
Option('filters', help='Apply content filters to export the '
2829
'convenient form.'),
2832
2047
help="Name of the root directory inside the exported file."),
2833
Option('per-file-timestamps',
2834
help='Set modification time of files to that of the last '
2835
'revision in which it was changed.'),
2837
2049
def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2838
root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2839
2051
from bzrlib.export import export
2841
2053
if branch_or_subdir is None:
2842
tree = WorkingTree.open_containing(directory)[0]
2054
tree = WorkingTree.open_containing(u'.')[0]
2843
2055
b = tree.branch
2846
2058
b, subdir = Branch.open_containing(branch_or_subdir)
2849
rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2060
if revision is None:
2061
# should be tree.last_revision FIXME
2062
rev_id = b.last_revision()
2064
if len(revision) != 1:
2065
raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2066
rev_id = revision[0].as_revision_id(b)
2067
t = b.repository.revision_tree(rev_id)
2851
export(rev_tree, dest, format, root, subdir, filtered=filters,
2852
per_file_timestamps=per_file_timestamps)
2069
export(t, dest, format, root, subdir)
2853
2070
except errors.NoSuchExportFormat, e:
2854
2071
raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2857
2074
class cmd_cat(Command):
2858
__doc__ = """Write the contents of a file as of a given revision to standard output.
2075
"""Write the contents of a file as of a given revision to standard output.
2860
2077
If no revision is nominated, the last revision is used.
2862
2079
Note: Take care to redirect standard output when using this command on a
2866
2083
_see_also = ['ls']
2867
takes_options = ['directory',
2868
2085
Option('name-from-revision', help='The path name in the old tree.'),
2869
Option('filters', help='Apply content filters to display the '
2870
'convenience form.'),
2873
2088
takes_args = ['filename']
2874
2089
encoding_type = 'exact'
2876
2091
@display_command
2877
def run(self, filename, revision=None, name_from_revision=False,
2878
filters=False, directory=None):
2092
def run(self, filename, revision=None, name_from_revision=False):
2879
2093
if revision is not None and len(revision) != 1:
2880
2094
raise errors.BzrCommandError("bzr cat --revision takes exactly"
2881
2095
" one revision specifier")
2882
2096
tree, branch, relpath = \
2883
_open_directory_or_containing_tree_or_branch(filename, directory)
2884
self.add_cleanup(branch.lock_read().unlock)
2885
return self._run(tree, branch, relpath, filename, revision,
2886
name_from_revision, filters)
2097
bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2100
return self._run(tree, branch, relpath, filename, revision,
2888
def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2105
def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2890
2106
if tree is None:
2891
2107
tree = b.basis_tree()
2892
rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2893
self.add_cleanup(rev_tree.lock_read().unlock)
2108
if revision is None:
2109
revision_id = b.last_revision()
2111
revision_id = revision[0].as_revision_id(b)
2113
cur_file_id = tree.path2id(relpath)
2114
rev_tree = b.repository.revision_tree(revision_id)
2895
2115
old_file_id = rev_tree.path2id(relpath)
2897
2117
if name_from_revision:
2898
# Try in revision if requested
2899
2118
if old_file_id is None:
2900
raise errors.BzrCommandError(
2901
"%r is not present in revision %s" % (
2902
filename, rev_tree.get_revision_id()))
2119
raise errors.BzrCommandError("%r is not present in revision %s"
2120
% (filename, revision_id))
2904
2122
content = rev_tree.get_file_text(old_file_id)
2906
cur_file_id = tree.path2id(relpath)
2908
if cur_file_id is not None:
2909
# Then try with the actual file id
2911
content = rev_tree.get_file_text(cur_file_id)
2913
except errors.NoSuchId:
2914
# The actual file id didn't exist at that time
2916
if not found and old_file_id is not None:
2917
# Finally try with the old file id
2918
content = rev_tree.get_file_text(old_file_id)
2921
# Can't be found anywhere
2922
raise errors.BzrCommandError(
2923
"%r is not present in revision %s" % (
2924
filename, rev_tree.get_revision_id()))
2926
from bzrlib.filters import (
2927
ContentFilterContext,
2928
filtered_output_bytes,
2930
filters = rev_tree._content_filter_stack(relpath)
2931
chunks = content.splitlines(True)
2932
content = filtered_output_bytes(chunks, filters,
2933
ContentFilterContext(relpath, rev_tree))
2935
self.outf.writelines(content)
2938
self.outf.write(content)
2123
elif cur_file_id is not None:
2124
content = rev_tree.get_file_text(cur_file_id)
2125
elif old_file_id is not None:
2126
content = rev_tree.get_file_text(old_file_id)
2128
raise errors.BzrCommandError("%r is not present in revision %s" %
2129
(filename, revision_id))
2130
self.outf.write(content)
2941
2133
class cmd_local_time_offset(Command):
2942
__doc__ = """Show the offset in seconds from GMT to local time."""
2134
"""Show the offset in seconds from GMT to local time."""
2944
2136
@display_command
2946
self.outf.write("%s\n" % osutils.local_time_offset())
2138
print osutils.local_time_offset()
2950
2142
class cmd_commit(Command):
2951
__doc__ = """Commit changes into a new revision.
2953
An explanatory message needs to be given for each commit. This is
2954
often done by using the --message option (getting the message from the
2955
command line) or by using the --file option (getting the message from
2956
a file). If neither of these options is given, an editor is opened for
2957
the user to enter the message. To see the changed files in the
2958
boilerplate text loaded into the editor, use the --show-diff option.
2960
By default, the entire tree is committed and the person doing the
2961
commit is assumed to be the author. These defaults can be overridden
2966
If selected files are specified, only changes to those files are
2967
committed. If a directory is specified then the directory and
2968
everything within it is committed.
2970
When excludes are given, they take precedence over selected files.
2971
For example, to commit only changes within foo, but not changes
2974
bzr commit foo -x foo/bar
2976
A selective commit after a merge is not yet supported.
2980
If the author of the change is not the same person as the committer,
2981
you can specify the author's name using the --author option. The
2982
name should be in the same format as a committer-id, e.g.
2983
"John Doe <jdoe@example.com>". If there is more than one author of
2984
the change you can specify the option multiple times, once for each
2989
A common mistake is to forget to add a new file or directory before
2990
running the commit command. The --strict option checks for unknown
2991
files and aborts the commit if any are found. More advanced pre-commit
2992
checks can be implemented by defining hooks. See ``bzr help hooks``
2997
If you accidentially commit the wrong changes or make a spelling
2998
mistake in the commit message say, you can use the uncommit command
2999
to undo it. See ``bzr help uncommit`` for details.
3001
Hooks can also be configured to run after a commit. This allows you
3002
to trigger updates to external systems like bug trackers. The --fixes
3003
option can be used to record the association between a revision and
3004
one or more bugs. See ``bzr help bugs`` for details.
3006
A selective commit may fail in some cases where the committed
3007
tree would be invalid. Consider::
3012
bzr commit foo -m "committing foo"
3013
bzr mv foo/bar foo/baz
3016
bzr commit foo/bar -m "committing bar but not baz"
3018
In the example above, the last commit will fail by design. This gives
3019
the user the opportunity to decide whether they want to commit the
3020
rename at the same time, separately first, or not at all. (As a general
3021
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2143
"""Commit changes into a new revision.
2145
If no arguments are given, the entire tree is committed.
2147
If selected files are specified, only changes to those files are
2148
committed. If a directory is specified then the directory and everything
2149
within it is committed.
2151
When excludes are given, they take precedence over selected files.
2152
For example, too commit only changes within foo, but not changes within
2155
bzr commit foo -x foo/bar
2157
If author of the change is not the same person as the committer, you can
2158
specify the author's name using the --author option. The name should be
2159
in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2161
A selected-file commit may fail in some cases where the committed
2162
tree would be invalid. Consider::
2167
bzr commit foo -m "committing foo"
2168
bzr mv foo/bar foo/baz
2171
bzr commit foo/bar -m "committing bar but not baz"
2173
In the example above, the last commit will fail by design. This gives
2174
the user the opportunity to decide whether they want to commit the
2175
rename at the same time, separately first, or not at all. (As a general
2176
rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2178
Note: A selected-file commit after a merge is not yet supported.
3023
2180
# TODO: Run hooks on tree to-be-committed, and after commit.
3127
2274
if fixes is None:
3129
bug_property = bugtracker.encode_fixes_bug_urls(
3130
self._iter_bug_fix_urls(fixes, tree.branch))
2276
bug_property = self._get_bug_fix_properties(fixes, tree.branch)
3131
2277
if bug_property:
3132
2278
properties['bugs'] = bug_property
3134
2280
if local and not tree.branch.get_bound_location():
3135
2281
raise errors.LocalRequiresBoundBranch()
3137
if message is not None:
3139
file_exists = osutils.lexists(message)
3140
except UnicodeError:
3141
# The commit message contains unicode characters that can't be
3142
# represented in the filesystem encoding, so that can't be a
3147
'The commit message is a file name: "%(f)s".\n'
3148
'(use --file "%(f)s" to take commit message from that file)'
3150
ui.ui_factory.show_warning(warning_msg)
3152
message = message.replace('\r\n', '\n')
3153
message = message.replace('\r', '\n')
3155
raise errors.BzrCommandError(
3156
"please specify either --message or --file")
3158
2283
def get_message(commit_obj):
3159
2284
"""Callback to get commit message"""
3161
f = codecs.open(file, 'rt', osutils.get_user_encoding())
3163
my_message = f.read()
3166
elif message is not None:
3167
my_message = message
3169
# No message supplied: make one up.
3170
# text is the status of the tree
3171
text = make_commit_message_template_encoded(tree,
2285
my_message = message
2286
if my_message is None and not file:
2287
t = make_commit_message_template_encoded(tree,
3172
2288
selected_list, diff=show_diff,
3173
output_encoding=osutils.get_user_encoding())
3174
# start_message is the template generated from hooks
3175
# XXX: Warning - looks like hooks return unicode,
3176
# make_commit_message_template_encoded returns user encoding.
3177
# We probably want to be using edit_commit_message instead to
3179
start_message = generate_commit_message_template(commit_obj)
3180
my_message = edit_commit_message_encoded(text,
3181
start_message=start_message)
2289
output_encoding=bzrlib.user_encoding)
2290
my_message = edit_commit_message_encoded(t)
3182
2291
if my_message is None:
3183
2292
raise errors.BzrCommandError("please specify a commit"
3184
2293
" message with either --message or --file")
2294
elif my_message and file:
2295
raise errors.BzrCommandError(
2296
"please specify either --message or --file")
2298
my_message = codecs.open(file, 'rt',
2299
bzrlib.user_encoding).read()
3185
2300
if my_message == "":
3186
2301
raise errors.BzrCommandError("empty commit message specified")
3187
2302
return my_message
3189
# The API permits a commit with a filter of [] to mean 'select nothing'
3190
# but the command line should not do that.
3191
if not selected_list:
3192
selected_list = None
3194
2305
tree.commit(message_callback=get_message,
3195
2306
specific_files=selected_list,
3196
2307
allow_pointless=unchanged, strict=strict, local=local,
3197
2308
reporter=None, verbose=verbose, revprops=properties,
3198
authors=author, timestamp=commit_stamp,
3200
2310
exclude=safe_relpath_files(tree, exclude))
3201
2311
except PointlessCommit:
3202
raise errors.BzrCommandError("No changes to commit."
3203
" Use --unchanged to commit anyhow.")
2312
# FIXME: This should really happen before the file is read in;
2313
# perhaps prepare the commit; get the message; then actually commit
2314
raise errors.BzrCommandError("no changes to commit."
2315
" use --unchanged to commit anyhow")
3204
2316
except ConflictsInTree:
3205
2317
raise errors.BzrCommandError('Conflicts detected in working '
3206
2318
'tree. Use "bzr conflicts" to list, "bzr resolve FILE" to'
3562
2647
short_name='x',
3563
2648
help='Exclude tests that match this regular'
3564
2649
' expression.'),
3566
help='Output test progress via subunit.'),
3567
2650
Option('strict', help='Fail on missing dependencies or '
3568
2651
'known failures.'),
3569
2652
Option('load-list', type=str, argname='TESTLISTFILE',
3570
2653
help='Load a test id list from a text file.'),
3571
2654
ListOption('debugflag', type=str, short_name='E',
3572
2655
help='Turn on a selftest debug flag.'),
3573
ListOption('starting-with', type=str, argname='TESTID',
3574
param_name='starting_with', short_name='s',
3576
'Load only the tests starting with TESTID.'),
2656
Option('starting-with', type=str, argname='TESTID',
2658
help='Load only the tests starting with TESTID.'),
3578
2660
encoding_type = 'replace'
3581
Command.__init__(self)
3582
self.additional_selftest_args = {}
3584
2662
def run(self, testspecs_list=None, verbose=False, one=False,
3585
2663
transport=None, benchmark=None,
2664
lsprof_timed=None, cache_dir=None,
3587
2665
first=False, list_only=False,
3588
2666
randomize=None, exclude=None, strict=False,
3589
load_list=None, debugflag=None, starting_with=None, subunit=False,
3590
parallel=None, lsprof_tests=False):
2667
load_list=None, debugflag=None, starting_with=None):
3591
2669
from bzrlib.tests import selftest
2670
import bzrlib.benchmarks as benchmarks
2671
from bzrlib.benchmarks import tree_creator
3593
2673
# Make deprecation warnings visible, unless -Werror is set
3594
2674
symbol_versioning.activate_deprecation_warnings(override=False)
2676
if cache_dir is not None:
2677
tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2679
print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2680
print ' %s (%s python%s)' % (
2682
bzrlib.version_string,
2683
bzrlib._format_version_tuple(sys.version_info),
3596
2686
if testspecs_list is not None:
3597
2687
pattern = '|'.join(testspecs_list)
3602
from bzrlib.tests import SubUnitBzrRunner
3604
raise errors.BzrCommandError("subunit not available. subunit "
3605
"needs to be installed to use --subunit.")
3606
self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
3607
# On Windows, disable automatic conversion of '\n' to '\r\n' in
3608
# stdout, which would corrupt the subunit stream.
3609
# FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3610
# following code can be deleted when it's sufficiently deployed
3611
# -- vila/mgz 20100514
3612
if (sys.platform == "win32"
3613
and getattr(sys.stdout, 'fileno', None) is not None):
3615
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
3617
self.additional_selftest_args.setdefault(
3618
'suite_decorators', []).append(parallel)
3620
raise errors.BzrCommandError(
3621
"--benchmark is no longer supported from bzr 2.2; "
3622
"use bzr-usertest instead")
3623
test_suite_factory = None
3624
selftest_kwargs = {"verbose": verbose,
3626
"stop_on_failure": one,
3627
"transport": transport,
3628
"test_suite_factory": test_suite_factory,
3629
"lsprof_timed": lsprof_timed,
3630
"lsprof_tests": lsprof_tests,
3631
"matching_tests_first": first,
3632
"list_only": list_only,
3633
"random_seed": randomize,
3634
"exclude_pattern": exclude,
3636
"load_list": load_list,
3637
"debug_flags": debugflag,
3638
"starting_with": starting_with
3640
selftest_kwargs.update(self.additional_selftest_args)
3641
result = selftest(**selftest_kwargs)
2691
test_suite_factory = benchmarks.test_suite
2692
# Unless user explicitly asks for quiet, be verbose in benchmarks
2693
verbose = not is_quiet()
2694
# TODO: should possibly lock the history file...
2695
benchfile = open(".perf_history", "at", buffering=1)
2697
test_suite_factory = None
2700
result = selftest(verbose=verbose,
2702
stop_on_failure=one,
2703
transport=transport,
2704
test_suite_factory=test_suite_factory,
2705
lsprof_timed=lsprof_timed,
2706
bench_history=benchfile,
2707
matching_tests_first=first,
2708
list_only=list_only,
2709
random_seed=randomize,
2710
exclude_pattern=exclude,
2712
load_list=load_list,
2713
debug_flags=debugflag,
2714
starting_with=starting_with,
2717
if benchfile is not None:
2720
note('tests passed')
2722
note('tests failed')
3642
2723
return int(not result)
3645
2726
class cmd_version(Command):
3646
__doc__ = """Show version of bzr."""
2727
"""Show version of bzr."""
3648
2729
encoding_type = 'replace'
3649
2730
takes_options = [
3808
2879
allow_pending = True
3809
2880
verified = 'inapplicable'
3810
2881
tree = WorkingTree.open_containing(directory)[0]
2882
change_reporter = delta._ChangeReporter(
2883
unversioned_filter=tree.is_ignored)
3813
basis_tree = tree.revision_tree(tree.last_revision())
3814
except errors.NoSuchRevision:
3815
basis_tree = tree.basis_tree()
3817
# die as quickly as possible if there are uncommitted changes
3819
if tree.has_changes():
3820
raise errors.UncommittedChanges(tree)
3822
view_info = _get_view_info_for_change_reporter(tree)
3823
change_reporter = delta._ChangeReporter(
3824
unversioned_filter=tree.is_ignored, view_info=view_info)
3825
pb = ui.ui_factory.nested_progress_bar()
3826
self.add_cleanup(pb.finished)
3827
self.add_cleanup(tree.lock_write().unlock)
3828
if location is not None:
3830
mergeable = bundle.read_mergeable_from_url(location,
3831
possible_transports=possible_transports)
3832
except errors.NotABundle:
2886
pb = ui.ui_factory.nested_progress_bar()
2887
cleanups.append(pb.finished)
2889
cleanups.append(tree.unlock)
2890
if location is not None:
2892
mergeable = bundle.read_mergeable_from_url(location,
2893
possible_transports=possible_transports)
2894
except errors.NotABundle:
2898
raise errors.BzrCommandError('Cannot use --uncommitted'
2899
' with bundles or merge directives.')
2901
if revision is not None:
2902
raise errors.BzrCommandError(
2903
'Cannot use -r with merge directives or bundles')
2904
merger, verified = _mod_merge.Merger.from_mergeable(tree,
2907
if merger is None and uncommitted:
2908
if revision is not None and len(revision) > 0:
2909
raise errors.BzrCommandError('Cannot use --uncommitted and'
2910
' --revision at the same time.')
2911
location = self._select_branch_location(tree, location)[0]
2912
other_tree, other_path = WorkingTree.open_containing(location)
2913
merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2915
allow_pending = False
2916
if other_path != '':
2917
merger.interesting_files = [other_path]
2920
merger, allow_pending = self._get_merger_from_branch(tree,
2921
location, revision, remember, possible_transports, pb)
2923
merger.merge_type = merge_type
2924
merger.reprocess = reprocess
2925
merger.show_base = show_base
2926
self.sanity_check_merger(merger)
2927
if (merger.base_rev_id == merger.other_rev_id and
2928
merger.other_rev_id is not None):
2929
note('Nothing to do.')
2932
if merger.interesting_files is not None:
2933
raise errors.BzrCommandError('Cannot pull individual files')
2934
if (merger.base_rev_id == tree.last_revision()):
2935
result = tree.pull(merger.other_branch, False,
2936
merger.other_rev_id)
2937
result.report(self.outf)
2939
merger.check_basis(not force)
2941
return self._do_preview(merger)
3836
raise errors.BzrCommandError('Cannot use --uncommitted'
3837
' with bundles or merge directives.')
3839
if revision is not None:
3840
raise errors.BzrCommandError(
3841
'Cannot use -r with merge directives or bundles')
3842
merger, verified = _mod_merge.Merger.from_mergeable(tree,
3845
if merger is None and uncommitted:
3846
if revision is not None and len(revision) > 0:
3847
raise errors.BzrCommandError('Cannot use --uncommitted and'
3848
' --revision at the same time.')
3849
merger = self.get_merger_from_uncommitted(tree, location, None)
3850
allow_pending = False
3853
merger, allow_pending = self._get_merger_from_branch(tree,
3854
location, revision, remember, possible_transports, None)
3856
merger.merge_type = merge_type
3857
merger.reprocess = reprocess
3858
merger.show_base = show_base
3859
self.sanity_check_merger(merger)
3860
if (merger.base_rev_id == merger.other_rev_id and
3861
merger.other_rev_id is not None):
3862
note('Nothing to do.')
3865
if merger.interesting_files is not None:
3866
raise errors.BzrCommandError('Cannot pull individual files')
3867
if (merger.base_rev_id == tree.last_revision()):
3868
result = tree.pull(merger.other_branch, False,
3869
merger.other_rev_id)
3870
result.report(self.outf)
3872
if merger.this_basis is None:
3873
raise errors.BzrCommandError(
3874
"This branch has no commits."
3875
" (perhaps you would prefer 'bzr pull')")
3877
return self._do_preview(merger)
3879
return self._do_interactive(merger)
3881
return self._do_merge(merger, change_reporter, allow_pending,
3884
def _get_preview(self, merger):
2943
return self._do_merge(merger, change_reporter, allow_pending,
2946
for cleanup in reversed(cleanups):
2949
def _do_preview(self, merger):
2950
from bzrlib.diff import show_diff_trees
3885
2951
tree_merger = merger.make_merger()
3886
2952
tt = tree_merger.make_preview_transform()
3887
self.add_cleanup(tt.finalize)
3888
result_tree = tt.get_preview_tree()
3891
def _do_preview(self, merger):
3892
from bzrlib.diff import show_diff_trees
3893
result_tree = self._get_preview(merger)
3894
path_encoding = osutils.get_diff_header_encoding()
3895
show_diff_trees(merger.this_tree, result_tree, self.outf,
3896
old_label='', new_label='',
3897
path_encoding=path_encoding)
2954
result_tree = tt.get_preview_tree()
2955
show_diff_trees(merger.this_tree, result_tree, self.outf,
2956
old_label='', new_label='')
3899
2960
def _do_merge(self, merger, change_reporter, allow_pending, verified):
3900
2961
merger.change_reporter = change_reporter
4085
3105
def run(self, file_list=None, merge_type=None, show_base=False,
4086
3106
reprocess=False):
4087
from bzrlib.conflicts import restore
4088
3107
if merge_type is None:
4089
3108
merge_type = _mod_merge.Merge3Merger
4090
3109
tree, file_list = tree_files(file_list)
4091
self.add_cleanup(tree.lock_write().unlock)
4092
parents = tree.get_parent_ids()
4093
if len(parents) != 2:
4094
raise errors.BzrCommandError("Sorry, remerge only works after normal"
4095
" merges. Not cherrypicking or"
4097
repository = tree.branch.repository
4098
interesting_ids = None
4100
conflicts = tree.conflicts()
4101
if file_list is not None:
4102
interesting_ids = set()
4103
for filename in file_list:
4104
file_id = tree.path2id(filename)
4106
raise errors.NotVersionedError(filename)
4107
interesting_ids.add(file_id)
4108
if tree.kind(file_id) != "directory":
4111
for name, ie in tree.inventory.iter_entries(file_id):
4112
interesting_ids.add(ie.file_id)
4113
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4115
# Remerge only supports resolving contents conflicts
4116
allowed_conflicts = ('text conflict', 'contents conflict')
4117
restore_files = [c.path for c in conflicts
4118
if c.typestring in allowed_conflicts]
4119
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4120
tree.set_conflicts(ConflictList(new_conflicts))
4121
if file_list is not None:
4122
restore_files = file_list
4123
for filename in restore_files:
3112
parents = tree.get_parent_ids()
3113
if len(parents) != 2:
3114
raise errors.BzrCommandError("Sorry, remerge only works after normal"
3115
" merges. Not cherrypicking or"
3117
repository = tree.branch.repository
3118
interesting_ids = None
3120
conflicts = tree.conflicts()
3121
if file_list is not None:
3122
interesting_ids = set()
3123
for filename in file_list:
3124
file_id = tree.path2id(filename)
3126
raise errors.NotVersionedError(filename)
3127
interesting_ids.add(file_id)
3128
if tree.kind(file_id) != "directory":
3131
for name, ie in tree.inventory.iter_entries(file_id):
3132
interesting_ids.add(ie.file_id)
3133
new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3135
# Remerge only supports resolving contents conflicts
3136
allowed_conflicts = ('text conflict', 'contents conflict')
3137
restore_files = [c.path for c in conflicts
3138
if c.typestring in allowed_conflicts]
3139
_mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3140
tree.set_conflicts(ConflictList(new_conflicts))
3141
if file_list is not None:
3142
restore_files = file_list
3143
for filename in restore_files:
3145
restore(tree.abspath(filename))
3146
except errors.NotConflicted:
3148
# Disable pending merges, because the file texts we are remerging
3149
# have not had those merges performed. If we use the wrong parents
3150
# list, we imply that the working tree text has seen and rejected
3151
# all the changes from the other tree, when in fact those changes
3152
# have not yet been seen.
3153
pb = ui.ui_factory.nested_progress_bar()
3154
tree.set_parent_ids(parents[:1])
4125
restore(tree.abspath(filename))
4126
except errors.NotConflicted:
4128
# Disable pending merges, because the file texts we are remerging
4129
# have not had those merges performed. If we use the wrong parents
4130
# list, we imply that the working tree text has seen and rejected
4131
# all the changes from the other tree, when in fact those changes
4132
# have not yet been seen.
4133
tree.set_parent_ids(parents[:1])
4135
merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4136
merger.interesting_ids = interesting_ids
4137
merger.merge_type = merge_type
4138
merger.show_base = show_base
4139
merger.reprocess = reprocess
4140
conflicts = merger.do_merge()
3156
merger = _mod_merge.Merger.from_revision_ids(pb,
3158
merger.interesting_ids = interesting_ids
3159
merger.merge_type = merge_type
3160
merger.show_base = show_base
3161
merger.reprocess = reprocess
3162
conflicts = merger.do_merge()
3164
tree.set_parent_ids(parents)
4142
tree.set_parent_ids(parents)
4143
3168
if conflicts > 0:
4358
3333
" or specified.")
4359
3334
display_url = urlutils.unescape_for_display(parent,
4360
3335
self.outf.encoding)
4361
message("Using saved parent location: "
4362
+ display_url + "\n")
3336
self.outf.write("Using last location: " + display_url + "\n")
4364
3338
remote_branch = Branch.open(other_branch)
4365
3339
if remote_branch.base == local_branch.base:
4366
3340
remote_branch = local_branch
4368
self.add_cleanup(remote_branch.lock_read().unlock)
4370
local_revid_range = _revision_range_to_revid_range(
4371
_get_revision_range(my_revision, local_branch,
4374
remote_revid_range = _revision_range_to_revid_range(
4375
_get_revision_range(revision,
4376
remote_branch, self.name()))
4378
local_extra, remote_extra = find_unmerged(
4379
local_branch, remote_branch, restrict,
4380
backward=not reverse,
4381
include_merges=include_merges,
4382
local_revid_range=local_revid_range,
4383
remote_revid_range=remote_revid_range)
4385
if log_format is None:
4386
registry = log.log_formatter_registry
4387
log_format = registry.get_default(local_branch)
4388
lf = log_format(to_file=self.outf,
4390
show_timezone='original')
4393
if local_extra and not theirs_only:
4394
message("You have %d extra revision(s):\n" %
4396
for revision in iter_log_revisions(local_extra,
4397
local_branch.repository,
4399
lf.log_revision(revision)
4400
printed_local = True
4403
printed_local = False
4405
if remote_extra and not mine_only:
4406
if printed_local is True:
4408
message("You are missing %d revision(s):\n" %
4410
for revision in iter_log_revisions(remote_extra,
4411
remote_branch.repository,
4413
lf.log_revision(revision)
4416
if mine_only and not local_extra:
4417
# We checked local, and found nothing extra
4418
message('This branch is up to date.\n')
4419
elif theirs_only and not remote_extra:
4420
# We checked remote, and found nothing extra
4421
message('Other branch is up to date.\n')
4422
elif not (mine_only or theirs_only or local_extra or
4424
# We checked both branches, and neither one had extra
4426
message("Branches are up to date.\n")
3341
local_branch.lock_read()
3343
remote_branch.lock_read()
3345
local_extra, remote_extra = find_unmerged(
3346
local_branch, remote_branch, restrict)
3348
if log_format is None:
3349
registry = log.log_formatter_registry
3350
log_format = registry.get_default(local_branch)
3351
lf = log_format(to_file=self.outf,
3353
show_timezone='original')
3354
if reverse is False:
3355
if local_extra is not None:
3356
local_extra.reverse()
3357
if remote_extra is not None:
3358
remote_extra.reverse()
3361
if local_extra and not theirs_only:
3362
self.outf.write("You have %d extra revision(s):\n" %
3364
for revision in iter_log_revisions(local_extra,
3365
local_branch.repository,
3367
lf.log_revision(revision)
3368
printed_local = True
3371
printed_local = False
3373
if remote_extra and not mine_only:
3374
if printed_local is True:
3375
self.outf.write("\n\n\n")
3376
self.outf.write("You are missing %d revision(s):\n" %
3378
for revision in iter_log_revisions(remote_extra,
3379
remote_branch.repository,
3381
lf.log_revision(revision)
3384
if mine_only and not local_extra:
3385
# We checked local, and found nothing extra
3386
self.outf.write('This branch is up to date.\n')
3387
elif theirs_only and not remote_extra:
3388
# We checked remote, and found nothing extra
3389
self.outf.write('Other branch is up to date.\n')
3390
elif not (mine_only or theirs_only or local_extra or
3392
# We checked both branches, and neither one had extra
3394
self.outf.write("Branches are up to date.\n")
3396
remote_branch.unlock()
3398
local_branch.unlock()
4428
3399
if not status_code and parent is None and other_branch is not None:
4429
self.add_cleanup(local_branch.lock_write().unlock)
4430
# handle race conditions - a parent might be set while we run.
4431
if local_branch.get_parent() is None:
4432
local_branch.set_parent(remote_branch.base)
3400
local_branch.lock_write()
3402
# handle race conditions - a parent might be set while we run.
3403
if local_branch.get_parent() is None:
3404
local_branch.set_parent(remote_branch.base)
3406
local_branch.unlock()
4433
3407
return status_code
4436
3410
class cmd_pack(Command):
4437
__doc__ = """Compress the data within a repository.
4439
This operation compresses the data within a bazaar repository. As
4440
bazaar supports automatic packing of repository, this operation is
4441
normally not required to be done manually.
4443
During the pack operation, bazaar takes a backup of existing repository
4444
data, i.e. pack files. This backup is eventually removed by bazaar
4445
automatically when it is safe to do so. To save disk space by removing
4446
the backed up pack files, the --clean-obsolete-packs option may be
4449
Warning: If you use --clean-obsolete-packs and your machine crashes
4450
during or immediately after repacking, you may be left with a state
4451
where the deletion has been written to disk but the new packs have not
4452
been. In this case the repository may be unusable.
3411
"""Compress the data within a repository."""
4455
3413
_see_also = ['repositories']
4456
3414
takes_args = ['branch_or_repo?']
4458
Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4461
def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3416
def run(self, branch_or_repo='.'):
4462
3417
dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4464
3419
branch = dir.open_branch()
4465
3420
repository = branch.repository
4466
3421
except errors.NotBranchError:
4467
3422
repository = dir.open_repository()
4468
repository.pack(clean_obsolete_packs=clean_obsolete_packs)
4471
3426
class cmd_plugins(Command):
4472
__doc__ = """List the installed plugins.
3427
"""List the installed plugins.
4474
3429
This command displays the list of installed plugins including
4475
3430
version of plugin and a short description of each.
4866
3827
class cmd_serve(Command):
4867
__doc__ = """Run the bzr server."""
3828
"""Run the bzr server."""
4869
3830
aliases = ['server']
4871
3832
takes_options = [
4873
3834
help='Serve on stdin/out for use from inetd or sshd.'),
4874
RegistryOption('protocol',
4875
help="Protocol to serve.",
4876
lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4877
value_switches=True),
4879
3836
help='Listen for connections on nominated port of the form '
4880
3837
'[hostname:]portnumber. Passing 0 as the port number will '
4881
'result in a dynamically allocated port. The default port '
4882
'depends on the protocol.',
3838
'result in a dynamically allocated port. The default port is '
4884
custom_help('directory',
4885
help='Serve contents of this directory.'),
3842
help='Serve contents of this directory.',
4886
3844
Option('allow-writes',
4887
3845
help='By default the server is a readonly server. Supplying '
4888
3846
'--allow-writes enables write access to the contents of '
4889
'the served directory and below. Note that ``bzr serve`` '
4890
'does not perform authentication, so unless some form of '
4891
'external authentication is arranged supplying this '
4892
'option leads to global uncontrolled write access to your '
3847
'the served directory and below.'
4897
def get_host_and_port(self, port):
4898
"""Return the host and port to run the smart server on.
4900
If 'port' is None, None will be returned for the host and port.
4902
If 'port' has a colon in it, the string before the colon will be
4903
interpreted as the host.
4905
:param port: A string of the port to run the server on.
4906
:return: A tuple of (host, port), where 'host' is a host name or IP,
4907
and port is an integer TCP/IP port.
4910
if port is not None:
4912
host, port = port.split(':')
4916
def run(self, port=None, inet=False, directory=None, allow_writes=False,
4918
from bzrlib import transport
3851
def run(self, port=None, inet=False, directory=None, allow_writes=False):
3852
from bzrlib import lockdir
3853
from bzrlib.smart import medium, server
3854
from bzrlib.transport import get_transport
3855
from bzrlib.transport.chroot import ChrootServer
4919
3856
if directory is None:
4920
3857
directory = os.getcwd()
4921
if protocol is None:
4922
protocol = transport.transport_server_registry.get()
4923
host, port = self.get_host_and_port(port)
4924
3858
url = urlutils.local_path_to_url(directory)
4925
3859
if not allow_writes:
4926
3860
url = 'readonly+' + url
4927
t = transport.get_transport(url)
4928
protocol(t, host, port, inet)
3861
chroot_server = ChrootServer(get_transport(url))
3862
chroot_server.setUp()
3863
t = get_transport(chroot_server.get_url())
3865
smart_server = medium.SmartServerPipeStreamMedium(
3866
sys.stdin, sys.stdout, t)
3868
host = medium.BZR_DEFAULT_INTERFACE
3870
port = medium.BZR_DEFAULT_PORT
3873
host, port = port.split(':')
3875
smart_server = server.SmartTCPServer(t, host=host, port=port)
3876
print 'listening on port: ', smart_server.port
3878
# for the duration of this server, no UI output is permitted.
3879
# note that this may cause problems with blackbox tests. This should
3880
# be changed with care though, as we dont want to use bandwidth sending
3881
# progress over stderr to smart server clients!
3882
old_factory = ui.ui_factory
3883
old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
3885
ui.ui_factory = ui.SilentUIFactory()
3886
lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3887
smart_server.serve()
3889
ui.ui_factory = old_factory
3890
lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4931
3893
class cmd_join(Command):
4932
__doc__ = """Combine a tree into its containing tree.
4934
This command requires the target tree to be in a rich-root format.
3894
"""Combine a subtree into its containing tree.
3896
This command is for experimental use only. It requires the target tree
3897
to be in dirstate-with-subtree format, which cannot be converted into
4936
3900
The TREE argument should be an independent tree, inside another tree, but
4937
3901
not part of it. (Such trees can be produced by "bzr split", but also by
5190
4139
short_name='f',
5192
4141
Option('output', short_name='o',
5193
help='Write merge directive to this file or directory; '
4142
help='Write merge directive to this file; '
5194
4143
'use - for stdout.',
5197
help='Refuse to send if there are uncommitted changes in'
5198
' the working tree, --no-strict disables the check.'),
5199
4145
Option('mail-to', help='Mail the request to this address.',
5203
Option('body', help='Body for the email.', type=unicode),
5204
RegistryOption('format',
5205
help='Use the specified output format.',
5206
lazy_registry=('bzrlib.send', 'format_registry')),
4149
RegistryOption.from_kwargs('format',
4150
'Use the specified output format.',
4151
**{'4': 'Bundle format 4, Merge Directive 2 (default)',
4152
'0.9': 'Bundle format 0.9, Merge Directive 1',})
5209
4155
def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5210
4156
no_patch=False, revision=None, remember=False, output=None,
5211
format=None, mail_to=None, message=None, body=None,
5212
strict=None, **kwargs):
5213
from bzrlib.send import send
5214
return send(submit_branch, revision, public_branch, remember,
5215
format, no_bundle, no_patch, output,
5216
kwargs.get('from', '.'), mail_to, message, body,
4157
format='4', mail_to=None, message=None, **kwargs):
4158
return self._run(submit_branch, revision, public_branch, remember,
4159
format, no_bundle, no_patch, output,
4160
kwargs.get('from', '.'), mail_to, message)
4162
def _run(self, submit_branch, revision, public_branch, remember, format,
4163
no_bundle, no_patch, output, from_, mail_to, message):
4164
from bzrlib.revision import NULL_REVISION
4165
branch = Branch.open_containing(from_)[0]
4167
outfile = StringIO()
4171
outfile = open(output, 'wb')
4172
# we may need to write data into branch's repository to calculate
4177
config = branch.get_config()
4179
mail_to = config.get_user_option('submit_to')
4180
mail_client = config.get_mail_client()
4181
if remember and submit_branch is None:
4182
raise errors.BzrCommandError(
4183
'--remember requires a branch to be specified.')
4184
stored_submit_branch = branch.get_submit_branch()
4185
remembered_submit_branch = False
4186
if submit_branch is None:
4187
submit_branch = stored_submit_branch
4188
remembered_submit_branch = True
4190
if stored_submit_branch is None or remember:
4191
branch.set_submit_branch(submit_branch)
4192
if submit_branch is None:
4193
submit_branch = branch.get_parent()
4194
remembered_submit_branch = True
4195
if submit_branch is None:
4196
raise errors.BzrCommandError('No submit branch known or'
4198
if remembered_submit_branch:
4199
note('Using saved location "%s" to determine what changes to submit.', submit_branch)
4202
submit_config = Branch.open(submit_branch).get_config()
4203
mail_to = submit_config.get_user_option("child_submit_to")
4205
stored_public_branch = branch.get_public_branch()
4206
if public_branch is None:
4207
public_branch = stored_public_branch
4208
elif stored_public_branch is None or remember:
4209
branch.set_public_branch(public_branch)
4210
if no_bundle and public_branch is None:
4211
raise errors.BzrCommandError('No public branch specified or'
4213
base_revision_id = None
4215
if revision is not None:
4216
if len(revision) > 2:
4217
raise errors.BzrCommandError('bzr send takes '
4218
'at most two one revision identifiers')
4219
revision_id = revision[-1].as_revision_id(branch)
4220
if len(revision) == 2:
4221
base_revision_id = revision[0].as_revision_id(branch)
4222
if revision_id is None:
4223
revision_id = branch.last_revision()
4224
if revision_id == NULL_REVISION:
4225
raise errors.BzrCommandError('No revisions to submit.')
4227
directive = merge_directive.MergeDirective2.from_objects(
4228
branch.repository, revision_id, time.time(),
4229
osutils.local_time_offset(), submit_branch,
4230
public_branch=public_branch, include_patch=not no_patch,
4231
include_bundle=not no_bundle, message=message,
4232
base_revision_id=base_revision_id)
4233
elif format == '0.9':
4236
patch_type = 'bundle'
4238
raise errors.BzrCommandError('Format 0.9 does not'
4239
' permit bundle with no patch')
4245
directive = merge_directive.MergeDirective.from_objects(
4246
branch.repository, revision_id, time.time(),
4247
osutils.local_time_offset(), submit_branch,
4248
public_branch=public_branch, patch_type=patch_type,
4251
outfile.writelines(directive.to_lines())
4253
subject = '[MERGE] '
4254
if message is not None:
4257
revision = branch.repository.get_revision(revision_id)
4258
subject += revision.get_summary()
4259
basename = directive.get_disk_name(branch)
4260
mail_client.compose_merge_request(mail_to, subject,
4261
outfile.getvalue(), basename)
5221
4268
class cmd_bundle_revisions(cmd_send):
5222
__doc__ = """Create a merge-directive for submitting changes.
4270
"""Create a merge-directive for submiting changes.
5224
4272
A merge directive provides many things needed for requesting merges:
5447
4468
_see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
5448
4469
takes_args = ['location?']
5450
RegistryOption.from_kwargs(
5452
title='Target type',
5453
help='The type to reconfigure the directory to.',
5454
value_switches=True, enum_switch=False,
5455
branch='Reconfigure to be an unbound branch with no working tree.',
5456
tree='Reconfigure to be an unbound branch with a working tree.',
5457
checkout='Reconfigure to be a bound branch with a working tree.',
5458
lightweight_checkout='Reconfigure to be a lightweight'
5459
' checkout (with no local history).',
5460
standalone='Reconfigure to be a standalone branch '
5461
'(i.e. stop using shared repository).',
5462
use_shared='Reconfigure to use a shared repository.',
5463
with_trees='Reconfigure repository to create '
5464
'working trees on branches by default.',
5465
with_no_trees='Reconfigure repository to not create '
5466
'working trees on branches by default.'
5468
Option('bind-to', help='Branch to bind checkout to.', type=str),
5470
help='Perform reconfiguration even if local changes'
5472
Option('stacked-on',
5473
help='Reconfigure a branch to be stacked on another branch.',
5477
help='Reconfigure a branch to be unstacked. This '
5478
'may require copying substantial data into it.',
4470
takes_options = [RegistryOption.from_kwargs('target_type',
4471
title='Target type',
4472
help='The type to reconfigure the directory to.',
4473
value_switches=True, enum_switch=False,
4474
branch='Reconfigure to be an unbound branch '
4475
'with no working tree.',
4476
tree='Reconfigure to be an unbound branch '
4477
'with a working tree.',
4478
checkout='Reconfigure to be a bound branch '
4479
'with a working tree.',
4480
lightweight_checkout='Reconfigure to be a lightweight'
4481
' checkout (with no local history).',
4482
standalone='Reconfigure to be a standalone branch '
4483
'(i.e. stop using shared repository).',
4484
use_shared='Reconfigure to use a shared repository.'),
4485
Option('bind-to', help='Branch to bind checkout to.',
4488
help='Perform reconfiguration even if local changes'
5482
def run(self, location=None, target_type=None, bind_to=None, force=False,
4492
def run(self, location=None, target_type=None, bind_to=None, force=False):
5485
4493
directory = bzrdir.BzrDir.open(location)
5486
if stacked_on and unstacked:
5487
raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5488
elif stacked_on is not None:
5489
reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
5491
reconfigure.ReconfigureUnstacked().apply(directory)
5492
# At the moment you can use --stacked-on and a different
5493
# reconfiguration shape at the same time; there seems no good reason
5495
4494
if target_type is None:
5496
if stacked_on or unstacked:
5499
raise errors.BzrCommandError('No target configuration '
4495
raise errors.BzrCommandError('No target configuration specified')
5501
4496
elif target_type == 'branch':
5502
4497
reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5503
4498
elif target_type == 'tree':
5504
4499
reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5505
4500
elif target_type == 'checkout':
5506
reconfiguration = reconfigure.Reconfigure.to_checkout(
4501
reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
5508
4503
elif target_type == 'lightweight-checkout':
5509
4504
reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5510
4505
directory, bind_to)
5538
4527
directory of the current branch. For example, if you are currently in a
5539
4528
checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5540
4529
/path/to/newbranch.
5542
Bound branches use the nickname of its master branch unless it is set
5543
locally, in which case switching will update the local nickname to be
5547
takes_args = ['to_location?']
5548
takes_options = ['directory',
5550
help='Switch even if local commits will be lost.'),
5552
Option('create-branch', short_name='b',
5553
help='Create the target branch from this one before'
5554
' switching to it.'),
4532
takes_args = ['to_location']
4533
takes_options = [Option('force',
4534
help='Switch even if local commits will be lost.')
5557
def run(self, to_location=None, force=False, create_branch=False,
5558
revision=None, directory=u'.'):
4537
def run(self, to_location, force=False):
5559
4538
from bzrlib import switch
5560
tree_location = directory
5561
revision = _get_one_revision('switch', revision)
5562
4540
control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5563
if to_location is None:
5564
if revision is None:
5565
raise errors.BzrCommandError('You must supply either a'
5566
' revision or a location')
5567
to_location = tree_location
5569
branch = control_dir.open_branch()
5570
had_explicit_nick = branch.get_config().has_explicit_nickname()
4542
to_branch = Branch.open(to_location)
5571
4543
except errors.NotBranchError:
5573
had_explicit_nick = False
5576
raise errors.BzrCommandError('cannot create branch without'
5578
to_location = directory_service.directories.dereference(
5580
if '/' not in to_location and '\\' not in to_location:
5581
# This path is meant to be relative to the existing branch
5582
this_url = self._get_branch_location(control_dir)
5583
to_location = urlutils.join(this_url, '..', to_location)
5584
to_branch = branch.bzrdir.sprout(to_location,
5585
possible_transports=[branch.bzrdir.root_transport],
5586
source_branch=branch).open_branch()
5589
to_branch = Branch.open(to_location)
5590
except errors.NotBranchError:
5591
this_url = self._get_branch_location(control_dir)
5592
to_branch = Branch.open(
5593
urlutils.join(this_url, '..', to_location))
5594
if revision is not None:
5595
revision = revision.as_revision_id(to_branch)
5596
switch.switch(control_dir, to_branch, force, revision_id=revision)
5597
if had_explicit_nick:
5598
branch = control_dir.open_branch() #get the new branch!
5599
branch.nick = to_branch.nick
4544
to_branch = Branch.open(
4545
control_dir.open_branch().base + '../' + to_location)
4546
switch.switch(control_dir, to_branch, force)
5600
4547
note('Switched to branch: %s',
5601
4548
urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5603
def _get_branch_location(self, control_dir):
5604
"""Return location of branch for this control dir."""
5606
this_branch = control_dir.open_branch()
5607
# This may be a heavy checkout, where we want the master branch
5608
master_location = this_branch.get_bound_location()
5609
if master_location is not None:
5610
return master_location
5611
# If not, use a local sibling
5612
return this_branch.base
5613
except errors.NotBranchError:
5614
format = control_dir.find_branch_format()
5615
if getattr(format, 'get_reference', None) is not None:
5616
return format.get_reference(control_dir)
5618
return control_dir.root_transport.base
5621
class cmd_view(Command):
5622
__doc__ = """Manage filtered views.
5624
Views provide a mask over the tree so that users can focus on
5625
a subset of a tree when doing their work. After creating a view,
5626
commands that support a list of files - status, diff, commit, etc -
5627
effectively have that list of files implicitly given each time.
5628
An explicit list of files can still be given but those files
5629
must be within the current view.
5631
In most cases, a view has a short life-span: it is created to make
5632
a selected change and is deleted once that change is committed.
5633
At other times, you may wish to create one or more named views
5634
and switch between them.
5636
To disable the current view without deleting it, you can switch to
5637
the pseudo view called ``off``. This can be useful when you need
5638
to see the whole tree for an operation or two (e.g. merge) but
5639
want to switch back to your view after that.
5642
To define the current view::
5644
bzr view file1 dir1 ...
5646
To list the current view::
5650
To delete the current view::
5654
To disable the current view without deleting it::
5656
bzr view --switch off
5658
To define a named view and switch to it::
5660
bzr view --name view-name file1 dir1 ...
5662
To list a named view::
5664
bzr view --name view-name
5666
To delete a named view::
5668
bzr view --name view-name --delete
5670
To switch to a named view::
5672
bzr view --switch view-name
5674
To list all views defined::
5678
To delete all views::
5680
bzr view --delete --all
5684
takes_args = ['file*']
5687
help='Apply list or delete action to all views.',
5690
help='Delete the view.',
5693
help='Name of the view to define, list or delete.',
5697
help='Name of the view to switch to.',
5702
def run(self, file_list,
5708
tree, file_list = tree_files(file_list, apply_view=False)
5709
current_view, view_dict = tree.views.get_view_info()
5714
raise errors.BzrCommandError(
5715
"Both --delete and a file list specified")
5717
raise errors.BzrCommandError(
5718
"Both --delete and --switch specified")
5720
tree.views.set_view_info(None, {})
5721
self.outf.write("Deleted all views.\n")
5723
raise errors.BzrCommandError("No current view to delete")
5725
tree.views.delete_view(name)
5726
self.outf.write("Deleted '%s' view.\n" % name)
5729
raise errors.BzrCommandError(
5730
"Both --switch and a file list specified")
5732
raise errors.BzrCommandError(
5733
"Both --switch and --all specified")
5734
elif switch == 'off':
5735
if current_view is None:
5736
raise errors.BzrCommandError("No current view to disable")
5737
tree.views.set_view_info(None, view_dict)
5738
self.outf.write("Disabled '%s' view.\n" % (current_view))
5740
tree.views.set_view_info(switch, view_dict)
5741
view_str = views.view_display_str(tree.views.lookup_view())
5742
self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
5745
self.outf.write('Views defined:\n')
5746
for view in sorted(view_dict):
5747
if view == current_view:
5751
view_str = views.view_display_str(view_dict[view])
5752
self.outf.write('%s %-20s %s\n' % (active, view, view_str))
5754
self.outf.write('No views defined.\n')
5757
# No name given and no current view set
5760
raise errors.BzrCommandError(
5761
"Cannot change the 'off' pseudo view")
5762
tree.views.set_view(name, sorted(file_list))
5763
view_str = views.view_display_str(tree.views.lookup_view())
5764
self.outf.write("Using '%s' view: %s\n" % (name, view_str))
5768
# No name given and no current view set
5769
self.outf.write('No current view.\n')
5771
view_str = views.view_display_str(tree.views.lookup_view(name))
5772
self.outf.write("'%s' view is: %s\n" % (name, view_str))
5775
4551
class cmd_hooks(Command):
5776
__doc__ = """Show hooks."""
5781
for hook_key in sorted(hooks.known_hooks.keys()):
5782
some_hooks = hooks.known_hooks_key_to_object(hook_key)
5783
self.outf.write("%s:\n" % type(some_hooks).__name__)
5784
for hook_name, hook_point in sorted(some_hooks.items()):
5785
self.outf.write(" %s:\n" % (hook_name,))
5786
found_hooks = list(hook_point)
5788
for hook in found_hooks:
5789
self.outf.write(" %s\n" %
5790
(some_hooks.get_hook_name(hook),))
5792
self.outf.write(" <no hooks installed>\n")
5795
class cmd_remove_branch(Command):
5796
__doc__ = """Remove a branch.
5798
This will remove the branch from the specified location but
5799
will keep any working tree or repository in place.
5803
Remove the branch at repo/trunk::
5805
bzr remove-branch repo/trunk
5809
takes_args = ["location?"]
5811
aliases = ["rmbranch"]
5813
def run(self, location=None):
5814
if location is None:
5816
branch = Branch.open_containing(location)[0]
5817
branch.bzrdir.destroy_branch()
5820
class cmd_shelve(Command):
5821
__doc__ = """Temporarily set aside some changes from the current tree.
5823
Shelve allows you to temporarily put changes you've made "on the shelf",
5824
ie. out of the way, until a later time when you can bring them back from
5825
the shelf with the 'unshelve' command. The changes are stored alongside
5826
your working tree, and so they aren't propagated along with your branch nor
5827
will they survive its deletion.
5829
If shelve --list is specified, previously-shelved changes are listed.
5831
Shelve is intended to help separate several sets of changes that have
5832
been inappropriately mingled. If you just want to get rid of all changes
5833
and you don't need to restore them later, use revert. If you want to
5834
shelve all text changes at once, use shelve --all.
5836
If filenames are specified, only the changes to those files will be
5837
shelved. Other files will be left untouched.
5839
If a revision is specified, changes since that revision will be shelved.
5841
You can put multiple items on the shelf, and by default, 'unshelve' will
5842
restore the most recently shelved changes.
5845
takes_args = ['file*']
5850
Option('all', help='Shelve all changes.'),
5852
RegistryOption('writer', 'Method to use for writing diffs.',
5853
bzrlib.option.diff_writer_registry,
5854
value_switches=True, enum_switch=False),
5856
Option('list', help='List shelved changes.'),
5858
help='Destroy removed changes instead of shelving them.'),
5860
_see_also = ['unshelve']
5862
def run(self, revision=None, all=False, file_list=None, message=None,
5863
writer=None, list=False, destroy=False, directory=u'.'):
5865
return self.run_for_list()
5866
from bzrlib.shelf_ui import Shelver
5868
writer = bzrlib.option.diff_writer_registry.get()
5870
shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5871
file_list, message, destroy=destroy, directory=directory)
5876
except errors.UserAbort:
5879
def run_for_list(self):
5880
tree = WorkingTree.open_containing('.')[0]
5881
self.add_cleanup(tree.lock_read().unlock)
5882
manager = tree.get_shelf_manager()
5883
shelves = manager.active_shelves()
5884
if len(shelves) == 0:
5885
note('No shelved changes.')
5887
for shelf_id in reversed(shelves):
5888
message = manager.get_metadata(shelf_id).get('message')
5890
message = '<no message>'
5891
self.outf.write('%3d: %s\n' % (shelf_id, message))
5895
class cmd_unshelve(Command):
5896
__doc__ = """Restore shelved changes.
5898
By default, the most recently shelved changes are restored. However if you
5899
specify a shelf by id those changes will be restored instead. This works
5900
best when the changes don't depend on each other.
5903
takes_args = ['shelf_id?']
5906
RegistryOption.from_kwargs(
5907
'action', help="The action to perform.",
5908
enum_switch=False, value_switches=True,
5909
apply="Apply changes and remove from the shelf.",
5910
dry_run="Show changes, but do not apply or remove them.",
5911
preview="Instead of unshelving the changes, show the diff that "
5912
"would result from unshelving.",
5913
delete_only="Delete changes without applying them.",
5914
keep="Apply changes but don't delete them.",
5917
_see_also = ['shelve']
5919
def run(self, shelf_id=None, action='apply', directory=u'.'):
5920
from bzrlib.shelf_ui import Unshelver
5921
unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5925
unshelver.tree.unlock()
5928
class cmd_clean_tree(Command):
5929
__doc__ = """Remove unwanted files from working tree.
5931
By default, only unknown files, not ignored files, are deleted. Versioned
5932
files are never deleted.
5934
Another class is 'detritus', which includes files emitted by bzr during
5935
normal operations and selftests. (The value of these files decreases with
5938
If no options are specified, unknown files are deleted. Otherwise, option
5939
flags are respected, and may be combined.
5941
To check what clean-tree will do, use --dry-run.
5943
takes_options = ['directory',
5944
Option('ignored', help='Delete all ignored files.'),
5945
Option('detritus', help='Delete conflict files, merge'
5946
' backups, and failed selftest dirs.'),
5948
help='Delete files unknown to bzr (default).'),
5949
Option('dry-run', help='Show files to delete instead of'
5951
Option('force', help='Do not prompt before deleting.')]
5952
def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5953
force=False, directory=u'.'):
5954
from bzrlib.clean_tree import clean_tree
5955
if not (unknown or ignored or detritus):
5959
clean_tree(directory, unknown=unknown, ignored=ignored,
5960
detritus=detritus, dry_run=dry_run, no_prompt=force)
5963
class cmd_reference(Command):
5964
__doc__ = """list, view and set branch locations for nested trees.
5966
If no arguments are provided, lists the branch locations for nested trees.
5967
If one argument is provided, display the branch location for that tree.
5968
If two arguments are provided, set the branch location for that tree.
5973
takes_args = ['path?', 'location?']
5975
def run(self, path=None, location=None):
5977
if path is not None:
5979
tree, branch, relpath =(
5980
bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
5981
if path is not None:
5984
tree = branch.basis_tree()
4552
"""Show a branch's currently registered hooks.
4556
takes_args = ['path?']
4558
def run(self, path=None):
5985
4559
if path is None:
5986
info = branch._get_all_reference_info().iteritems()
5987
self._display_reference_info(tree, branch, info)
4561
branch_hooks = Branch.open(path).hooks
4562
for hook_type in branch_hooks:
4563
hooks = branch_hooks[hook_type]
4564
self.outf.write("%s:\n" % (hook_type,))
4567
self.outf.write(" %s\n" %
4568
(branch_hooks.get_hook_name(hook),))
4570
self.outf.write(" <no hooks installed>\n")
4573
def _create_prefix(cur_transport):
4574
needed = [cur_transport]
4575
# Recurse upwards until we can create a directory successfully
4577
new_transport = cur_transport.clone('..')
4578
if new_transport.base == cur_transport.base:
4579
raise errors.BzrCommandError(
4580
"Failed to create path prefix for %s."
4581
% cur_transport.base)
4583
new_transport.mkdir('.')
4584
except errors.NoSuchFile:
4585
needed.append(new_transport)
4586
cur_transport = new_transport
5989
file_id = tree.path2id(path)
5991
raise errors.NotVersionedError(path)
5992
if location is None:
5993
info = [(file_id, branch.get_reference_info(file_id))]
5994
self._display_reference_info(tree, branch, info)
5996
branch.set_reference_info(file_id, path, location)
5998
def _display_reference_info(self, tree, branch, info):
6000
for file_id, (path, location) in info:
6002
path = tree.id2path(file_id)
6003
except errors.NoSuchId:
6005
ref_list.append((path, location))
6006
for path, location in sorted(ref_list):
6007
self.outf.write('%s %s\n' % (path, location))
6010
def _register_lazy_builtins():
6011
# register lazy builtins from other modules; called at startup and should
6012
# be only called once.
6013
for (name, aliases, module_name) in [
6014
('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
6015
('cmd_dpush', [], 'bzrlib.foreign'),
6016
('cmd_version_info', [], 'bzrlib.cmd_version_info'),
6017
('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
6018
('cmd_conflicts', [], 'bzrlib.conflicts'),
6019
('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
6021
builtin_command_registry.register_lazy(name, aliases, module_name)
4589
# Now we only need to create child directories
4591
cur_transport = needed.pop()
4592
cur_transport.ensure_base()
4595
# these get imported and then picked up by the scan for cmd_*
4596
# TODO: Some more consistent way to split command definitions across files;
4597
# we do need to load at least some information about them to know of
4598
# aliases. ideally we would avoid loading the implementation until the
4599
# details were needed.
4600
from bzrlib.cmd_version_info import cmd_version_info
4601
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
4602
from bzrlib.bundle.commands import (
4605
from bzrlib.sign_my_commits import cmd_sign_my_commits
4606
from bzrlib.weave_commands import cmd_versionedfile_list, \
4607
cmd_weave_plan_merge, cmd_weave_merge_text