359
513
"""Iterate over an inclusive range of sorted revisions."""
360
514
rev_iter = iter(merge_sorted_revisions)
361
515
if start_revision_id is not None:
362
for rev_id, depth, revno, end_of_merge in rev_iter:
516
for node in rev_iter:
363
518
if rev_id != start_revision_id:
366
521
# The decision to include the start or not
367
522
# depends on the stop_rule if a stop is provided
369
iter([(rev_id, depth, revno, end_of_merge)]),
523
# so pop this node back into the iterator
524
rev_iter = itertools.chain(iter([node]), rev_iter)
372
526
if stop_revision_id is None:
373
for rev_id, depth, revno, end_of_merge in rev_iter:
374
yield rev_id, depth, revno, end_of_merge
528
for node in rev_iter:
530
yield (rev_id, node.merge_depth, node.revno,
375
532
elif stop_rule == 'exclude':
376
for rev_id, depth, revno, end_of_merge in rev_iter:
533
for node in rev_iter:
377
535
if rev_id == stop_revision_id:
379
yield rev_id, depth, revno, end_of_merge
537
yield (rev_id, node.merge_depth, node.revno,
380
539
elif stop_rule == 'include':
381
for rev_id, depth, revno, end_of_merge in rev_iter:
382
yield rev_id, depth, revno, end_of_merge
540
for node in rev_iter:
542
yield (rev_id, node.merge_depth, node.revno,
383
544
if rev_id == stop_revision_id:
546
elif stop_rule == 'with-merges-without-common-ancestry':
547
# We want to exclude all revisions that are already part of the
548
# stop_revision_id ancestry.
549
graph = self.repository.get_graph()
550
ancestors = graph.find_unique_ancestors(start_revision_id,
552
for node in rev_iter:
554
if rev_id not in ancestors:
556
yield (rev_id, node.merge_depth, node.revno,
385
558
elif stop_rule == 'with-merges':
386
559
stop_rev = self.repository.get_revision(stop_revision_id)
387
560
if stop_rev.parent_ids:
388
561
left_parent = stop_rev.parent_ids[0]
390
563
left_parent = _mod_revision.NULL_REVISION
391
for rev_id, depth, revno, end_of_merge in rev_iter:
564
# left_parent is the actual revision we want to stop logging at,
565
# since we want to show the merged revisions after the stop_rev too
566
reached_stop_revision_id = False
567
revision_id_whitelist = []
568
for node in rev_iter:
392
570
if rev_id == left_parent:
571
# reached the left parent after the stop_revision
394
yield rev_id, depth, revno, end_of_merge
573
if (not reached_stop_revision_id or
574
rev_id in revision_id_whitelist):
575
yield (rev_id, node.merge_depth, node.revno,
577
if reached_stop_revision_id or rev_id == stop_revision_id:
578
# only do the merged revs of rev_id from now on
579
rev = self.repository.get_revision(rev_id)
581
reached_stop_revision_id = True
582
revision_id_whitelist.extend(rev.parent_ids)
396
584
raise ValueError('invalid stop_rule %r' % stop_rule)
586
def _filter_start_non_ancestors(self, rev_iter):
587
# If we started from a dotted revno, we want to consider it as a tip
588
# and don't want to yield revisions that are not part of its
589
# ancestry. Given the order guaranteed by the merge sort, we will see
590
# uninteresting descendants of the first parent of our tip before the
592
first = rev_iter.next()
593
(rev_id, merge_depth, revno, end_of_merge) = first
596
# We start at a mainline revision so by definition, all others
597
# revisions in rev_iter are ancestors
598
for node in rev_iter:
603
pmap = self.repository.get_parent_map([rev_id])
604
parents = pmap.get(rev_id, [])
606
whitelist.update(parents)
608
# If there is no parents, there is nothing of interest left
610
# FIXME: It's hard to test this scenario here as this code is never
611
# called in that case. -- vila 20100322
614
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
616
if rev_id in whitelist:
617
pmap = self.repository.get_parent_map([rev_id])
618
parents = pmap.get(rev_id, [])
619
whitelist.remove(rev_id)
620
whitelist.update(parents)
622
# We've reached the mainline, there is nothing left to
626
# A revision that is not part of the ancestry of our
629
yield (rev_id, merge_depth, revno, end_of_merge)
398
631
def leave_lock_in_place(self):
399
632
"""Tell this branch object not to release the physical lock when this
400
633
object is unlocked.
402
635
If lock_write doesn't return a token, then this method is not supported.
404
637
self.control_files.leave_in_place()
517
757
"""Print `file` to stdout."""
518
758
raise NotImplementedError(self.print_file)
760
@deprecated_method(deprecated_in((2, 4, 0)))
520
761
def set_revision_history(self, rev_history):
521
raise NotImplementedError(self.set_revision_history)
762
"""See Branch.set_revision_history."""
763
self._set_revision_history(rev_history)
766
def _set_revision_history(self, rev_history):
767
if len(rev_history) == 0:
768
revid = _mod_revision.NULL_REVISION
770
revid = rev_history[-1]
771
if rev_history != self._lefthand_history(revid):
772
raise errors.NotLefthandHistory(rev_history)
773
self.set_last_revision_info(len(rev_history), revid)
774
self._cache_revision_history(rev_history)
775
for hook in Branch.hooks['set_rh']:
776
hook(self, rev_history)
779
def set_last_revision_info(self, revno, revision_id):
780
"""Set the last revision of this branch.
782
The caller is responsible for checking that the revno is correct
783
for this revision id.
785
It may be possible to set the branch last revision to an id not
786
present in the repository. However, branches can also be
787
configured to check constraints on history, in which case this may not
790
raise NotImplementedError(self.set_last_revision_info)
793
def generate_revision_history(self, revision_id, last_rev=None,
795
"""See Branch.generate_revision_history"""
796
graph = self.repository.get_graph()
797
(last_revno, last_revid) = self.last_revision_info()
798
known_revision_ids = [
799
(last_revid, last_revno),
800
(_mod_revision.NULL_REVISION, 0),
802
if last_rev is not None:
803
if not graph.is_ancestor(last_rev, revision_id):
804
# our previous tip is not merged into stop_revision
805
raise errors.DivergedBranches(self, other_branch)
806
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
807
self.set_last_revision_info(revno, revision_id)
810
def set_parent(self, url):
811
"""See Branch.set_parent."""
812
# TODO: Maybe delete old location files?
813
# URLs should never be unicode, even on the local fs,
814
# FIXUP this and get_parent in a future branch format bump:
815
# read and rewrite the file. RBC 20060125
817
if isinstance(url, unicode):
819
url = url.encode('ascii')
820
except UnicodeEncodeError:
821
raise errors.InvalidURL(url,
822
"Urls must be 7-bit ascii, "
823
"use bzrlib.urlutils.escape")
824
url = urlutils.relative_url(self.base, url)
825
self._set_parent_location(url)
523
828
def set_stacked_on_url(self, url):
524
829
"""Set the URL this branch is stacked against.
528
833
:raises UnstackableRepositoryFormat: If the repository does not support
531
raise NotImplementedError(self.set_stacked_on_url)
836
if not self._format.supports_stacking():
837
raise errors.UnstackableBranchFormat(self._format, self.user_url)
838
# XXX: Changing from one fallback repository to another does not check
839
# that all the data you need is present in the new fallback.
840
# Possibly it should.
841
self._check_stackable_repo()
844
old_url = self.get_stacked_on_url()
845
except (errors.NotStacked, errors.UnstackableBranchFormat,
846
errors.UnstackableRepositoryFormat):
850
self._activate_fallback_location(url)
851
# write this out after the repository is stacked to avoid setting a
852
# stacked config that doesn't work.
853
self._set_config_location('stacked_on_location', url)
856
"""Change a branch to be unstacked, copying data as needed.
858
Don't call this directly, use set_stacked_on_url(None).
860
pb = ui.ui_factory.nested_progress_bar()
862
pb.update(gettext("Unstacking"))
863
# The basic approach here is to fetch the tip of the branch,
864
# including all available ghosts, from the existing stacked
865
# repository into a new repository object without the fallbacks.
867
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
868
# correct for CHKMap repostiories
869
old_repository = self.repository
870
if len(old_repository._fallback_repositories) != 1:
871
raise AssertionError("can't cope with fallback repositories "
872
"of %r (fallbacks: %r)" % (old_repository,
873
old_repository._fallback_repositories))
874
# Open the new repository object.
875
# Repositories don't offer an interface to remove fallback
876
# repositories today; take the conceptually simpler option and just
877
# reopen it. We reopen it starting from the URL so that we
878
# get a separate connection for RemoteRepositories and can
879
# stream from one of them to the other. This does mean doing
880
# separate SSH connection setup, but unstacking is not a
881
# common operation so it's tolerable.
882
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
883
new_repository = new_bzrdir.find_repository()
884
if new_repository._fallback_repositories:
885
raise AssertionError("didn't expect %r to have "
886
"fallback_repositories"
887
% (self.repository,))
888
# Replace self.repository with the new repository.
889
# Do our best to transfer the lock state (i.e. lock-tokens and
890
# lock count) of self.repository to the new repository.
891
lock_token = old_repository.lock_write().repository_token
892
self.repository = new_repository
893
if isinstance(self, remote.RemoteBranch):
894
# Remote branches can have a second reference to the old
895
# repository that need to be replaced.
896
if self._real_branch is not None:
897
self._real_branch.repository = new_repository
898
self.repository.lock_write(token=lock_token)
899
if lock_token is not None:
900
old_repository.leave_lock_in_place()
901
old_repository.unlock()
902
if lock_token is not None:
903
# XXX: self.repository.leave_lock_in_place() before this
904
# function will not be preserved. Fortunately that doesn't
905
# affect the current default format (2a), and would be a
906
# corner-case anyway.
907
# - Andrew Bennetts, 2010/06/30
908
self.repository.dont_leave_lock_in_place()
912
old_repository.unlock()
913
except errors.LockNotHeld:
916
if old_lock_count == 0:
917
raise AssertionError(
918
'old_repository should have been locked at least once.')
919
for i in range(old_lock_count-1):
920
self.repository.lock_write()
921
# Fetch from the old repository into the new.
922
old_repository.lock_read()
924
# XXX: If you unstack a branch while it has a working tree
925
# with a pending merge, the pending-merged revisions will no
926
# longer be present. You can (probably) revert and remerge.
928
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
929
except errors.TagsNotSupported:
930
tags_to_fetch = set()
931
fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
932
old_repository, required_ids=[self.last_revision()],
933
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
934
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
936
old_repository.unlock()
940
def _set_tags_bytes(self, bytes):
941
"""Mirror method for _get_tags_bytes.
943
:seealso: Branch._get_tags_bytes.
945
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
946
op.add_cleanup(self.lock_write().unlock)
947
return op.run_simple(bytes)
949
def _set_tags_bytes_locked(self, bytes):
950
self._tags_bytes = bytes
951
return self._transport.put_bytes('tags', bytes)
533
953
def _cache_revision_history(self, rev_history):
534
954
"""Set the cached revision history to rev_history.
621
1041
:return: A tuple (revno, revision_id).
623
1043
if self._last_revision_info_cache is None:
624
self._last_revision_info_cache = self._last_revision_info()
1044
self._last_revision_info_cache = self._read_last_revision_info()
625
1045
return self._last_revision_info_cache
627
def _last_revision_info(self):
628
rh = self.revision_history()
631
return (revno, rh[-1])
633
return (0, _mod_revision.NULL_REVISION)
635
@deprecated_method(deprecated_in((1, 6, 0)))
636
def missing_revisions(self, other, stop_revision=None):
637
"""Return a list of new revisions that would perfectly fit.
639
If self and other have not diverged, return a list of the revisions
640
present in other, but missing from self.
642
self_history = self.revision_history()
643
self_len = len(self_history)
644
other_history = other.revision_history()
645
other_len = len(other_history)
646
common_index = min(self_len, other_len) -1
647
if common_index >= 0 and \
648
self_history[common_index] != other_history[common_index]:
649
raise errors.DivergedBranches(self, other)
651
if stop_revision is None:
652
stop_revision = other_len
654
if stop_revision > other_len:
655
raise errors.NoSuchRevision(self, stop_revision)
656
return other_history[self_len:stop_revision]
659
def update_revisions(self, other, stop_revision=None, overwrite=False,
661
"""Pull in new perfect-fit revisions.
663
:param other: Another Branch to pull from
664
:param stop_revision: Updated until the given revision
665
:param overwrite: Always set the branch pointer, rather than checking
666
to see if it is a proper descendant.
667
:param graph: A Graph object that can be used to query history
668
information. This can be None.
673
other_revno, other_last_revision = other.last_revision_info()
674
stop_revno = None # unknown
675
if stop_revision is None:
676
stop_revision = other_last_revision
677
if _mod_revision.is_null(stop_revision):
678
# if there are no commits, we're done.
680
stop_revno = other_revno
682
# what's the current last revision, before we fetch [and change it
684
last_rev = _mod_revision.ensure_null(self.last_revision())
685
# we fetch here so that we don't process data twice in the common
686
# case of having something to pull, and so that the check for
687
# already merged can operate on the just fetched graph, which will
688
# be cached in memory.
689
self.fetch(other, stop_revision)
690
# Check to see if one is an ancestor of the other
693
graph = self.repository.get_graph()
694
if self._check_if_descendant_or_diverged(
695
stop_revision, last_rev, graph, other):
696
# stop_revision is a descendant of last_rev, but we aren't
697
# overwriting, so we're done.
699
if stop_revno is None:
701
graph = self.repository.get_graph()
702
this_revno, this_last_revision = self.last_revision_info()
703
stop_revno = graph.find_distance_to_null(stop_revision,
704
[(other_last_revision, other_revno),
705
(this_last_revision, this_revno)])
706
self.set_last_revision_info(stop_revno, stop_revision)
1047
def _read_last_revision_info(self):
1048
raise NotImplementedError(self._read_last_revision_info)
1050
@deprecated_method(deprecated_in((2, 4, 0)))
1051
def import_last_revision_info(self, source_repo, revno, revid):
1052
"""Set the last revision info, importing from another repo if necessary.
1054
:param source_repo: Source repository to optionally fetch from
1055
:param revno: Revision number of the new tip
1056
:param revid: Revision id of the new tip
1058
if not self.repository.has_same_location(source_repo):
1059
self.repository.fetch(source_repo, revision_id=revid)
1060
self.set_last_revision_info(revno, revid)
1062
def import_last_revision_info_and_tags(self, source, revno, revid,
1064
"""Set the last revision info, importing from another repo if necessary.
1066
This is used by the bound branch code to upload a revision to
1067
the master branch first before updating the tip of the local branch.
1068
Revisions referenced by source's tags are also transferred.
1070
:param source: Source branch to optionally fetch from
1071
:param revno: Revision number of the new tip
1072
:param revid: Revision id of the new tip
1073
:param lossy: Whether to discard metadata that can not be
1074
natively represented
1075
:return: Tuple with the new revision number and revision id
1076
(should only be different from the arguments when lossy=True)
1078
if not self.repository.has_same_location(source.repository):
1079
self.fetch(source, revid)
1080
self.set_last_revision_info(revno, revid)
1081
return (revno, revid)
710
1083
def revision_id_to_revno(self, revision_id):
711
1084
"""Given a revision id, return its revno"""
886
1327
source_revno, source_revision_id = self.last_revision_info()
887
1328
if revision_id is None:
888
1329
revno, revision_id = source_revno, source_revision_id
889
elif source_revision_id == revision_id:
890
# we know the revno without needing to walk all of history
893
# To figure out the revno for a random revision, we need to build
894
# the revision history, and count its length.
895
# We don't care about the order, just how long it is.
896
# Alternatively, we could start at the current location, and count
897
# backwards. But there is no guarantee that we will find it since
898
# it may be a merged revision.
899
revno = len(list(self.repository.iter_reverse_revision_history(
1331
graph = self.repository.get_graph()
1333
revno = graph.find_distance_to_null(revision_id,
1334
[(source_revision_id, source_revno)])
1335
except errors.GhostRevisionsHaveNoRevno:
1336
# Default to 1, if we can't find anything else
901
1338
destination.set_last_revision_info(revno, revision_id)
904
1340
def copy_content_into(self, destination, revision_id=None):
905
1341
"""Copy the content of self into destination.
907
1343
revision_id: if not None, the revision history in the new branch will
908
1344
be truncated to end with revision_id.
910
self._synchronize_history(destination, revision_id)
912
parent = self.get_parent()
913
except errors.InaccessibleParent, e:
914
mutter('parent was not accessible to copy: %s', e)
917
destination.set_parent(parent)
918
self.tags.merge_to(destination.tags)
1346
return InterBranch.get(self, destination).copy_content_into(
1347
revision_id=revision_id)
1349
def update_references(self, target):
1350
if not getattr(self._format, 'supports_reference_locations', False):
1352
reference_dict = self._get_all_reference_info()
1353
if len(reference_dict) == 0:
1355
old_base = self.base
1356
new_base = target.base
1357
target_reference_dict = target._get_all_reference_info()
1358
for file_id, (tree_path, branch_location) in (
1359
reference_dict.items()):
1360
branch_location = urlutils.rebase_url(branch_location,
1362
target_reference_dict.setdefault(
1363
file_id, (tree_path, branch_location))
1364
target._set_all_reference_info(target_reference_dict)
920
1366
@needs_read_lock
1367
def check(self, refs):
922
1368
"""Check consistency of the branch.
924
1370
In particular this checks that revisions given in the revision-history
925
do actually match up in the revision graph, and that they're all
1371
do actually match up in the revision graph, and that they're all
926
1372
present in the repository.
928
1374
Callers will typically also want to check the repository.
1376
:param refs: Calculated refs for this branch as specified by
1377
branch._get_check_refs()
930
1378
:return: A BranchCheckResult.
932
mainline_parent_id = None
1380
result = BranchCheckResult(self)
933
1381
last_revno, last_revision_id = self.last_revision_info()
934
real_rev_history = list(self.repository.iter_reverse_revision_history(
936
real_rev_history.reverse()
937
if len(real_rev_history) != last_revno:
938
raise errors.BzrCheckError('revno does not match len(mainline)'
939
' %s != %s' % (last_revno, len(real_rev_history)))
940
# TODO: We should probably also check that real_rev_history actually
941
# matches self.revision_history()
942
for revision_id in real_rev_history:
944
revision = self.repository.get_revision(revision_id)
945
except errors.NoSuchRevision, e:
946
raise errors.BzrCheckError("mainline revision {%s} not in repository"
948
# In general the first entry on the revision history has no parents.
949
# But it's not illegal for it to have parents listed; this can happen
950
# in imports from Arch when the parents weren't reachable.
951
if mainline_parent_id is not None:
952
if mainline_parent_id not in revision.parent_ids:
953
raise errors.BzrCheckError("previous revision {%s} not listed among "
955
% (mainline_parent_id, revision_id))
956
mainline_parent_id = revision_id
957
return BranchCheckResult(self)
1382
actual_revno = refs[('lefthand-distance', last_revision_id)]
1383
if actual_revno != last_revno:
1384
result.errors.append(errors.BzrCheckError(
1385
'revno does not match len(mainline) %s != %s' % (
1386
last_revno, actual_revno)))
1387
# TODO: We should probably also check that self.revision_history
1388
# matches the repository for older branch formats.
1389
# If looking for the code that cross-checks repository parents against
1390
# the iter_reverse_revision_history output, that is now a repository
959
def _get_checkout_format(self):
1394
def _get_checkout_format(self, lightweight=False):
960
1395
"""Return the most suitable metadir for a checkout of this branch.
961
1396
Weaves are used if this branch's repository uses weaves.
963
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
964
from bzrlib.repofmt import weaverepo
965
format = bzrdir.BzrDirMetaFormat1()
966
format.repository_format = weaverepo.RepositoryFormat7()
968
format = self.repository.bzrdir.checkout_metadir()
969
format.set_branch_format(self._format)
1398
format = self.repository.bzrdir.checkout_metadir()
1399
format.set_branch_format(self._format)
1402
def create_clone_on_transport(self, to_transport, revision_id=None,
1403
stacked_on=None, create_prefix=False, use_existing_dir=False,
1405
"""Create a clone of this branch and its bzrdir.
1407
:param to_transport: The transport to clone onto.
1408
:param revision_id: The revision id to use as tip in the new branch.
1409
If None the tip is obtained from this branch.
1410
:param stacked_on: An optional URL to stack the clone on.
1411
:param create_prefix: Create any missing directories leading up to
1413
:param use_existing_dir: Use an existing directory if one exists.
1415
# XXX: Fix the bzrdir API to allow getting the branch back from the
1416
# clone call. Or something. 20090224 RBC/spiv.
1417
# XXX: Should this perhaps clone colocated branches as well,
1418
# rather than just the default branch? 20100319 JRV
1419
if revision_id is None:
1420
revision_id = self.last_revision()
1421
dir_to = self.bzrdir.clone_on_transport(to_transport,
1422
revision_id=revision_id, stacked_on=stacked_on,
1423
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1425
return dir_to.open_branch()
972
1427
def create_checkout(self, to_location, revision_id=None,
973
1428
lightweight=False, accelerator_tree=None,
974
1429
hardlink=False):
975
1430
"""Create a checkout of a branch.
977
1432
:param to_location: The url to produce the checkout at
978
1433
:param revision_id: The revision to check out
979
1434
:param lightweight: If True, produce a lightweight checkout, otherwise,
980
produce a bound branch (heavyweight checkout)
1435
produce a bound branch (heavyweight checkout)
981
1436
:param accelerator_tree: A tree which can be used for retrieving file
982
1437
contents more quickly than the revision tree, i.e. a workingtree.
983
1438
The revision tree will be used for cases where accelerator_tree's
1154
1655
"""Return the short format description for this format."""
1155
1656
raise NotImplementedError(self.get_format_description)
1157
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1159
"""Initialize a branch in a bzrdir, with specified files
1658
def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1659
hooks = Branch.hooks['post_branch_init']
1662
params = BranchInitHookParams(self, a_bzrdir, name, branch)
1161
:param a_bzrdir: The bzrdir to initialize the branch in
1162
:param utf8_files: The files to create as a list of
1163
(filename, content) tuples
1164
:param set_format: If True, set the format with
1165
self.get_format_string. (BzrBranch4 has its format set
1167
:return: a branch in this format
1666
def initialize(self, a_bzrdir, name=None, repository=None,
1667
append_revisions_only=None):
1668
"""Create a branch of this format in a_bzrdir.
1670
:param name: Name of the colocated branch to create.
1169
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1170
branch_transport = a_bzrdir.get_branch_transport(self)
1172
'metadir': ('lock', lockdir.LockDir),
1173
'branch4': ('branch-lock', lockable_files.TransportLock),
1175
lock_name, lock_class = lock_map[lock_type]
1176
control_files = lockable_files.LockableFiles(branch_transport,
1177
lock_name, lock_class)
1178
control_files.create_lock()
1179
control_files.lock_write()
1181
utf8_files += [('format', self.get_format_string())]
1183
for (filename, content) in utf8_files:
1184
branch_transport.put_bytes(
1186
mode=a_bzrdir._get_file_mode())
1188
control_files.unlock()
1189
return self.open(a_bzrdir, _found=True)
1191
def initialize(self, a_bzrdir):
1192
"""Create a branch of this format in a_bzrdir."""
1193
1672
raise NotImplementedError(self.initialize)
1195
1674
def is_supported(self):
1196
1675
"""Is this format supported?
1198
1677
Supported formats can be initialized and opened.
1199
Unsupported formats may not support initialization or committing or
1678
Unsupported formats may not support initialization or committing or
1200
1679
some other features depending on the reason for not being supported.
1204
def open(self, a_bzrdir, _found=False):
1683
def make_tags(self, branch):
1684
"""Create a tags object for branch.
1686
This method is on BranchFormat, because BranchFormats are reflected
1687
over the wire via network_name(), whereas full Branch instances require
1688
multiple VFS method calls to operate at all.
1690
The default implementation returns a disabled-tags instance.
1692
Note that it is normal for branch to be a RemoteBranch when using tags
1695
return _mod_tag.DisabledTags(branch)
1697
def network_name(self):
1698
"""A simple byte string uniquely identifying this format for RPC calls.
1700
MetaDir branch formats use their disk format string to identify the
1701
repository over the wire. All in one formats such as bzr < 0.8, and
1702
foreign formats like svn/git and hg should use some marker which is
1703
unique and immutable.
1705
raise NotImplementedError(self.network_name)
1707
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1708
found_repository=None):
1205
1709
"""Return the branch object for a_bzrdir
1207
_found is a private parameter, do not use it. It is used to indicate
1208
if format probing has already be done.
1711
:param a_bzrdir: A BzrDir that contains a branch.
1712
:param name: Name of colocated branch to open
1713
:param _found: a private parameter, do not use it. It is used to
1714
indicate if format probing has already be done.
1715
:param ignore_fallbacks: when set, no fallback branches will be opened
1716
(if there are any). Default is to open fallbacks.
1210
1718
raise NotImplementedError(self.open)
1721
@deprecated_method(deprecated_in((2, 4, 0)))
1213
1722
def register_format(klass, format):
1214
klass._formats[format.get_format_string()] = format
1723
"""Register a metadir format.
1725
See MetaDirBranchFormatFactory for the ability to register a format
1726
without loading the code the format needs until it is actually used.
1728
format_registry.register(format)
1731
@deprecated_method(deprecated_in((2, 4, 0)))
1217
1732
def set_default_format(klass, format):
1218
klass._default_format = format
1733
format_registry.set_default(format)
1735
def supports_set_append_revisions_only(self):
1736
"""True if this format supports set_append_revisions_only."""
1220
1739
def supports_stacking(self):
1221
1740
"""True if this format records a stacked-on branch."""
1743
def supports_leaving_lock(self):
1744
"""True if this format supports leaving locks in place."""
1745
return False # by default
1748
@deprecated_method(deprecated_in((2, 4, 0)))
1225
1749
def unregister_format(klass, format):
1226
del klass._formats[format.get_format_string()]
1750
format_registry.remove(format)
1228
1752
def __str__(self):
1229
return self.get_format_string().rstrip()
1753
return self.get_format_description().rstrip()
1231
1755
def supports_tags(self):
1232
1756
"""True if this format supports tags stored in the branch"""
1233
1757
return False # by default
1759
def tags_are_versioned(self):
1760
"""Whether the tag container for this branch versions tags."""
1763
def supports_tags_referencing_ghosts(self):
1764
"""True if tags can reference ghost revisions."""
1768
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1769
"""A factory for a BranchFormat object, permitting simple lazy registration.
1771
While none of the built in BranchFormats are lazy registered yet,
1772
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1773
use it, and the bzr-loom plugin uses it as well (see
1774
bzrlib.plugins.loom.formats).
1777
def __init__(self, format_string, module_name, member_name):
1778
"""Create a MetaDirBranchFormatFactory.
1780
:param format_string: The format string the format has.
1781
:param module_name: Module to load the format class from.
1782
:param member_name: Attribute name within the module for the format class.
1784
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1785
self._format_string = format_string
1787
def get_format_string(self):
1788
"""See BranchFormat.get_format_string."""
1789
return self._format_string
1792
"""Used for network_format_registry support."""
1793
return self.get_obj()()
1236
1796
class BranchHooks(Hooks):
1237
1797
"""A dictionary mapping hook name to a list of callables for branch hooks.
1239
1799
e.g. ['set_rh'] Is the list of items to be called when the
1240
1800
set_revision_history function is invoked.
1246
1806
These are all empty initially, because by default nothing should get
1249
Hooks.__init__(self)
1250
# Introduced in 0.15:
1251
# invoked whenever the revision history has been set
1252
# with set_revision_history. The api signature is
1253
# (branch, revision_history), and the branch will
1256
# Invoked after a branch is opened. The api signature is (branch).
1258
# invoked after a push operation completes.
1259
# the api signature is
1261
# containing the members
1262
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1263
# where local is the local target branch or None, master is the target
1264
# master branch, and the rest should be self explanatory. The source
1265
# is read locked and the target branches write locked. Source will
1266
# be the local low-latency branch.
1267
self['post_push'] = []
1268
# invoked after a pull operation completes.
1269
# the api signature is
1271
# containing the members
1272
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1273
# where local is the local branch or None, master is the target
1274
# master branch, and the rest should be self explanatory. The source
1275
# is read locked and the target branches write locked. The local
1276
# branch is the low-latency branch.
1277
self['post_pull'] = []
1278
# invoked before a commit operation takes place.
1279
# the api signature is
1280
# (local, master, old_revno, old_revid, future_revno, future_revid,
1281
# tree_delta, future_tree).
1282
# old_revid is NULL_REVISION for the first commit to a branch
1283
# tree_delta is a TreeDelta object describing changes from the basis
1284
# revision, hooks MUST NOT modify this delta
1285
# future_tree is an in-memory tree obtained from
1286
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1287
self['pre_commit'] = []
1288
# invoked after a commit operation completes.
1289
# the api signature is
1290
# (local, master, old_revno, old_revid, new_revno, new_revid)
1291
# old_revid is NULL_REVISION for the first commit to a branch.
1292
self['post_commit'] = []
1293
# invoked after a uncommit operation completes.
1294
# the api signature is
1295
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1296
# local is the local branch or None, master is the target branch,
1297
# and an empty branch recieves new_revno of 0, new_revid of None.
1298
self['post_uncommit'] = []
1300
# Invoked before the tip of a branch changes.
1301
# the api signature is
1302
# (params) where params is a ChangeBranchTipParams with the members
1303
# (branch, old_revno, new_revno, old_revid, new_revid)
1304
self['pre_change_branch_tip'] = []
1306
# Invoked after the tip of a branch changes.
1307
# the api signature is
1308
# (params) where params is a ChangeBranchTipParams with the members
1309
# (branch, old_revno, new_revno, old_revid, new_revid)
1310
self['post_change_branch_tip'] = []
1312
# Invoked when a stacked branch activates its fallback locations and
1313
# allows the transformation of the url of said location.
1314
# the api signature is
1315
# (branch, url) where branch is the branch having its fallback
1316
# location activated and url is the url for the fallback location.
1317
# The hook should return a url.
1318
self['transform_fallback_location'] = []
1809
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1810
self.add_hook('set_rh',
1811
"Invoked whenever the revision history has been set via "
1812
"set_revision_history. The api signature is (branch, "
1813
"revision_history), and the branch will be write-locked. "
1814
"The set_rh hook can be expensive for bzr to trigger, a better "
1815
"hook to use is Branch.post_change_branch_tip.", (0, 15))
1816
self.add_hook('open',
1817
"Called with the Branch object that has been opened after a "
1818
"branch is opened.", (1, 8))
1819
self.add_hook('post_push',
1820
"Called after a push operation completes. post_push is called "
1821
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1822
"bzr client.", (0, 15))
1823
self.add_hook('post_pull',
1824
"Called after a pull operation completes. post_pull is called "
1825
"with a bzrlib.branch.PullResult object and only runs in the "
1826
"bzr client.", (0, 15))
1827
self.add_hook('pre_commit',
1828
"Called after a commit is calculated but before it is "
1829
"completed. pre_commit is called with (local, master, old_revno, "
1830
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1831
"). old_revid is NULL_REVISION for the first commit to a branch, "
1832
"tree_delta is a TreeDelta object describing changes from the "
1833
"basis revision. hooks MUST NOT modify this delta. "
1834
" future_tree is an in-memory tree obtained from "
1835
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1837
self.add_hook('post_commit',
1838
"Called in the bzr client after a commit has completed. "
1839
"post_commit is called with (local, master, old_revno, old_revid, "
1840
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1841
"commit to a branch.", (0, 15))
1842
self.add_hook('post_uncommit',
1843
"Called in the bzr client after an uncommit completes. "
1844
"post_uncommit is called with (local, master, old_revno, "
1845
"old_revid, new_revno, new_revid) where local is the local branch "
1846
"or None, master is the target branch, and an empty branch "
1847
"receives new_revno of 0, new_revid of None.", (0, 15))
1848
self.add_hook('pre_change_branch_tip',
1849
"Called in bzr client and server before a change to the tip of a "
1850
"branch is made. pre_change_branch_tip is called with a "
1851
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1852
"commit, uncommit will all trigger this hook.", (1, 6))
1853
self.add_hook('post_change_branch_tip',
1854
"Called in bzr client and server after a change to the tip of a "
1855
"branch is made. post_change_branch_tip is called with a "
1856
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1857
"commit, uncommit will all trigger this hook.", (1, 4))
1858
self.add_hook('transform_fallback_location',
1859
"Called when a stacked branch is activating its fallback "
1860
"locations. transform_fallback_location is called with (branch, "
1861
"url), and should return a new url. Returning the same url "
1862
"allows it to be used as-is, returning a different one can be "
1863
"used to cause the branch to stack on a closer copy of that "
1864
"fallback_location. Note that the branch cannot have history "
1865
"accessing methods called on it during this hook because the "
1866
"fallback locations have not been activated. When there are "
1867
"multiple hooks installed for transform_fallback_location, "
1868
"all are called with the url returned from the previous hook."
1869
"The order is however undefined.", (1, 9))
1870
self.add_hook('automatic_tag_name',
1871
"Called to determine an automatic tag name for a revision. "
1872
"automatic_tag_name is called with (branch, revision_id) and "
1873
"should return a tag name or None if no tag name could be "
1874
"determined. The first non-None tag name returned will be used.",
1876
self.add_hook('post_branch_init',
1877
"Called after new branch initialization completes. "
1878
"post_branch_init is called with a "
1879
"bzrlib.branch.BranchInitHookParams. "
1880
"Note that init, branch and checkout (both heavyweight and "
1881
"lightweight) will all trigger this hook.", (2, 2))
1882
self.add_hook('post_switch',
1883
"Called after a checkout switches branch. "
1884
"post_switch is called with a "
1885
"bzrlib.branch.SwitchHookParams.", (2, 2))
1321
1889
# install the default hooks into the Branch class.
1354
1922
def __eq__(self, other):
1355
1923
return self.__dict__ == other.__dict__
1357
1925
def __repr__(self):
1358
1926
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1359
self.__class__.__name__, self.branch,
1927
self.__class__.__name__, self.branch,
1360
1928
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1363
class BzrBranchFormat4(BranchFormat):
1364
"""Bzr branch format 4.
1367
- a revision-history file.
1368
- a branch-lock lock file [ to be shared with the bzrdir ]
1371
def get_format_description(self):
1372
"""See BranchFormat.get_format_description()."""
1373
return "Branch format 4"
1375
def initialize(self, a_bzrdir):
1376
"""Create a branch of this format in a_bzrdir."""
1377
utf8_files = [('revision-history', ''),
1378
('branch-name', ''),
1380
return self._initialize_helper(a_bzrdir, utf8_files,
1381
lock_type='branch4', set_format=False)
1384
super(BzrBranchFormat4, self).__init__()
1385
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1387
def open(self, a_bzrdir, _found=False):
1388
"""Return the branch object for a_bzrdir
1390
_found is a private parameter, do not use it. It is used to indicate
1391
if format probing has already be done.
1394
# we are being called directly and must probe.
1395
raise NotImplementedError
1396
return BzrBranch(_format=self,
1397
_control_files=a_bzrdir._control_files,
1399
_repository=a_bzrdir.open_repository())
1402
return "Bazaar-NG branch format 4"
1931
class BranchInitHookParams(object):
1932
"""Object holding parameters passed to `*_branch_init` hooks.
1934
There are 4 fields that hooks may wish to access:
1936
:ivar format: the branch format
1937
:ivar bzrdir: the BzrDir where the branch will be/has been initialized
1938
:ivar name: name of colocated branch, if any (or None)
1939
:ivar branch: the branch created
1941
Note that for lightweight checkouts, the bzrdir and format fields refer to
1942
the checkout, hence they are different from the corresponding fields in
1943
branch, which refer to the original branch.
1946
def __init__(self, format, a_bzrdir, name, branch):
1947
"""Create a group of BranchInitHook parameters.
1949
:param format: the branch format
1950
:param a_bzrdir: the BzrDir where the branch will be/has been
1952
:param name: name of colocated branch, if any (or None)
1953
:param branch: the branch created
1955
Note that for lightweight checkouts, the bzrdir and format fields refer
1956
to the checkout, hence they are different from the corresponding fields
1957
in branch, which refer to the original branch.
1959
self.format = format
1960
self.bzrdir = a_bzrdir
1962
self.branch = branch
1964
def __eq__(self, other):
1965
return self.__dict__ == other.__dict__
1968
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1971
class SwitchHookParams(object):
1972
"""Object holding parameters passed to `*_switch` hooks.
1974
There are 4 fields that hooks may wish to access:
1976
:ivar control_dir: BzrDir of the checkout to change
1977
:ivar to_branch: branch that the checkout is to reference
1978
:ivar force: skip the check for local commits in a heavy checkout
1979
:ivar revision_id: revision ID to switch to (or None)
1982
def __init__(self, control_dir, to_branch, force, revision_id):
1983
"""Create a group of SwitchHook parameters.
1985
:param control_dir: BzrDir of the checkout to change
1986
:param to_branch: branch that the checkout is to reference
1987
:param force: skip the check for local commits in a heavy checkout
1988
:param revision_id: revision ID to switch to (or None)
1990
self.control_dir = control_dir
1991
self.to_branch = to_branch
1993
self.revision_id = revision_id
1995
def __eq__(self, other):
1996
return self.__dict__ == other.__dict__
1999
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
2000
self.control_dir, self.to_branch,
1405
2004
class BranchFormatMetadir(BranchFormat):
1409
2008
"""What class to instantiate on open calls."""
1410
2009
raise NotImplementedError(self._branch_class)
1412
def open(self, a_bzrdir, _found=False):
1413
"""Return the branch object for a_bzrdir.
1415
_found is a private parameter, do not use it. It is used to indicate
1416
if format probing has already be done.
2011
def _get_initial_config(self, append_revisions_only=None):
2012
if append_revisions_only:
2013
return "append_revisions_only = True\n"
2015
# Avoid writing anything if append_revisions_only is disabled,
2016
# as that is the default.
2019
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2021
"""Initialize a branch in a bzrdir, with specified files
2023
:param a_bzrdir: The bzrdir to initialize the branch in
2024
:param utf8_files: The files to create as a list of
2025
(filename, content) tuples
2026
:param name: Name of colocated branch to create, if any
2027
:return: a branch in this format
2029
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2030
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2031
control_files = lockable_files.LockableFiles(branch_transport,
2032
'lock', lockdir.LockDir)
2033
control_files.create_lock()
2034
control_files.lock_write()
2036
utf8_files += [('format', self.get_format_string())]
2037
for (filename, content) in utf8_files:
2038
branch_transport.put_bytes(
2040
mode=a_bzrdir._get_file_mode())
2042
control_files.unlock()
2043
branch = self.open(a_bzrdir, name, _found=True,
2044
found_repository=repository)
2045
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2048
def network_name(self):
2049
"""A simple byte string uniquely identifying this format for RPC calls.
2051
Metadir branch formats use their format string.
2053
return self.get_format_string()
2055
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2056
found_repository=None):
2057
"""See BranchFormat.open()."""
1419
format = BranchFormat.find_format(a_bzrdir)
2059
format = BranchFormat.find_format(a_bzrdir, name=name)
1420
2060
if format.__class__ != self.__class__:
1421
2061
raise AssertionError("wrong format %r found for %r" %
1422
2062
(format, self))
2063
transport = a_bzrdir.get_branch_transport(None, name=name)
1424
transport = a_bzrdir.get_branch_transport(None)
1425
2065
control_files = lockable_files.LockableFiles(transport, 'lock',
1426
2066
lockdir.LockDir)
2067
if found_repository is None:
2068
found_repository = a_bzrdir.find_repository()
1427
2069
return self._branch_class()(_format=self,
1428
2070
_control_files=control_files,
1429
2072
a_bzrdir=a_bzrdir,
1430
_repository=a_bzrdir.find_repository())
2073
_repository=found_repository,
2074
ignore_fallbacks=ignore_fallbacks)
1431
2075
except errors.NoSuchFile:
1432
raise errors.NotBranchError(path=transport.base)
2076
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1434
2078
def __init__(self):
1435
2079
super(BranchFormatMetadir, self).__init__()
2353
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2354
"""Branch format registry."""
2356
def __init__(self, other_registry=None):
2357
super(BranchFormatRegistry, self).__init__(other_registry)
2358
self._default_format = None
2360
def set_default(self, format):
2361
self._default_format = format
2363
def get_default(self):
2364
return self._default_format
2367
network_format_registry = registry.FormatRegistry()
2368
"""Registry of formats indexed by their network name.
2370
The network name for a branch format is an identifier that can be used when
2371
referring to formats with smart server operations. See
2372
BranchFormat.network_name() for more detail.
2375
format_registry = BranchFormatRegistry(network_format_registry)
1634
2378
# formats which have no format string are not discoverable
1635
2379
# and not independently creatable, so are not registered.
1636
2380
__format5 = BzrBranchFormat5()
1637
2381
__format6 = BzrBranchFormat6()
1638
2382
__format7 = BzrBranchFormat7()
1639
BranchFormat.register_format(__format5)
1640
BranchFormat.register_format(BranchReferenceFormat())
1641
BranchFormat.register_format(__format6)
1642
BranchFormat.register_format(__format7)
1643
BranchFormat.set_default_format(__format6)
1644
_legacy_formats = [BzrBranchFormat4(),
1647
class BzrBranch(Branch):
2383
__format8 = BzrBranchFormat8()
2384
format_registry.register(__format5)
2385
format_registry.register(BranchReferenceFormat())
2386
format_registry.register(__format6)
2387
format_registry.register(__format7)
2388
format_registry.register(__format8)
2389
format_registry.set_default(__format7)
2392
class BranchWriteLockResult(LogicalLockResult):
2393
"""The result of write locking a branch.
2395
:ivar branch_token: The token obtained from the underlying branch lock, or
2397
:ivar unlock: A callable which will unlock the lock.
2400
def __init__(self, unlock, branch_token):
2401
LogicalLockResult.__init__(self, unlock)
2402
self.branch_token = branch_token
2405
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2409
class BzrBranch(Branch, _RelockDebugMixin):
1648
2410
"""A branch stored in the actual filesystem.
1650
2412
Note that it's "local" in the context of the filesystem; it doesn't
1651
2413
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1652
2414
it's writable, and can be accessed via the normal filesystem API.
1654
:ivar _transport: Transport for file operations on this branch's
2416
:ivar _transport: Transport for file operations on this branch's
1655
2417
control files, typically pointing to the .bzr/branch directory.
1656
2418
:ivar repository: Repository for this branch.
1657
:ivar base: The url of the base directory for this branch; the one
2419
:ivar base: The url of the base directory for this branch; the one
1658
2420
containing the .bzr directory.
2421
:ivar name: Optional colocated branch name as it exists in the control
1661
2425
def __init__(self, _format=None,
1662
_control_files=None, a_bzrdir=None, _repository=None):
2426
_control_files=None, a_bzrdir=None, name=None,
2427
_repository=None, ignore_fallbacks=False):
1663
2428
"""Create new branch object at a particular location."""
1664
2429
if a_bzrdir is None:
1665
2430
raise ValueError('a_bzrdir must be supplied')
1667
2432
self.bzrdir = a_bzrdir
1668
2433
self._base = self.bzrdir.transport.clone('..').base
1669
2435
# XXX: We should be able to just do
1670
2436
# self.base = self.bzrdir.root_transport.base
1671
2437
# but this does not quite work yet -- mbp 20080522
1732
2540
"""See Branch.print_file."""
1733
2541
return self.repository.print_file(file, revision_id)
1735
def _write_revision_history(self, history):
1736
"""Factored out of set_revision_history.
1738
This performs the actual writing to disk.
1739
It is intended to be called by BzrBranch5.set_revision_history."""
1740
self._transport.put_bytes(
1741
'revision-history', '\n'.join(history),
1742
mode=self.bzrdir._get_file_mode())
1745
def set_revision_history(self, rev_history):
1746
"""See Branch.set_revision_history."""
1747
if 'evil' in debug.debug_flags:
1748
mutter_callsite(3, "set_revision_history scales with history.")
1749
check_not_reserved_id = _mod_revision.check_not_reserved_id
1750
for rev_id in rev_history:
1751
check_not_reserved_id(rev_id)
1752
if Branch.hooks['post_change_branch_tip']:
1753
# Don't calculate the last_revision_info() if there are no hooks
1755
old_revno, old_revid = self.last_revision_info()
1756
if len(rev_history) == 0:
1757
revid = _mod_revision.NULL_REVISION
1759
revid = rev_history[-1]
1760
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1761
self._write_revision_history(rev_history)
1762
self._clear_cached_state()
1763
self._cache_revision_history(rev_history)
1764
for hook in Branch.hooks['set_rh']:
1765
hook(self, rev_history)
1766
if Branch.hooks['post_change_branch_tip']:
1767
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1769
def _synchronize_history(self, destination, revision_id):
1770
"""Synchronize last revision and revision history between branches.
1772
This version is most efficient when the destination is also a
1773
BzrBranch5, but works for BzrBranch6 as long as the revision
1774
history is the true lefthand parent history, and all of the revisions
1775
are in the destination's repository. If not, set_revision_history
1778
:param destination: The branch to copy the history into
1779
:param revision_id: The revision-id to truncate history at. May
1780
be None to copy complete history.
1782
if not isinstance(destination._format, BzrBranchFormat5):
1783
super(BzrBranch, self)._synchronize_history(
1784
destination, revision_id)
1786
if revision_id == _mod_revision.NULL_REVISION:
1789
new_history = self.revision_history()
1790
if revision_id is not None and new_history != []:
1792
new_history = new_history[:new_history.index(revision_id) + 1]
1794
rev = self.repository.get_revision(revision_id)
1795
new_history = rev.get_history(self.repository)[1:]
1796
destination.set_revision_history(new_history)
1798
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1799
"""Run the pre_change_branch_tip hooks."""
1800
hooks = Branch.hooks['pre_change_branch_tip']
1803
old_revno, old_revid = self.last_revision_info()
1804
params = ChangeBranchTipParams(
1805
self, old_revno, new_revno, old_revid, new_revid)
1809
except errors.TipChangeRejected:
1812
exc_info = sys.exc_info()
1813
hook_name = Branch.hooks.get_hook_name(hook)
1814
raise errors.HookFailed(
1815
'pre_change_branch_tip', hook_name, exc_info)
1817
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1818
"""Run the post_change_branch_tip hooks."""
1819
hooks = Branch.hooks['post_change_branch_tip']
1822
new_revno, new_revid = self.last_revision_info()
1823
params = ChangeBranchTipParams(
1824
self, old_revno, new_revno, old_revid, new_revid)
1828
2543
@needs_write_lock
1829
2544
def set_last_revision_info(self, revno, revision_id):
1830
"""Set the last revision of this branch.
1832
The caller is responsible for checking that the revno is correct
1833
for this revision id.
1835
It may be possible to set the branch last revision to an id not
1836
present in the repository. However, branches can also be
1837
configured to check constraints on history, in which case this may not
2545
if not revision_id or not isinstance(revision_id, basestring):
2546
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
1840
2547
revision_id = _mod_revision.ensure_null(revision_id)
1841
# this old format stores the full history, but this api doesn't
1842
# provide it, so we must generate, and might as well check it's
1844
history = self._lefthand_history(revision_id)
1845
if len(history) != revno:
1846
raise AssertionError('%d != %d' % (len(history), revno))
1847
self.set_revision_history(history)
1849
def _gen_revision_history(self):
1850
history = self._transport.get_bytes('revision-history').split('\n')
1851
if history[-1:] == ['']:
1852
# There shouldn't be a trailing newline, but just in case.
1856
def _lefthand_history(self, revision_id, last_rev=None,
1858
if 'evil' in debug.debug_flags:
1859
mutter_callsite(4, "_lefthand_history scales with history.")
1860
# stop_revision must be a descendant of last_revision
1861
graph = self.repository.get_graph()
1862
if last_rev is not None:
1863
if not graph.is_ancestor(last_rev, revision_id):
1864
# our previous tip is not merged into stop_revision
1865
raise errors.DivergedBranches(self, other_branch)
1866
# make a new revision history from the graph
1867
parents_map = graph.get_parent_map([revision_id])
1868
if revision_id not in parents_map:
1869
raise errors.NoSuchRevision(self, revision_id)
1870
current_rev_id = revision_id
1872
check_not_reserved_id = _mod_revision.check_not_reserved_id
1873
# Do not include ghosts or graph origin in revision_history
1874
while (current_rev_id in parents_map and
1875
len(parents_map[current_rev_id]) > 0):
1876
check_not_reserved_id(current_rev_id)
1877
new_history.append(current_rev_id)
1878
current_rev_id = parents_map[current_rev_id][0]
1879
parents_map = graph.get_parent_map([current_rev_id])
1880
new_history.reverse()
1884
def generate_revision_history(self, revision_id, last_rev=None,
1886
"""Create a new revision history that will finish with revision_id.
1888
:param revision_id: the new tip to use.
1889
:param last_rev: The previous last_revision. If not None, then this
1890
must be a ancestory of revision_id, or DivergedBranches is raised.
1891
:param other_branch: The other branch that DivergedBranches should
1892
raise with respect to.
1894
self.set_revision_history(self._lefthand_history(revision_id,
1895
last_rev, other_branch))
2548
old_revno, old_revid = self.last_revision_info()
2549
if self.get_append_revisions_only():
2550
self._check_history_violation(revision_id)
2551
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2552
self._write_last_revision_info(revno, revision_id)
2553
self._clear_cached_state()
2554
self._last_revision_info_cache = revno, revision_id
2555
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1897
2557
def basis_tree(self):
1898
2558
"""See Branch.basis_tree."""
1899
2559
return self.repository.revision_tree(self.last_revision())
1902
def pull(self, source, overwrite=False, stop_revision=None,
1903
_hook_master=None, run_hooks=True, possible_transports=None,
1904
_override_hook_target=None):
1907
:param _hook_master: Private parameter - set the branch to
1908
be supplied as the master to pull hooks.
1909
:param run_hooks: Private parameter - if false, this branch
1910
is being called because it's the master of the primary branch,
1911
so it should not run its hooks.
1912
:param _override_hook_target: Private parameter - set the branch to be
1913
supplied as the target_branch to pull hooks.
1915
result = PullResult()
1916
result.source_branch = source
1917
if _override_hook_target is None:
1918
result.target_branch = self
1920
result.target_branch = _override_hook_target
1923
# We assume that during 'pull' the local repository is closer than
1925
graph = self.repository.get_graph(source.repository)
1926
result.old_revno, result.old_revid = self.last_revision_info()
1927
self.update_revisions(source, stop_revision, overwrite=overwrite,
1929
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1930
result.new_revno, result.new_revid = self.last_revision_info()
1932
result.master_branch = _hook_master
1933
result.local_branch = result.target_branch
1935
result.master_branch = result.target_branch
1936
result.local_branch = None
1938
for hook in Branch.hooks['post_pull']:
1944
2561
def _get_parent_location(self):
1945
2562
_locs = ['parent', 'pull', 'x-pull']
1946
2563
for l in _locs:
1954
def push(self, target, overwrite=False, stop_revision=None,
1955
_override_hook_source_branch=None):
1958
This is the basic concrete implementation of push()
1960
:param _override_hook_source_branch: If specified, run
1961
the hooks passing this Branch as the source, rather than self.
1962
This is for use of RemoteBranch, where push is delegated to the
1963
underlying vfs-based Branch.
1965
# TODO: Public option to disable running hooks - should be trivial but
1967
return _run_with_write_locked_target(
1968
target, self._push_with_bound_branches, target, overwrite,
1970
_override_hook_source_branch=_override_hook_source_branch)
1972
def _push_with_bound_branches(self, target, overwrite,
1974
_override_hook_source_branch=None):
1975
"""Push from self into target, and into target's master if any.
1977
This is on the base BzrBranch class even though it doesn't support
1978
bound branches because the *target* might be bound.
1981
if _override_hook_source_branch:
1982
result.source_branch = _override_hook_source_branch
1983
for hook in Branch.hooks['post_push']:
1986
bound_location = target.get_bound_location()
1987
if bound_location and target.base != bound_location:
1988
# there is a master branch.
1990
# XXX: Why the second check? Is it even supported for a branch to
1991
# be bound to itself? -- mbp 20070507
1992
master_branch = target.get_master_branch()
1993
master_branch.lock_write()
1995
# push into the master from this branch.
1996
self._basic_push(master_branch, overwrite, stop_revision)
1997
# and push into the target branch from this. Note that we push from
1998
# this branch again, because its considered the highest bandwidth
2000
result = self._basic_push(target, overwrite, stop_revision)
2001
result.master_branch = master_branch
2002
result.local_branch = target
2006
master_branch.unlock()
2009
result = self._basic_push(target, overwrite, stop_revision)
2010
# TODO: Why set master_branch and local_branch if there's no
2011
# binding? Maybe cleaner to just leave them unset? -- mbp
2013
result.master_branch = target
2014
result.local_branch = None
2018
def _basic_push(self, target, overwrite, stop_revision):
2019
"""Basic implementation of push without bound branches or hooks.
2021
Must be called with self read locked and target write locked.
2023
result = PushResult()
2024
result.source_branch = self
2025
result.target_branch = target
2026
result.old_revno, result.old_revid = target.last_revision_info()
2027
if result.old_revid != self.last_revision():
2028
# We assume that during 'push' this repository is closer than
2030
graph = self.repository.get_graph(target.repository)
2031
target.update_revisions(self, stop_revision, overwrite=overwrite,
2033
if self._push_should_merge_tags():
2034
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2035
result.new_revno, result.new_revid = target.last_revision_info()
2038
def _push_should_merge_tags(self):
2039
"""Should _basic_push merge this branch's tags into the target?
2041
The default implementation returns False if this branch has no tags,
2042
and True the rest of the time. Subclasses may override this.
2044
return self.tags.supports_tags() and self.tags.get_tag_dict()
2046
def get_parent(self):
2047
"""See Branch.get_parent."""
2048
parent = self._get_parent_location()
2051
# This is an old-format absolute path to a local branch
2052
# turn it into a url
2053
if parent.startswith('/'):
2054
parent = urlutils.local_path_to_url(parent.decode('utf8'))
2056
return urlutils.join(self.base[:-1], parent)
2057
except errors.InvalidURLJoin, e:
2058
raise errors.InaccessibleParent(parent, self.base)
2060
2570
def get_stacked_on_url(self):
2061
raise errors.UnstackableBranchFormat(self._format, self.base)
2571
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2063
2573
def set_push_location(self, location):
2064
2574
"""See Branch.set_push_location."""
2091
2583
self._transport.put_bytes('parent', url + '\n',
2092
2584
mode=self.bzrdir._get_file_mode())
2094
def set_stacked_on_url(self, url):
2095
raise errors.UnstackableBranchFormat(self._format, self.base)
2098
class BzrBranch5(BzrBranch):
2099
"""A format 5 branch. This supports new features over plain branches.
2101
It has support for a master_branch which is the data for bound branches.
2105
def pull(self, source, overwrite=False, stop_revision=None,
2106
run_hooks=True, possible_transports=None,
2107
_override_hook_target=None):
2108
"""Pull from source into self, updating my master if any.
2110
:param run_hooks: Private parameter - if false, this branch
2111
is being called because it's the master of the primary branch,
2112
so it should not run its hooks.
2114
bound_location = self.get_bound_location()
2115
master_branch = None
2116
if bound_location and source.base != bound_location:
2117
# not pulling from master, so we need to update master.
2118
master_branch = self.get_master_branch(possible_transports)
2119
master_branch.lock_write()
2122
# pull from source into master.
2123
master_branch.pull(source, overwrite, stop_revision,
2125
return super(BzrBranch5, self).pull(source, overwrite,
2126
stop_revision, _hook_master=master_branch,
2127
run_hooks=run_hooks,
2128
_override_hook_target=_override_hook_target)
2131
master_branch.unlock()
2133
def get_bound_location(self):
2135
return self._transport.get_bytes('bound')[:-1]
2136
except errors.NoSuchFile:
2140
def get_master_branch(self, possible_transports=None):
2141
"""Return the branch we are bound to.
2143
:return: Either a Branch, or None
2145
This could memoise the branch, but if thats done
2146
it must be revalidated on each new lock.
2147
So for now we just don't memoise it.
2148
# RBC 20060304 review this decision.
2150
bound_loc = self.get_bound_location()
2154
return Branch.open(bound_loc,
2155
possible_transports=possible_transports)
2156
except (errors.NotBranchError, errors.ConnectionError), e:
2157
raise errors.BoundBranchConnectionFailure(
2161
def set_bound_location(self, location):
2162
"""Set the target where this branch is bound to.
2164
:param location: URL to the target branch
2167
self._transport.put_bytes('bound', location+'\n',
2168
mode=self.bzrdir._get_file_mode())
2171
self._transport.delete('bound')
2172
except errors.NoSuchFile:
2588
"""If bound, unbind"""
2589
return self.set_bound_location(None)
2176
2591
@needs_write_lock
2177
2592
def bind(self, other):
2225
class BzrBranch7(BzrBranch5):
2226
"""A branch with support for a fallback repository."""
2228
def _get_fallback_repository(self, url):
2229
"""Get the repository we fallback to at url."""
2230
url = urlutils.join(self.base, url)
2231
a_bzrdir = bzrdir.BzrDir.open(url,
2232
possible_transports=[self._transport])
2233
return a_bzrdir.open_branch().repository
2235
def _activate_fallback_location(self, url):
2236
"""Activate the branch/repository from url as a fallback repository."""
2237
self.repository.add_fallback_repository(
2238
self._get_fallback_repository(url))
2679
def _read_last_revision_info(self):
2680
revision_string = self._transport.get_bytes('last-revision')
2681
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2682
revision_id = cache_utf8.get_cached_utf8(revision_id)
2684
return revno, revision_id
2686
def _write_last_revision_info(self, revno, revision_id):
2687
"""Simply write out the revision id, with no checks.
2689
Use set_last_revision_info to perform this safely.
2691
Does not update the revision_history cache.
2693
revision_id = _mod_revision.ensure_null(revision_id)
2694
out_string = '%d %s\n' % (revno, revision_id)
2695
self._transport.put_bytes('last-revision', out_string,
2696
mode=self.bzrdir._get_file_mode())
2699
class FullHistoryBzrBranch(BzrBranch):
2700
"""Bzr branch which contains the full revision history."""
2703
def set_last_revision_info(self, revno, revision_id):
2704
if not revision_id or not isinstance(revision_id, basestring):
2705
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2706
revision_id = _mod_revision.ensure_null(revision_id)
2707
# this old format stores the full history, but this api doesn't
2708
# provide it, so we must generate, and might as well check it's
2710
history = self._lefthand_history(revision_id)
2711
if len(history) != revno:
2712
raise AssertionError('%d != %d' % (len(history), revno))
2713
self._set_revision_history(history)
2715
def _read_last_revision_info(self):
2716
rh = self.revision_history()
2719
return (revno, rh[-1])
2721
return (0, _mod_revision.NULL_REVISION)
2723
@deprecated_method(deprecated_in((2, 4, 0)))
2725
def set_revision_history(self, rev_history):
2726
"""See Branch.set_revision_history."""
2727
self._set_revision_history(rev_history)
2729
def _set_revision_history(self, rev_history):
2730
if 'evil' in debug.debug_flags:
2731
mutter_callsite(3, "set_revision_history scales with history.")
2732
check_not_reserved_id = _mod_revision.check_not_reserved_id
2733
for rev_id in rev_history:
2734
check_not_reserved_id(rev_id)
2735
if Branch.hooks['post_change_branch_tip']:
2736
# Don't calculate the last_revision_info() if there are no hooks
2738
old_revno, old_revid = self.last_revision_info()
2739
if len(rev_history) == 0:
2740
revid = _mod_revision.NULL_REVISION
2742
revid = rev_history[-1]
2743
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2744
self._write_revision_history(rev_history)
2745
self._clear_cached_state()
2746
self._cache_revision_history(rev_history)
2747
for hook in Branch.hooks['set_rh']:
2748
hook(self, rev_history)
2749
if Branch.hooks['post_change_branch_tip']:
2750
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2752
def _write_revision_history(self, history):
2753
"""Factored out of set_revision_history.
2755
This performs the actual writing to disk.
2756
It is intended to be called by set_revision_history."""
2757
self._transport.put_bytes(
2758
'revision-history', '\n'.join(history),
2759
mode=self.bzrdir._get_file_mode())
2761
def _gen_revision_history(self):
2762
history = self._transport.get_bytes('revision-history').split('\n')
2763
if history[-1:] == ['']:
2764
# There shouldn't be a trailing newline, but just in case.
2768
def _synchronize_history(self, destination, revision_id):
2769
if not isinstance(destination, FullHistoryBzrBranch):
2770
super(BzrBranch, self)._synchronize_history(
2771
destination, revision_id)
2773
if revision_id == _mod_revision.NULL_REVISION:
2776
new_history = self.revision_history()
2777
if revision_id is not None and new_history != []:
2779
new_history = new_history[:new_history.index(revision_id) + 1]
2781
rev = self.repository.get_revision(revision_id)
2782
new_history = rev.get_history(self.repository)[1:]
2783
destination._set_revision_history(new_history)
2786
def generate_revision_history(self, revision_id, last_rev=None,
2788
"""Create a new revision history that will finish with revision_id.
2790
:param revision_id: the new tip to use.
2791
:param last_rev: The previous last_revision. If not None, then this
2792
must be a ancestory of revision_id, or DivergedBranches is raised.
2793
:param other_branch: The other branch that DivergedBranches should
2794
raise with respect to.
2796
self._set_revision_history(self._lefthand_history(revision_id,
2797
last_rev, other_branch))
2800
class BzrBranch5(FullHistoryBzrBranch):
2801
"""A format 5 branch. This supports new features over plain branches.
2803
It has support for a master_branch which is the data for bound branches.
2807
class BzrBranch8(BzrBranch):
2808
"""A branch that stores tree-reference locations."""
2240
2810
def _open_hook(self):
2811
if self._ignore_fallbacks:
2242
2814
url = self.get_stacked_on_url()
2243
2815
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2253
2825
"None, not a URL." % hook_name)
2254
2826
self._activate_fallback_location(url)
2256
def _check_stackable_repo(self):
2257
if not self.repository._format.supports_external_lookups:
2258
raise errors.UnstackableRepositoryFormat(self.repository._format,
2259
self.repository.base)
2261
2828
def __init__(self, *args, **kwargs):
2262
super(BzrBranch7, self).__init__(*args, **kwargs)
2829
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2830
super(BzrBranch8, self).__init__(*args, **kwargs)
2263
2831
self._last_revision_info_cache = None
2264
self._partial_revision_history_cache = []
2832
self._reference_info = None
2266
2834
def _clear_cached_state(self):
2267
super(BzrBranch7, self)._clear_cached_state()
2835
super(BzrBranch8, self)._clear_cached_state()
2268
2836
self._last_revision_info_cache = None
2269
self._partial_revision_history_cache = []
2271
def _last_revision_info(self):
2272
revision_string = self._transport.get_bytes('last-revision')
2273
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2274
revision_id = cache_utf8.get_cached_utf8(revision_id)
2276
return revno, revision_id
2278
def _write_last_revision_info(self, revno, revision_id):
2279
"""Simply write out the revision id, with no checks.
2281
Use set_last_revision_info to perform this safely.
2283
Does not update the revision_history cache.
2284
Intended to be called by set_last_revision_info and
2285
_write_revision_history.
2287
revision_id = _mod_revision.ensure_null(revision_id)
2288
out_string = '%d %s\n' % (revno, revision_id)
2289
self._transport.put_bytes('last-revision', out_string,
2290
mode=self.bzrdir._get_file_mode())
2293
def set_last_revision_info(self, revno, revision_id):
2294
revision_id = _mod_revision.ensure_null(revision_id)
2295
old_revno, old_revid = self.last_revision_info()
2296
if self._get_append_revisions_only():
2297
self._check_history_violation(revision_id)
2298
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2299
self._write_last_revision_info(revno, revision_id)
2300
self._clear_cached_state()
2301
self._last_revision_info_cache = revno, revision_id
2302
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2304
def _synchronize_history(self, destination, revision_id):
2305
"""Synchronize last revision and revision history between branches.
2307
:see: Branch._synchronize_history
2309
# XXX: The base Branch has a fast implementation of this method based
2310
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2311
# that uses set_revision_history. This class inherits from BzrBranch5,
2312
# but wants the fast implementation, so it calls
2313
# Branch._synchronize_history directly.
2314
Branch._synchronize_history(self, destination, revision_id)
2837
self._reference_info = None
2316
2839
def _check_history_violation(self, revision_id):
2317
last_revision = _mod_revision.ensure_null(self.last_revision())
2840
current_revid = self.last_revision()
2841
last_revision = _mod_revision.ensure_null(current_revid)
2318
2842
if _mod_revision.is_null(last_revision):
2320
if last_revision not in self._lefthand_history(revision_id):
2321
raise errors.AppendRevisionsOnlyViolation(self.base)
2844
graph = self.repository.get_graph()
2845
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2846
if lh_ancestor == current_revid:
2848
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2323
2850
def _gen_revision_history(self):
2324
2851
"""Generate the revision history from last revision
2382
2864
"""Set the parent branch"""
2383
2865
return self._get_config_location('parent_location')
2868
def _set_all_reference_info(self, info_dict):
2869
"""Replace all reference info stored in a branch.
2871
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2874
writer = rio.RioWriter(s)
2875
for key, (tree_path, branch_location) in info_dict.iteritems():
2876
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2877
branch_location=branch_location)
2878
writer.write_stanza(stanza)
2879
self._transport.put_bytes('references', s.getvalue())
2880
self._reference_info = info_dict
2883
def _get_all_reference_info(self):
2884
"""Return all the reference info stored in a branch.
2886
:return: A dict of {file_id: (tree_path, branch_location)}
2888
if self._reference_info is not None:
2889
return self._reference_info
2890
rio_file = self._transport.get('references')
2892
stanzas = rio.read_stanzas(rio_file)
2893
info_dict = dict((s['file_id'], (s['tree_path'],
2894
s['branch_location'])) for s in stanzas)
2897
self._reference_info = info_dict
2900
def set_reference_info(self, file_id, tree_path, branch_location):
2901
"""Set the branch location to use for a tree reference.
2903
:param file_id: The file-id of the tree reference.
2904
:param tree_path: The path of the tree reference in the tree.
2905
:param branch_location: The location of the branch to retrieve tree
2908
info_dict = self._get_all_reference_info()
2909
info_dict[file_id] = (tree_path, branch_location)
2910
if None in (tree_path, branch_location):
2911
if tree_path is not None:
2912
raise ValueError('tree_path must be None when branch_location'
2914
if branch_location is not None:
2915
raise ValueError('branch_location must be None when tree_path'
2917
del info_dict[file_id]
2918
self._set_all_reference_info(info_dict)
2920
def get_reference_info(self, file_id):
2921
"""Get the tree_path and branch_location for a tree reference.
2923
:return: a tuple of (tree_path, branch_location)
2925
return self._get_all_reference_info().get(file_id, (None, None))
2927
def reference_parent(self, file_id, path, possible_transports=None):
2928
"""Return the parent branch for a tree-reference file_id.
2930
:param file_id: The file_id of the tree reference
2931
:param path: The path of the file_id in the tree
2932
:return: A branch associated with the file_id
2934
branch_location = self.get_reference_info(file_id)[1]
2935
if branch_location is None:
2936
return Branch.reference_parent(self, file_id, path,
2937
possible_transports)
2938
branch_location = urlutils.join(self.user_url, branch_location)
2939
return Branch.open(branch_location,
2940
possible_transports=possible_transports)
2385
2942
def set_push_location(self, location):
2386
2943
"""See Branch.set_push_location."""
2387
2944
self._set_config_location('push_location', location)
2389
2946
def set_bound_location(self, location):
2390
2947
"""See Branch.set_push_location."""
2948
self._master_branch_cache = None
2392
2950
config = self.get_config()
2393
2951
if location is None:
2549
3076
:ivar new_revno: Revision number after pull.
2550
3077
:ivar old_revid: Tip revision id before pull.
2551
3078
:ivar new_revid: Tip revision id after pull.
2552
:ivar source_branch: Source (local) branch object.
3079
:ivar source_branch: Source (local) branch object. (read locked)
2553
3080
:ivar master_branch: Master branch of the target, or the target if no
2555
3082
:ivar local_branch: target branch if there is a Master, else None
2556
:ivar target_branch: Target/destination branch object.
3083
:ivar target_branch: Target/destination branch object. (write locked)
2557
3084
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3085
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3088
@deprecated_method(deprecated_in((2, 3, 0)))
2560
3089
def __int__(self):
2561
# DEPRECATED: pull used to return the change in revno
3090
"""Return the relative change in revno.
3092
:deprecated: Use `new_revno` and `old_revno` instead.
2562
3094
return self.new_revno - self.old_revno
2564
3096
def report(self, to_file):
3097
tag_conflicts = getattr(self, "tag_conflicts", None)
3098
tag_updates = getattr(self, "tag_updates", None)
2565
3099
if not is_quiet():
2566
if self.old_revid == self.new_revid:
2567
to_file.write('No revisions to pull.\n')
3100
if self.old_revid != self.new_revid:
2569
3101
to_file.write('Now on revision %d.\n' % self.new_revno)
3103
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3104
if self.old_revid == self.new_revid and not tag_updates:
3105
if not tag_conflicts:
3106
to_file.write('No revisions or tags to pull.\n')
3108
to_file.write('No revisions to pull.\n')
2570
3109
self._show_tag_conficts(to_file)
2573
class PushResult(_Result):
3112
class BranchPushResult(_Result):
2574
3113
"""Result of a Branch.push operation.
2576
:ivar old_revno: Revision number before push.
2577
:ivar new_revno: Revision number after push.
2578
:ivar old_revid: Tip revision id before push.
2579
:ivar new_revid: Tip revision id after push.
2580
:ivar source_branch: Source branch object.
2581
:ivar master_branch: Master branch of the target, or None.
2582
:ivar target_branch: Target/destination branch object.
3115
:ivar old_revno: Revision number (eg 10) of the target before push.
3116
:ivar new_revno: Revision number (eg 12) of the target after push.
3117
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
3119
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
3121
:ivar source_branch: Source branch object that the push was from. This is
3122
read locked, and generally is a local (and thus low latency) branch.
3123
:ivar master_branch: If target is a bound branch, the master branch of
3124
target, or target itself. Always write locked.
3125
:ivar target_branch: The direct Branch where data is being sent (write
3127
:ivar local_branch: If the target is a bound branch this will be the
3128
target, otherwise it will be None.
3131
@deprecated_method(deprecated_in((2, 3, 0)))
2585
3132
def __int__(self):
2586
# DEPRECATED: push used to return the change in revno
3133
"""Return the relative change in revno.
3135
:deprecated: Use `new_revno` and `old_revno` instead.
2587
3137
return self.new_revno - self.old_revno
2589
3139
def report(self, to_file):
2590
"""Write a human-readable description of the result."""
2591
if self.old_revid == self.new_revid:
2592
to_file.write('No new revisions to push.\n')
2594
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
3140
# TODO: This function gets passed a to_file, but then
3141
# ignores it and calls note() instead. This is also
3142
# inconsistent with PullResult(), which writes to stdout.
3143
# -- JRV20110901, bug #838853
3144
tag_conflicts = getattr(self, "tag_conflicts", None)
3145
tag_updates = getattr(self, "tag_updates", None)
3147
if self.old_revid != self.new_revid:
3148
note(gettext('Pushed up to revision %d.') % self.new_revno)
3150
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3151
if self.old_revid == self.new_revid and not tag_updates:
3152
if not tag_conflicts:
3153
note(gettext('No new revisions or tags to push.'))
3155
note(gettext('No new revisions to push.'))
2595
3156
self._show_tag_conficts(to_file)
2656
3219
branch._transport.put_bytes('format', format.get_format_string())
2660
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2661
"""Run ``callable(*args, **kwargs)``, write-locking target for the
2664
_run_with_write_locked_target will attempt to release the lock it acquires.
2666
If an exception is raised by callable, then that exception *will* be
2667
propagated, even if the unlock attempt raises its own error. Thus
2668
_run_with_write_locked_target should be preferred to simply doing::
2672
return callable(*args, **kwargs)
3222
class Converter7to8(object):
3223
"""Perform an in-place upgrade of format 7 to format 8"""
3225
def convert(self, branch):
3226
format = BzrBranchFormat8()
3227
branch._transport.put_bytes('references', '')
3228
# update target format
3229
branch._transport.put_bytes('format', format.get_format_string())
3232
class InterBranch(InterObject):
3233
"""This class represents operations taking place between two branches.
3235
Its instances have methods like pull() and push() and contain
3236
references to the source and target repositories these operations
3237
can be carried out on.
2677
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
2678
# should share code?
2681
result = callable(*args, **kwargs)
2683
exc_info = sys.exc_info()
2687
raise exc_info[0], exc_info[1], exc_info[2]
3241
"""The available optimised InterBranch types."""
3244
def _get_branch_formats_to_test(klass):
3245
"""Return an iterable of format tuples for testing.
3247
:return: An iterable of (from_format, to_format) to use when testing
3248
this InterBranch class. Each InterBranch class should define this
3251
raise NotImplementedError(klass._get_branch_formats_to_test)
3254
def pull(self, overwrite=False, stop_revision=None,
3255
possible_transports=None, local=False):
3256
"""Mirror source into target branch.
3258
The target branch is considered to be 'local', having low latency.
3260
:returns: PullResult instance
3262
raise NotImplementedError(self.pull)
3265
def push(self, overwrite=False, stop_revision=None, lossy=False,
3266
_override_hook_source_branch=None):
3267
"""Mirror the source branch into the target branch.
3269
The source branch is considered to be 'local', having low latency.
3271
raise NotImplementedError(self.push)
3274
def copy_content_into(self, revision_id=None):
3275
"""Copy the content of source into target
3277
revision_id: if not None, the revision history in the new branch will
3278
be truncated to end with revision_id.
3280
raise NotImplementedError(self.copy_content_into)
3283
def fetch(self, stop_revision=None, limit=None):
3286
:param stop_revision: Last revision to fetch
3287
:param limit: Optional rough limit of revisions to fetch
3289
raise NotImplementedError(self.fetch)
3292
class GenericInterBranch(InterBranch):
3293
"""InterBranch implementation that uses public Branch functions."""
3296
def is_compatible(klass, source, target):
3297
# GenericBranch uses the public API, so always compatible
3301
def _get_branch_formats_to_test(klass):
3302
return [(format_registry.get_default(), format_registry.get_default())]
3305
def unwrap_format(klass, format):
3306
if isinstance(format, remote.RemoteBranchFormat):
3307
format._ensure_real()
3308
return format._custom_format
3312
def copy_content_into(self, revision_id=None):
3313
"""Copy the content of source into target
3315
revision_id: if not None, the revision history in the new branch will
3316
be truncated to end with revision_id.
3318
self.source.update_references(self.target)
3319
self.source._synchronize_history(self.target, revision_id)
3321
parent = self.source.get_parent()
3322
except errors.InaccessibleParent, e:
3323
mutter('parent was not accessible to copy: %s', e)
3326
self.target.set_parent(parent)
3327
if self.source._push_should_merge_tags():
3328
self.source.tags.merge_to(self.target.tags)
3331
def fetch(self, stop_revision=None, limit=None):
3332
if self.target.base == self.source.base:
3334
self.source.lock_read()
3336
fetch_spec_factory = fetch.FetchSpecFactory()
3337
fetch_spec_factory.source_branch = self.source
3338
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3339
fetch_spec_factory.source_repo = self.source.repository
3340
fetch_spec_factory.target_repo = self.target.repository
3341
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3342
fetch_spec_factory.limit = limit
3343
fetch_spec = fetch_spec_factory.make_fetch_spec()
3344
return self.target.repository.fetch(self.source.repository,
3345
fetch_spec=fetch_spec)
3347
self.source.unlock()
3350
def _update_revisions(self, stop_revision=None, overwrite=False,
3352
other_revno, other_last_revision = self.source.last_revision_info()
3353
stop_revno = None # unknown
3354
if stop_revision is None:
3355
stop_revision = other_last_revision
3356
if _mod_revision.is_null(stop_revision):
3357
# if there are no commits, we're done.
3359
stop_revno = other_revno
3361
# what's the current last revision, before we fetch [and change it
3363
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3364
# we fetch here so that we don't process data twice in the common
3365
# case of having something to pull, and so that the check for
3366
# already merged can operate on the just fetched graph, which will
3367
# be cached in memory.
3368
self.fetch(stop_revision=stop_revision)
3369
# Check to see if one is an ancestor of the other
3372
graph = self.target.repository.get_graph()
3373
if self.target._check_if_descendant_or_diverged(
3374
stop_revision, last_rev, graph, self.source):
3375
# stop_revision is a descendant of last_rev, but we aren't
3376
# overwriting, so we're done.
3378
if stop_revno is None:
3380
graph = self.target.repository.get_graph()
3381
this_revno, this_last_revision = \
3382
self.target.last_revision_info()
3383
stop_revno = graph.find_distance_to_null(stop_revision,
3384
[(other_last_revision, other_revno),
3385
(this_last_revision, this_revno)])
3386
self.target.set_last_revision_info(stop_revno, stop_revision)
3389
def pull(self, overwrite=False, stop_revision=None,
3390
possible_transports=None, run_hooks=True,
3391
_override_hook_target=None, local=False):
3392
"""Pull from source into self, updating my master if any.
3394
:param run_hooks: Private parameter - if false, this branch
3395
is being called because it's the master of the primary branch,
3396
so it should not run its hooks.
3398
bound_location = self.target.get_bound_location()
3399
if local and not bound_location:
3400
raise errors.LocalRequiresBoundBranch()
3401
master_branch = None
3402
source_is_master = False
3404
# bound_location comes from a config file, some care has to be
3405
# taken to relate it to source.user_url
3406
normalized = urlutils.normalize_url(bound_location)
3408
relpath = self.source.user_transport.relpath(normalized)
3409
source_is_master = (relpath == '')
3410
except (errors.PathNotChild, errors.InvalidURL):
3411
source_is_master = False
3412
if not local and bound_location and not source_is_master:
3413
# not pulling from master, so we need to update master.
3414
master_branch = self.target.get_master_branch(possible_transports)
3415
master_branch.lock_write()
3418
# pull from source into master.
3419
master_branch.pull(self.source, overwrite, stop_revision,
3421
return self._pull(overwrite,
3422
stop_revision, _hook_master=master_branch,
3423
run_hooks=run_hooks,
3424
_override_hook_target=_override_hook_target,
3425
merge_tags_to_master=not source_is_master)
3428
master_branch.unlock()
3430
def push(self, overwrite=False, stop_revision=None, lossy=False,
3431
_override_hook_source_branch=None):
3432
"""See InterBranch.push.
3434
This is the basic concrete implementation of push()
3436
:param _override_hook_source_branch: If specified, run the hooks
3437
passing this Branch as the source, rather than self. This is for
3438
use of RemoteBranch, where push is delegated to the underlying
3442
raise errors.LossyPushToSameVCS(self.source, self.target)
3443
# TODO: Public option to disable running hooks - should be trivial but
3446
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3447
op.add_cleanup(self.source.lock_read().unlock)
3448
op.add_cleanup(self.target.lock_write().unlock)
3449
return op.run(overwrite, stop_revision,
3450
_override_hook_source_branch=_override_hook_source_branch)
3452
def _basic_push(self, overwrite, stop_revision):
3453
"""Basic implementation of push without bound branches or hooks.
3455
Must be called with source read locked and target write locked.
3457
result = BranchPushResult()
3458
result.source_branch = self.source
3459
result.target_branch = self.target
3460
result.old_revno, result.old_revid = self.target.last_revision_info()
3461
self.source.update_references(self.target)
3462
if result.old_revid != stop_revision:
3463
# We assume that during 'push' this repository is closer than
3465
graph = self.source.repository.get_graph(self.target.repository)
3466
self._update_revisions(stop_revision, overwrite=overwrite,
3468
if self.source._push_should_merge_tags():
3469
result.tag_updates, result.tag_conflicts = (
3470
self.source.tags.merge_to(self.target.tags, overwrite))
3471
result.new_revno, result.new_revid = self.target.last_revision_info()
3474
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3475
_override_hook_source_branch=None):
3476
"""Push from source into target, and into target's master if any.
3479
if _override_hook_source_branch:
3480
result.source_branch = _override_hook_source_branch
3481
for hook in Branch.hooks['post_push']:
3484
bound_location = self.target.get_bound_location()
3485
if bound_location and self.target.base != bound_location:
3486
# there is a master branch.
3488
# XXX: Why the second check? Is it even supported for a branch to
3489
# be bound to itself? -- mbp 20070507
3490
master_branch = self.target.get_master_branch()
3491
master_branch.lock_write()
3492
operation.add_cleanup(master_branch.unlock)
3493
# push into the master from the source branch.
3494
master_inter = InterBranch.get(self.source, master_branch)
3495
master_inter._basic_push(overwrite, stop_revision)
3496
# and push into the target branch from the source. Note that
3497
# we push from the source branch again, because it's considered
3498
# the highest bandwidth repository.
3499
result = self._basic_push(overwrite, stop_revision)
3500
result.master_branch = master_branch
3501
result.local_branch = self.target
3503
master_branch = None
3505
result = self._basic_push(overwrite, stop_revision)
3506
# TODO: Why set master_branch and local_branch if there's no
3507
# binding? Maybe cleaner to just leave them unset? -- mbp
3509
result.master_branch = self.target
3510
result.local_branch = None
3514
def _pull(self, overwrite=False, stop_revision=None,
3515
possible_transports=None, _hook_master=None, run_hooks=True,
3516
_override_hook_target=None, local=False,
3517
merge_tags_to_master=True):
3520
This function is the core worker, used by GenericInterBranch.pull to
3521
avoid duplication when pulling source->master and source->local.
3523
:param _hook_master: Private parameter - set the branch to
3524
be supplied as the master to pull hooks.
3525
:param run_hooks: Private parameter - if false, this branch
3526
is being called because it's the master of the primary branch,
3527
so it should not run its hooks.
3528
is being called because it's the master of the primary branch,
3529
so it should not run its hooks.
3530
:param _override_hook_target: Private parameter - set the branch to be
3531
supplied as the target_branch to pull hooks.
3532
:param local: Only update the local branch, and not the bound branch.
3534
# This type of branch can't be bound.
3536
raise errors.LocalRequiresBoundBranch()
3537
result = PullResult()
3538
result.source_branch = self.source
3539
if _override_hook_target is None:
3540
result.target_branch = self.target
3542
result.target_branch = _override_hook_target
3543
self.source.lock_read()
3545
# We assume that during 'pull' the target repository is closer than
3547
self.source.update_references(self.target)
3548
graph = self.target.repository.get_graph(self.source.repository)
3549
# TODO: Branch formats should have a flag that indicates
3550
# that revno's are expensive, and pull() should honor that flag.
3552
result.old_revno, result.old_revid = \
3553
self.target.last_revision_info()
3554
self._update_revisions(stop_revision, overwrite=overwrite,
3556
# TODO: The old revid should be specified when merging tags,
3557
# so a tags implementation that versions tags can only
3558
# pull in the most recent changes. -- JRV20090506
3559
result.tag_updates, result.tag_conflicts = (
3560
self.source.tags.merge_to(self.target.tags, overwrite,
3561
ignore_master=not merge_tags_to_master))
3562
result.new_revno, result.new_revid = self.target.last_revision_info()
3564
result.master_branch = _hook_master
3565
result.local_branch = result.target_branch
3567
result.master_branch = result.target_branch
3568
result.local_branch = None
3570
for hook in Branch.hooks['post_pull']:
3573
self.source.unlock()
3577
InterBranch.register_optimiser(GenericInterBranch)