359
486
"""Iterate over an inclusive range of sorted revisions."""
360
487
rev_iter = iter(merge_sorted_revisions)
361
488
if start_revision_id is not None:
362
for rev_id, depth, revno, end_of_merge in rev_iter:
489
for node in rev_iter:
490
rev_id = node.key[-1]
363
491
if rev_id != start_revision_id:
366
494
# The decision to include the start or not
367
495
# depends on the stop_rule if a stop is provided
369
iter([(rev_id, depth, revno, end_of_merge)]),
496
# so pop this node back into the iterator
497
rev_iter = chain(iter([node]), rev_iter)
372
499
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
501
for node in rev_iter:
502
rev_id = node.key[-1]
503
yield (rev_id, node.merge_depth, node.revno,
375
505
elif stop_rule == 'exclude':
376
for rev_id, depth, revno, end_of_merge in rev_iter:
506
for node in rev_iter:
507
rev_id = node.key[-1]
377
508
if rev_id == stop_revision_id:
379
yield rev_id, depth, revno, end_of_merge
510
yield (rev_id, node.merge_depth, node.revno,
380
512
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
513
for node in rev_iter:
514
rev_id = node.key[-1]
515
yield (rev_id, node.merge_depth, node.revno,
383
517
if rev_id == stop_revision_id:
519
elif stop_rule == 'with-merges-without-common-ancestry':
520
# We want to exclude all revisions that are already part of the
521
# stop_revision_id ancestry.
522
graph = self.repository.get_graph()
523
ancestors = graph.find_unique_ancestors(start_revision_id,
525
for node in rev_iter:
526
rev_id = node.key[-1]
527
if rev_id not in ancestors:
529
yield (rev_id, node.merge_depth, node.revno,
385
531
elif stop_rule == 'with-merges':
386
532
stop_rev = self.repository.get_revision(stop_revision_id)
387
533
if stop_rev.parent_ids:
388
534
left_parent = stop_rev.parent_ids[0]
390
536
left_parent = _mod_revision.NULL_REVISION
391
for rev_id, depth, revno, end_of_merge in rev_iter:
537
# left_parent is the actual revision we want to stop logging at,
538
# since we want to show the merged revisions after the stop_rev too
539
reached_stop_revision_id = False
540
revision_id_whitelist = []
541
for node in rev_iter:
542
rev_id = node.key[-1]
392
543
if rev_id == left_parent:
544
# reached the left parent after the stop_revision
394
yield rev_id, depth, revno, end_of_merge
546
if (not reached_stop_revision_id or
547
rev_id in revision_id_whitelist):
548
yield (rev_id, node.merge_depth, node.revno,
550
if reached_stop_revision_id or rev_id == stop_revision_id:
551
# only do the merged revs of rev_id from now on
552
rev = self.repository.get_revision(rev_id)
554
reached_stop_revision_id = True
555
revision_id_whitelist.extend(rev.parent_ids)
396
557
raise ValueError('invalid stop_rule %r' % stop_rule)
559
def _filter_start_non_ancestors(self, rev_iter):
560
# If we started from a dotted revno, we want to consider it as a tip
561
# and don't want to yield revisions that are not part of its
562
# ancestry. Given the order guaranteed by the merge sort, we will see
563
# uninteresting descendants of the first parent of our tip before the
565
first = rev_iter.next()
566
(rev_id, merge_depth, revno, end_of_merge) = first
569
# We start at a mainline revision so by definition, all others
570
# revisions in rev_iter are ancestors
571
for node in rev_iter:
576
pmap = self.repository.get_parent_map([rev_id])
577
parents = pmap.get(rev_id, [])
579
whitelist.update(parents)
581
# If there is no parents, there is nothing of interest left
583
# FIXME: It's hard to test this scenario here as this code is never
584
# called in that case. -- vila 20100322
587
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
589
if rev_id in whitelist:
590
pmap = self.repository.get_parent_map([rev_id])
591
parents = pmap.get(rev_id, [])
592
whitelist.remove(rev_id)
593
whitelist.update(parents)
595
# We've reached the mainline, there is nothing left to
599
# A revision that is not part of the ancestry of our
602
yield (rev_id, merge_depth, revno, end_of_merge)
398
604
def leave_lock_in_place(self):
399
605
"""Tell this branch object not to release the physical lock when this
400
606
object is unlocked.
402
608
If lock_write doesn't return a token, then this method is not supported.
404
610
self.control_files.leave_in_place()
528
764
:raises UnstackableRepositoryFormat: If the repository does not support
531
raise NotImplementedError(self.set_stacked_on_url)
767
if not self._format.supports_stacking():
768
raise errors.UnstackableBranchFormat(self._format, self.user_url)
769
# XXX: Changing from one fallback repository to another does not check
770
# that all the data you need is present in the new fallback.
771
# Possibly it should.
772
self._check_stackable_repo()
775
old_url = self.get_stacked_on_url()
776
except (errors.NotStacked, errors.UnstackableBranchFormat,
777
errors.UnstackableRepositoryFormat):
781
self._activate_fallback_location(url)
782
# write this out after the repository is stacked to avoid setting a
783
# stacked config that doesn't work.
784
self._set_config_location('stacked_on_location', url)
787
"""Change a branch to be unstacked, copying data as needed.
789
Don't call this directly, use set_stacked_on_url(None).
791
pb = ui.ui_factory.nested_progress_bar()
793
pb.update("Unstacking")
794
# The basic approach here is to fetch the tip of the branch,
795
# including all available ghosts, from the existing stacked
796
# repository into a new repository object without the fallbacks.
798
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
799
# correct for CHKMap repostiories
800
old_repository = self.repository
801
if len(old_repository._fallback_repositories) != 1:
802
raise AssertionError("can't cope with fallback repositories "
803
"of %r" % (self.repository,))
804
# unlock it, including unlocking the fallback
805
old_repository.unlock()
806
old_repository.lock_read()
808
# Repositories don't offer an interface to remove fallback
809
# repositories today; take the conceptually simpler option and just
810
# reopen it. We reopen it starting from the URL so that we
811
# get a separate connection for RemoteRepositories and can
812
# stream from one of them to the other. This does mean doing
813
# separate SSH connection setup, but unstacking is not a
814
# common operation so it's tolerable.
815
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
816
new_repository = new_bzrdir.find_repository()
817
self.repository = new_repository
818
if self.repository._fallback_repositories:
819
raise AssertionError("didn't expect %r to have "
820
"fallback_repositories"
821
% (self.repository,))
822
# this is not paired with an unlock because it's just restoring
823
# the previous state; the lock's released when set_stacked_on_url
825
self.repository.lock_write()
826
# XXX: If you unstack a branch while it has a working tree
827
# with a pending merge, the pending-merged revisions will no
828
# longer be present. You can (probably) revert and remerge.
830
# XXX: This only fetches up to the tip of the repository; it
831
# doesn't bring across any tags. That's fairly consistent
832
# with how branch works, but perhaps not ideal.
833
self.repository.fetch(old_repository,
834
revision_id=self.last_revision(),
837
old_repository.unlock()
841
def _set_tags_bytes(self, bytes):
842
"""Mirror method for _get_tags_bytes.
844
:seealso: Branch._get_tags_bytes.
846
return _run_with_write_locked_target(self, self._transport.put_bytes,
533
849
def _cache_revision_history(self, rev_history):
534
850
"""Set the cached revision history to rev_history.
668
981
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)
984
return InterBranch.get(other, self).update_revisions(stop_revision,
987
def import_last_revision_info(self, source_repo, revno, revid):
988
"""Set the last revision info, importing from another repo if necessary.
990
This is used by the bound branch code to upload a revision to
991
the master branch first before updating the tip of the local branch.
993
:param source_repo: Source repository to optionally fetch from
994
:param revno: Revision number of the new tip
995
:param revid: Revision id of the new tip
997
if not self.repository.has_same_location(source_repo):
998
self.repository.fetch(source_repo, revision_id=revid)
999
self.set_last_revision_info(revno, revid)
710
1001
def revision_id_to_revno(self, revision_id):
711
1002
"""Given a revision id, return its revno"""
717
1008
except ValueError:
718
1009
raise errors.NoSuchRevision(self, revision_id)
720
1012
def get_rev_id(self, revno, history=None):
721
1013
"""Find the revision id of the specified revno."""
723
1015
return _mod_revision.NULL_REVISION
725
history = self.revision_history()
726
if revno <= 0 or revno > len(history):
1016
last_revno, last_revid = self.last_revision_info()
1017
if revno == last_revno:
1019
if revno <= 0 or revno > last_revno:
727
1020
raise errors.NoSuchRevision(self, revno)
728
return history[revno - 1]
1021
distance_from_last = last_revno - revno
1022
if len(self._partial_revision_history_cache) <= distance_from_last:
1023
self._extend_partial_history(distance_from_last)
1024
return self._partial_revision_history_cache[distance_from_last]
730
1027
def pull(self, source, overwrite=False, stop_revision=None,
731
possible_transports=None, _override_hook_target=None):
1028
possible_transports=None, *args, **kwargs):
732
1029
"""Mirror source into this branch.
734
1031
This branch is considered to be 'local', having low latency.
736
1033
:returns: PullResult instance
738
raise NotImplementedError(self.pull)
1035
return InterBranch.get(source, self).pull(overwrite=overwrite,
1036
stop_revision=stop_revision,
1037
possible_transports=possible_transports, *args, **kwargs)
740
def push(self, target, overwrite=False, stop_revision=None):
1039
def push(self, target, overwrite=False, stop_revision=None, *args,
741
1041
"""Mirror this branch into target.
743
1043
This branch is considered to be 'local', having low latency.
745
raise NotImplementedError(self.push)
1045
return InterBranch.get(self, target).push(overwrite, stop_revision,
1048
def lossy_push(self, target, stop_revision=None):
1049
"""Push deltas into another branch.
1051
:note: This does not, like push, retain the revision ids from
1052
the source branch and will, rather than adding bzr-specific
1053
metadata, push only those semantics of the revision that can be
1054
natively represented by this branch' VCS.
1056
:param target: Target branch
1057
:param stop_revision: Revision to push, defaults to last revision.
1058
:return: BranchPushResult with an extra member revidmap:
1059
A dictionary mapping revision ids from the target branch
1060
to new revision ids in the target branch, for each
1061
revision that was pushed.
1063
inter = InterBranch.get(self, target)
1064
lossy_push = getattr(inter, "lossy_push", None)
1065
if lossy_push is None:
1066
raise errors.LossyPushToSameVCS(self, target)
1067
return lossy_push(stop_revision)
747
1069
def basis_tree(self):
748
1070
"""Return `Tree` object for last revision."""
886
1262
source_revno, source_revision_id = self.last_revision_info()
887
1263
if revision_id is None:
888
1264
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(
1266
graph = self.repository.get_graph()
1268
revno = graph.find_distance_to_null(revision_id,
1269
[(source_revision_id, source_revno)])
1270
except errors.GhostRevisionsHaveNoRevno:
1271
# Default to 1, if we can't find anything else
901
1273
destination.set_last_revision_info(revno, revision_id)
904
1275
def copy_content_into(self, destination, revision_id=None):
905
1276
"""Copy the content of self into destination.
907
1278
revision_id: if not None, the revision history in the new branch will
908
1279
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)
1281
return InterBranch.get(self, destination).copy_content_into(
1282
revision_id=revision_id)
1284
def update_references(self, target):
1285
if not getattr(self._format, 'supports_reference_locations', False):
1287
reference_dict = self._get_all_reference_info()
1288
if len(reference_dict) == 0:
1290
old_base = self.base
1291
new_base = target.base
1292
target_reference_dict = target._get_all_reference_info()
1293
for file_id, (tree_path, branch_location) in (
1294
reference_dict.items()):
1295
branch_location = urlutils.rebase_url(branch_location,
1297
target_reference_dict.setdefault(
1298
file_id, (tree_path, branch_location))
1299
target._set_all_reference_info(target_reference_dict)
920
1301
@needs_read_lock
1302
def check(self, refs):
922
1303
"""Check consistency of the branch.
924
1305
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
1306
do actually match up in the revision graph, and that they're all
926
1307
present in the repository.
928
1309
Callers will typically also want to check the repository.
1311
:param refs: Calculated refs for this branch as specified by
1312
branch._get_check_refs()
930
1313
:return: A BranchCheckResult.
932
mainline_parent_id = None
1315
result = BranchCheckResult(self)
933
1316
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)
1317
actual_revno = refs[('lefthand-distance', last_revision_id)]
1318
if actual_revno != last_revno:
1319
result.errors.append(errors.BzrCheckError(
1320
'revno does not match len(mainline) %s != %s' % (
1321
last_revno, actual_revno)))
1322
# TODO: We should probably also check that self.revision_history
1323
# matches the repository for older branch formats.
1324
# If looking for the code that cross-checks repository parents against
1325
# the iter_reverse_revision_history output, that is now a repository
959
1329
def _get_checkout_format(self):
960
1330
"""Return the most suitable metadir for a checkout of this branch.
1185
1612
filename, content,
1186
1613
mode=a_bzrdir._get_file_mode())
1188
control_files.unlock()
1189
return self.open(a_bzrdir, _found=True)
1616
control_files.unlock()
1617
branch = self.open(a_bzrdir, name, _found=True)
1618
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1191
def initialize(self, a_bzrdir):
1192
"""Create a branch of this format in a_bzrdir."""
1621
def initialize(self, a_bzrdir, name=None):
1622
"""Create a branch of this format in a_bzrdir.
1624
:param name: Name of the colocated branch to create.
1193
1626
raise NotImplementedError(self.initialize)
1195
1628
def is_supported(self):
1196
1629
"""Is this format supported?
1198
1631
Supported formats can be initialized and opened.
1199
Unsupported formats may not support initialization or committing or
1632
Unsupported formats may not support initialization or committing or
1200
1633
some other features depending on the reason for not being supported.
1204
def open(self, a_bzrdir, _found=False):
1637
def make_tags(self, branch):
1638
"""Create a tags object for branch.
1640
This method is on BranchFormat, because BranchFormats are reflected
1641
over the wire via network_name(), whereas full Branch instances require
1642
multiple VFS method calls to operate at all.
1644
The default implementation returns a disabled-tags instance.
1646
Note that it is normal for branch to be a RemoteBranch when using tags
1649
return DisabledTags(branch)
1651
def network_name(self):
1652
"""A simple byte string uniquely identifying this format for RPC calls.
1654
MetaDir branch formats use their disk format string to identify the
1655
repository over the wire. All in one formats such as bzr < 0.8, and
1656
foreign formats like svn/git and hg should use some marker which is
1657
unique and immutable.
1659
raise NotImplementedError(self.network_name)
1661
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1205
1662
"""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.
1664
:param a_bzrdir: A BzrDir that contains a branch.
1665
:param name: Name of colocated branch to open
1666
:param _found: a private parameter, do not use it. It is used to
1667
indicate if format probing has already be done.
1668
:param ignore_fallbacks: when set, no fallback branches will be opened
1669
(if there are any). Default is to open fallbacks.
1210
1671
raise NotImplementedError(self.open)
1213
1674
def register_format(klass, format):
1675
"""Register a metadir format."""
1214
1676
klass._formats[format.get_format_string()] = format
1677
# Metadir formats have a network name of their format string, and get
1678
# registered as class factories.
1679
network_format_registry.register(format.get_format_string(), format.__class__)
1217
1682
def set_default_format(klass, format):
1218
1683
klass._default_format = format
1685
def supports_set_append_revisions_only(self):
1686
"""True if this format supports set_append_revisions_only."""
1220
1689
def supports_stacking(self):
1221
1690
"""True if this format records a stacked-on branch."""
1249
1718
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'] = []
1719
self.create_hook(HookPoint('set_rh',
1720
"Invoked whenever the revision history has been set via "
1721
"set_revision_history. The api signature is (branch, "
1722
"revision_history), and the branch will be write-locked. "
1723
"The set_rh hook can be expensive for bzr to trigger, a better "
1724
"hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1725
self.create_hook(HookPoint('open',
1726
"Called with the Branch object that has been opened after a "
1727
"branch is opened.", (1, 8), None))
1728
self.create_hook(HookPoint('post_push',
1729
"Called after a push operation completes. post_push is called "
1730
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1731
"bzr client.", (0, 15), None))
1732
self.create_hook(HookPoint('post_pull',
1733
"Called after a pull operation completes. post_pull is called "
1734
"with a bzrlib.branch.PullResult object and only runs in the "
1735
"bzr client.", (0, 15), None))
1736
self.create_hook(HookPoint('pre_commit',
1737
"Called after a commit is calculated but before it is is "
1738
"completed. pre_commit is called with (local, master, old_revno, "
1739
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1740
"). old_revid is NULL_REVISION for the first commit to a branch, "
1741
"tree_delta is a TreeDelta object describing changes from the "
1742
"basis revision. hooks MUST NOT modify this delta. "
1743
" future_tree is an in-memory tree obtained from "
1744
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1745
"tree.", (0,91), None))
1746
self.create_hook(HookPoint('post_commit',
1747
"Called in the bzr client after a commit has completed. "
1748
"post_commit is called with (local, master, old_revno, old_revid, "
1749
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1750
"commit to a branch.", (0, 15), None))
1751
self.create_hook(HookPoint('post_uncommit',
1752
"Called in the bzr client after an uncommit completes. "
1753
"post_uncommit is called with (local, master, old_revno, "
1754
"old_revid, new_revno, new_revid) where local is the local branch "
1755
"or None, master is the target branch, and an empty branch "
1756
"receives new_revno of 0, new_revid of None.", (0, 15), None))
1757
self.create_hook(HookPoint('pre_change_branch_tip',
1758
"Called in bzr client and server before a change to the tip of a "
1759
"branch is made. pre_change_branch_tip is called with a "
1760
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1761
"commit, uncommit will all trigger this hook.", (1, 6), None))
1762
self.create_hook(HookPoint('post_change_branch_tip',
1763
"Called in bzr client and server after a change to the tip of a "
1764
"branch is made. post_change_branch_tip is called with a "
1765
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1766
"commit, uncommit will all trigger this hook.", (1, 4), None))
1767
self.create_hook(HookPoint('transform_fallback_location',
1768
"Called when a stacked branch is activating its fallback "
1769
"locations. transform_fallback_location is called with (branch, "
1770
"url), and should return a new url. Returning the same url "
1771
"allows it to be used as-is, returning a different one can be "
1772
"used to cause the branch to stack on a closer copy of that "
1773
"fallback_location. Note that the branch cannot have history "
1774
"accessing methods called on it during this hook because the "
1775
"fallback locations have not been activated. When there are "
1776
"multiple hooks installed for transform_fallback_location, "
1777
"all are called with the url returned from the previous hook."
1778
"The order is however undefined.", (1, 9), None))
1779
self.create_hook(HookPoint('automatic_tag_name',
1780
"Called to determine an automatic tag name for a revision."
1781
"automatic_tag_name is called with (branch, revision_id) and "
1782
"should return a tag name or None if no tag name could be "
1783
"determined. The first non-None tag name returned will be used.",
1785
self.create_hook(HookPoint('post_branch_init',
1786
"Called after new branch initialization completes. "
1787
"post_branch_init is called with a "
1788
"bzrlib.branch.BranchInitHookParams. "
1789
"Note that init, branch and checkout (both heavyweight and "
1790
"lightweight) will all trigger this hook.", (2, 2), None))
1791
self.create_hook(HookPoint('post_switch',
1792
"Called after a checkout switches branch. "
1793
"post_switch is called with a "
1794
"bzrlib.branch.SwitchHookParams.", (2, 2), None))
1321
1798
# install the default hooks into the Branch class.
1354
1831
def __eq__(self, other):
1355
1832
return self.__dict__ == other.__dict__
1357
1834
def __repr__(self):
1358
1835
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1359
self.__class__.__name__, self.branch,
1836
self.__class__.__name__, self.branch,
1360
1837
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1840
class BranchInitHookParams(object):
1841
"""Object holding parameters passed to *_branch_init hooks.
1843
There are 4 fields that hooks may wish to access:
1845
:ivar format: the branch format
1846
:ivar bzrdir: the BzrDir where the branch will be/has been initialized
1847
:ivar name: name of colocated branch, if any (or None)
1848
:ivar branch: the branch created
1850
Note that for lightweight checkouts, the bzrdir and format fields refer to
1851
the checkout, hence they are different from the corresponding fields in
1852
branch, which refer to the original branch.
1855
def __init__(self, format, a_bzrdir, name, branch):
1856
"""Create a group of BranchInitHook parameters.
1858
:param format: the branch format
1859
:param a_bzrdir: the BzrDir where the branch will be/has been
1861
:param name: name of colocated branch, if any (or None)
1862
:param branch: the branch created
1864
Note that for lightweight checkouts, the bzrdir and format fields refer
1865
to the checkout, hence they are different from the corresponding fields
1866
in branch, which refer to the original branch.
1868
self.format = format
1869
self.bzrdir = a_bzrdir
1871
self.branch = branch
1873
def __eq__(self, other):
1874
return self.__dict__ == other.__dict__
1878
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1880
return "<%s of format:%s bzrdir:%s>" % (
1881
self.__class__.__name__, self.branch,
1882
self.format, self.bzrdir)
1885
class SwitchHookParams(object):
1886
"""Object holding parameters passed to *_switch hooks.
1888
There are 4 fields that hooks may wish to access:
1890
:ivar control_dir: BzrDir of the checkout to change
1891
:ivar to_branch: branch that the checkout is to reference
1892
:ivar force: skip the check for local commits in a heavy checkout
1893
:ivar revision_id: revision ID to switch to (or None)
1896
def __init__(self, control_dir, to_branch, force, revision_id):
1897
"""Create a group of SwitchHook parameters.
1899
:param control_dir: BzrDir of the checkout to change
1900
:param to_branch: branch that the checkout is to reference
1901
:param force: skip the check for local commits in a heavy checkout
1902
:param revision_id: revision ID to switch to (or None)
1904
self.control_dir = control_dir
1905
self.to_branch = to_branch
1907
self.revision_id = revision_id
1909
def __eq__(self, other):
1910
return self.__dict__ == other.__dict__
1913
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1914
self.control_dir, self.to_branch,
1363
1918
class BzrBranchFormat4(BranchFormat):
1364
1919
"""Bzr branch format 4.
1497
2058
"""See BranchFormat.get_format_description()."""
1498
2059
return "Branch format 6"
1500
def initialize(self, a_bzrdir):
1501
"""Create a branch of this format in a_bzrdir."""
1502
utf8_files = [('last-revision', '0 null:\n'),
1503
('branch.conf', ''),
1506
return self._initialize_helper(a_bzrdir, utf8_files)
1509
class BzrBranchFormat7(BranchFormatMetadir):
2061
def initialize(self, a_bzrdir, name=None):
2062
"""Create a branch of this format in a_bzrdir."""
2063
utf8_files = [('last-revision', '0 null:\n'),
2064
('branch.conf', ''),
2067
return self._initialize_helper(a_bzrdir, utf8_files, name)
2069
def make_tags(self, branch):
2070
"""See bzrlib.branch.BranchFormat.make_tags()."""
2071
return BasicTags(branch)
2073
def supports_set_append_revisions_only(self):
2077
class BzrBranchFormat8(BranchFormatMetadir):
2078
"""Metadir format supporting storing locations of subtree branches."""
2080
def _branch_class(self):
2083
def get_format_string(self):
2084
"""See BranchFormat.get_format_string()."""
2085
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2087
def get_format_description(self):
2088
"""See BranchFormat.get_format_description()."""
2089
return "Branch format 8"
2091
def initialize(self, a_bzrdir, name=None):
2092
"""Create a branch of this format in a_bzrdir."""
2093
utf8_files = [('last-revision', '0 null:\n'),
2094
('branch.conf', ''),
2098
return self._initialize_helper(a_bzrdir, utf8_files, name)
2101
super(BzrBranchFormat8, self).__init__()
2102
self._matchingbzrdir.repository_format = \
2103
RepositoryFormatKnitPack5RichRoot()
2105
def make_tags(self, branch):
2106
"""See bzrlib.branch.BranchFormat.make_tags()."""
2107
return BasicTags(branch)
2109
def supports_set_append_revisions_only(self):
2112
def supports_stacking(self):
2115
supports_reference_locations = True
2118
class BzrBranchFormat7(BzrBranchFormat8):
1510
2119
"""Branch format with last-revision, tags, and a stacked location pointer.
1512
2121
The stacked location pointer is passed down to the repository and requires
1562
2168
"""See BranchFormat.get_format_description()."""
1563
2169
return "Checkout reference format 1"
1565
def get_reference(self, a_bzrdir):
2171
def get_reference(self, a_bzrdir, name=None):
1566
2172
"""See BranchFormat.get_reference()."""
1567
transport = a_bzrdir.get_branch_transport(None)
1568
return transport.get('location').read()
2173
transport = a_bzrdir.get_branch_transport(None, name=name)
2174
return transport.get_bytes('location')
1570
def set_reference(self, a_bzrdir, to_branch):
2176
def set_reference(self, a_bzrdir, name, to_branch):
1571
2177
"""See BranchFormat.set_reference()."""
1572
transport = a_bzrdir.get_branch_transport(None)
2178
transport = a_bzrdir.get_branch_transport(None, name=name)
1573
2179
location = transport.put_bytes('location', to_branch.base)
1575
def initialize(self, a_bzrdir, target_branch=None):
2181
def initialize(self, a_bzrdir, name=None, target_branch=None):
1576
2182
"""Create a branch of this format in a_bzrdir."""
1577
2183
if target_branch is None:
1578
2184
# this format does not implement branch itself, thus the implicit
1579
2185
# creation contract must see it as uninitializable
1580
2186
raise errors.UninitializableFormat(self)
1581
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1582
branch_transport = a_bzrdir.get_branch_transport(self)
2187
mutter('creating branch reference in %s', a_bzrdir.user_url)
2188
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1583
2189
branch_transport.put_bytes('location',
1584
target_branch.bzrdir.root_transport.base)
2190
target_branch.bzrdir.user_url)
1585
2191
branch_transport.put_bytes('format', self.get_format_string())
1587
a_bzrdir, _found=True,
2193
a_bzrdir, name, _found=True,
1588
2194
possible_transports=[target_branch.bzrdir.root_transport])
2195
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1590
2198
def __init__(self):
1591
2199
super(BranchReferenceFormat, self).__init__()
1595
2203
def _make_reference_clone_function(format, a_branch):
1596
2204
"""Create a clone() routine for a branch dynamically."""
1597
def clone(to_bzrdir, revision_id=None):
2205
def clone(to_bzrdir, revision_id=None,
2206
repository_policy=None):
1598
2207
"""See Branch.clone()."""
1599
return format.initialize(to_bzrdir, a_branch)
2208
return format.initialize(to_bzrdir, target_branch=a_branch)
1600
2209
# cannot obey revision_id limits when cloning a reference ...
1601
2210
# FIXME RBC 20060210 either nuke revision_id for clone, or
1602
2211
# emit some sort of warning/error to the caller ?!
1605
def open(self, a_bzrdir, _found=False, location=None,
1606
possible_transports=None):
2214
def open(self, a_bzrdir, name=None, _found=False, location=None,
2215
possible_transports=None, ignore_fallbacks=False):
1607
2216
"""Return the branch that the branch reference in a_bzrdir points at.
1609
_found is a private parameter, do not use it. It is used to indicate
1610
if format probing has already be done.
2218
:param a_bzrdir: A BzrDir that contains a branch.
2219
:param name: Name of colocated branch to open, if any
2220
:param _found: a private parameter, do not use it. It is used to
2221
indicate if format probing has already be done.
2222
:param ignore_fallbacks: when set, no fallback branches will be opened
2223
(if there are any). Default is to open fallbacks.
2224
:param location: The location of the referenced branch. If
2225
unspecified, this will be determined from the branch reference in
2227
:param possible_transports: An optional reusable transports list.
1613
format = BranchFormat.find_format(a_bzrdir)
2230
format = BranchFormat.find_format(a_bzrdir, name=name)
1614
2231
if format.__class__ != self.__class__:
1615
2232
raise AssertionError("wrong format %r found for %r" %
1616
2233
(format, self))
1617
2234
if location is None:
1618
location = self.get_reference(a_bzrdir)
2235
location = self.get_reference(a_bzrdir, name)
1619
2236
real_bzrdir = bzrdir.BzrDir.open(
1620
2237
location, possible_transports=possible_transports)
1621
result = real_bzrdir.open_branch()
2238
result = real_bzrdir.open_branch(name=name,
2239
ignore_fallbacks=ignore_fallbacks)
1622
2240
# this changes the behaviour of result.clone to create a new reference
1623
2241
# rather than a copy of the content of the branch.
1624
2242
# I did not use a proxy object because that needs much more extensive
2252
network_format_registry = registry.FormatRegistry()
2253
"""Registry of formats indexed by their network name.
2255
The network name for a branch format is an identifier that can be used when
2256
referring to formats with smart server operations. See
2257
BranchFormat.network_name() for more detail.
1634
2261
# formats which have no format string are not discoverable
1635
2262
# and not independently creatable, so are not registered.
1636
2263
__format5 = BzrBranchFormat5()
1637
2264
__format6 = BzrBranchFormat6()
1638
2265
__format7 = BzrBranchFormat7()
2266
__format8 = BzrBranchFormat8()
1639
2267
BranchFormat.register_format(__format5)
1640
2268
BranchFormat.register_format(BranchReferenceFormat())
1641
2269
BranchFormat.register_format(__format6)
1642
2270
BranchFormat.register_format(__format7)
1643
BranchFormat.set_default_format(__format6)
2271
BranchFormat.register_format(__format8)
2272
BranchFormat.set_default_format(__format7)
1644
2273
_legacy_formats = [BzrBranchFormat4(),
1647
class BzrBranch(Branch):
2275
network_format_registry.register(
2276
_legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2279
class BranchWriteLockResult(LogicalLockResult):
2280
"""The result of write locking a branch.
2282
:ivar branch_token: The token obtained from the underlying branch lock, or
2284
:ivar unlock: A callable which will unlock the lock.
2287
def __init__(self, unlock, branch_token):
2288
LogicalLockResult.__init__(self, unlock)
2289
self.branch_token = branch_token
2292
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2296
class BzrBranch(Branch, _RelockDebugMixin):
1648
2297
"""A branch stored in the actual filesystem.
1650
2299
Note that it's "local" in the context of the filesystem; it doesn't
1651
2300
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1652
2301
it's writable, and can be accessed via the normal filesystem API.
1654
:ivar _transport: Transport for file operations on this branch's
2303
:ivar _transport: Transport for file operations on this branch's
1655
2304
control files, typically pointing to the .bzr/branch directory.
1656
2305
:ivar repository: Repository for this branch.
1657
:ivar base: The url of the base directory for this branch; the one
2306
:ivar base: The url of the base directory for this branch; the one
1658
2307
containing the .bzr directory.
2308
:ivar name: Optional colocated branch name as it exists in the control
1661
2312
def __init__(self, _format=None,
1662
_control_files=None, a_bzrdir=None, _repository=None):
2313
_control_files=None, a_bzrdir=None, name=None,
2314
_repository=None, ignore_fallbacks=False):
1663
2315
"""Create new branch object at a particular location."""
1664
2316
if a_bzrdir is None:
1665
2317
raise ValueError('a_bzrdir must be supplied')
1667
2319
self.bzrdir = a_bzrdir
1668
2320
self._base = self.bzrdir.transport.clone('..').base
1669
2322
# XXX: We should be able to just do
1670
2323
# self.base = self.bzrdir.root_transport.base
1671
2324
# but this does not quite work yet -- mbp 20080522
1689
2346
base = property(_get_base, doc="The URL for the root of this branch.")
2348
def _get_config(self):
2349
return TransportConfig(self._transport, 'branch.conf')
1691
2351
def is_locked(self):
1692
2352
return self.control_files.is_locked()
1694
2354
def lock_write(self, token=None):
1695
repo_token = self.repository.lock_write()
2355
"""Lock the branch for write operations.
2357
:param token: A token to permit reacquiring a previously held and
2359
:return: A BranchWriteLockResult.
2361
if not self.is_locked():
2362
self._note_lock('w')
2363
# All-in-one needs to always unlock/lock.
2364
repo_control = getattr(self.repository, 'control_files', None)
2365
if self.control_files == repo_control or not self.is_locked():
2366
self.repository._warn_if_deprecated(self)
2367
self.repository.lock_write()
1697
token = self.control_files.lock_write(token=token)
2372
return BranchWriteLockResult(self.unlock,
2373
self.control_files.lock_write(token=token))
1699
self.repository.unlock()
2376
self.repository.unlock()
1703
2379
def lock_read(self):
1704
self.repository.lock_read()
2380
"""Lock the branch for read operations.
2382
:return: A bzrlib.lock.LogicalLockResult.
2384
if not self.is_locked():
2385
self._note_lock('r')
2386
# All-in-one needs to always unlock/lock.
2387
repo_control = getattr(self.repository, 'control_files', None)
2388
if self.control_files == repo_control or not self.is_locked():
2389
self.repository._warn_if_deprecated(self)
2390
self.repository.lock_read()
1706
2395
self.control_files.lock_read()
2396
return LogicalLockResult(self.unlock)
1708
self.repository.unlock()
2399
self.repository.unlock()
2402
@only_raises(errors.LockNotHeld, errors.LockBroken)
1711
2403
def unlock(self):
1712
# TODO: test for failed two phase locks. This is known broken.
1714
2405
self.control_files.unlock()
1716
self.repository.unlock()
1717
if not self.control_files.is_locked():
1718
# we just released the lock
1719
self._clear_cached_state()
2407
# All-in-one needs to always unlock/lock.
2408
repo_control = getattr(self.repository, 'control_files', None)
2409
if (self.control_files == repo_control or
2410
not self.control_files.is_locked()):
2411
self.repository.unlock()
2412
if not self.control_files.is_locked():
2413
# we just released the lock
2414
self._clear_cached_state()
1721
2416
def peek_lock_mode(self):
1722
2417
if self.control_files._lock_count == 0:
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
2548
def _basic_push(self, target, overwrite, stop_revision):
2019
2549
"""Basic implementation of push without bound branches or hooks.
2021
Must be called with self read locked and target write locked.
2551
Must be called with source read locked and target write locked.
2023
result = PushResult()
2553
result = BranchPushResult()
2024
2554
result.source_branch = self
2025
2555
result.target_branch = target
2026
2556
result.old_revno, result.old_revid = target.last_revision_info()
2557
self.update_references(target)
2027
2558
if result.old_revid != self.last_revision():
2028
2559
# We assume that during 'push' this repository is closer than
2030
2561
graph = self.repository.get_graph(target.repository)
2031
target.update_revisions(self, stop_revision, overwrite=overwrite,
2562
target.update_revisions(self, stop_revision,
2563
overwrite=overwrite, graph=graph)
2033
2564
if self._push_should_merge_tags():
2034
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2565
result.tag_conflicts = self.tags.merge_to(target.tags,
2035
2567
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."""
2382
2799
"""Set the parent branch"""
2383
2800
return self._get_config_location('parent_location')
2803
def _set_all_reference_info(self, info_dict):
2804
"""Replace all reference info stored in a branch.
2806
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2809
writer = rio.RioWriter(s)
2810
for key, (tree_path, branch_location) in info_dict.iteritems():
2811
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2812
branch_location=branch_location)
2813
writer.write_stanza(stanza)
2814
self._transport.put_bytes('references', s.getvalue())
2815
self._reference_info = info_dict
2818
def _get_all_reference_info(self):
2819
"""Return all the reference info stored in a branch.
2821
:return: A dict of {file_id: (tree_path, branch_location)}
2823
if self._reference_info is not None:
2824
return self._reference_info
2825
rio_file = self._transport.get('references')
2827
stanzas = rio.read_stanzas(rio_file)
2828
info_dict = dict((s['file_id'], (s['tree_path'],
2829
s['branch_location'])) for s in stanzas)
2832
self._reference_info = info_dict
2835
def set_reference_info(self, file_id, tree_path, branch_location):
2836
"""Set the branch location to use for a tree reference.
2838
:param file_id: The file-id of the tree reference.
2839
:param tree_path: The path of the tree reference in the tree.
2840
:param branch_location: The location of the branch to retrieve tree
2843
info_dict = self._get_all_reference_info()
2844
info_dict[file_id] = (tree_path, branch_location)
2845
if None in (tree_path, branch_location):
2846
if tree_path is not None:
2847
raise ValueError('tree_path must be None when branch_location'
2849
if branch_location is not None:
2850
raise ValueError('branch_location must be None when tree_path'
2852
del info_dict[file_id]
2853
self._set_all_reference_info(info_dict)
2855
def get_reference_info(self, file_id):
2856
"""Get the tree_path and branch_location for a tree reference.
2858
:return: a tuple of (tree_path, branch_location)
2860
return self._get_all_reference_info().get(file_id, (None, None))
2862
def reference_parent(self, file_id, path, possible_transports=None):
2863
"""Return the parent branch for a tree-reference file_id.
2865
:param file_id: The file_id of the tree reference
2866
:param path: The path of the file_id in the tree
2867
:return: A branch associated with the file_id
2869
branch_location = self.get_reference_info(file_id)[1]
2870
if branch_location is None:
2871
return Branch.reference_parent(self, file_id, path,
2872
possible_transports)
2873
branch_location = urlutils.join(self.user_url, branch_location)
2874
return Branch.open(branch_location,
2875
possible_transports=possible_transports)
2385
2877
def set_push_location(self, location):
2386
2878
"""See Branch.set_push_location."""
2387
2879
self._set_config_location('push_location', location)
2689
3173
target.unlock()
3177
class InterBranch(InterObject):
3178
"""This class represents operations taking place between two branches.
3180
Its instances have methods like pull() and push() and contain
3181
references to the source and target repositories these operations
3182
can be carried out on.
3186
"""The available optimised InterBranch types."""
3189
def _get_branch_formats_to_test():
3190
"""Return a tuple with the Branch formats to use when testing."""
3191
raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3193
def pull(self, overwrite=False, stop_revision=None,
3194
possible_transports=None, local=False):
3195
"""Mirror source into target branch.
3197
The target branch is considered to be 'local', having low latency.
3199
:returns: PullResult instance
3201
raise NotImplementedError(self.pull)
3203
def update_revisions(self, stop_revision=None, overwrite=False,
3205
"""Pull in new perfect-fit revisions.
3207
:param stop_revision: Updated until the given revision
3208
:param overwrite: Always set the branch pointer, rather than checking
3209
to see if it is a proper descendant.
3210
:param graph: A Graph object that can be used to query history
3211
information. This can be None.
3214
raise NotImplementedError(self.update_revisions)
3216
def push(self, overwrite=False, stop_revision=None,
3217
_override_hook_source_branch=None):
3218
"""Mirror the source branch into the target branch.
3220
The source branch is considered to be 'local', having low latency.
3222
raise NotImplementedError(self.push)
3225
class GenericInterBranch(InterBranch):
3226
"""InterBranch implementation that uses public Branch functions."""
3229
def is_compatible(klass, source, target):
3230
# GenericBranch uses the public API, so always compatible
3234
def _get_branch_formats_to_test():
3235
return BranchFormat._default_format, BranchFormat._default_format
3238
def unwrap_format(klass, format):
3239
if isinstance(format, remote.RemoteBranchFormat):
3240
format._ensure_real()
3241
return format._custom_format
3245
def copy_content_into(self, revision_id=None):
3246
"""Copy the content of source into target
3248
revision_id: if not None, the revision history in the new branch will
3249
be truncated to end with revision_id.
3251
self.source.update_references(self.target)
3252
self.source._synchronize_history(self.target, revision_id)
3254
parent = self.source.get_parent()
3255
except errors.InaccessibleParent, e:
3256
mutter('parent was not accessible to copy: %s', e)
3259
self.target.set_parent(parent)
3260
if self.source._push_should_merge_tags():
3261
self.source.tags.merge_to(self.target.tags)
3264
def update_revisions(self, stop_revision=None, overwrite=False,
3266
"""See InterBranch.update_revisions()."""
3267
other_revno, other_last_revision = self.source.last_revision_info()
3268
stop_revno = None # unknown
3269
if stop_revision is None:
3270
stop_revision = other_last_revision
3271
if _mod_revision.is_null(stop_revision):
3272
# if there are no commits, we're done.
3274
stop_revno = other_revno
3276
# what's the current last revision, before we fetch [and change it
3278
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3279
# we fetch here so that we don't process data twice in the common
3280
# case of having something to pull, and so that the check for
3281
# already merged can operate on the just fetched graph, which will
3282
# be cached in memory.
3283
self.target.fetch(self.source, stop_revision)
3284
# Check to see if one is an ancestor of the other
3287
graph = self.target.repository.get_graph()
3288
if self.target._check_if_descendant_or_diverged(
3289
stop_revision, last_rev, graph, self.source):
3290
# stop_revision is a descendant of last_rev, but we aren't
3291
# overwriting, so we're done.
3293
if stop_revno is None:
3295
graph = self.target.repository.get_graph()
3296
this_revno, this_last_revision = \
3297
self.target.last_revision_info()
3298
stop_revno = graph.find_distance_to_null(stop_revision,
3299
[(other_last_revision, other_revno),
3300
(this_last_revision, this_revno)])
3301
self.target.set_last_revision_info(stop_revno, stop_revision)
3303
def pull(self, overwrite=False, stop_revision=None,
3304
possible_transports=None, run_hooks=True,
3305
_override_hook_target=None, local=False):
3306
"""Pull from source into self, updating my master if any.
3308
:param run_hooks: Private parameter - if false, this branch
3309
is being called because it's the master of the primary branch,
3310
so it should not run its hooks.
3312
bound_location = self.target.get_bound_location()
3313
if local and not bound_location:
3314
raise errors.LocalRequiresBoundBranch()
3315
master_branch = None
3316
if not local and bound_location and self.source.user_url != bound_location:
3317
# not pulling from master, so we need to update master.
3318
master_branch = self.target.get_master_branch(possible_transports)
3319
master_branch.lock_write()
3322
# pull from source into master.
3323
master_branch.pull(self.source, overwrite, stop_revision,
3325
return self._pull(overwrite,
3326
stop_revision, _hook_master=master_branch,
3327
run_hooks=run_hooks,
3328
_override_hook_target=_override_hook_target)
3331
master_branch.unlock()
3333
def push(self, overwrite=False, stop_revision=None,
3334
_override_hook_source_branch=None):
3335
"""See InterBranch.push.
3337
This is the basic concrete implementation of push()
3339
:param _override_hook_source_branch: If specified, run
3340
the hooks passing this Branch as the source, rather than self.
3341
This is for use of RemoteBranch, where push is delegated to the
3342
underlying vfs-based Branch.
3344
# TODO: Public option to disable running hooks - should be trivial but
3346
self.source.lock_read()
3348
return _run_with_write_locked_target(
3349
self.target, self._push_with_bound_branches, overwrite,
3351
_override_hook_source_branch=_override_hook_source_branch)
3353
self.source.unlock()
3355
def _push_with_bound_branches(self, overwrite, stop_revision,
3356
_override_hook_source_branch=None):
3357
"""Push from source into target, and into target's master if any.
3360
if _override_hook_source_branch:
3361
result.source_branch = _override_hook_source_branch
3362
for hook in Branch.hooks['post_push']:
3365
bound_location = self.target.get_bound_location()
3366
if bound_location and self.target.base != bound_location:
3367
# there is a master branch.
3369
# XXX: Why the second check? Is it even supported for a branch to
3370
# be bound to itself? -- mbp 20070507
3371
master_branch = self.target.get_master_branch()
3372
master_branch.lock_write()
3374
# push into the master from the source branch.
3375
self.source._basic_push(master_branch, overwrite, stop_revision)
3376
# and push into the target branch from the source. Note that we
3377
# push from the source branch again, because its considered the
3378
# highest bandwidth repository.
3379
result = self.source._basic_push(self.target, overwrite,
3381
result.master_branch = master_branch
3382
result.local_branch = self.target
3386
master_branch.unlock()
3389
result = self.source._basic_push(self.target, overwrite,
3391
# TODO: Why set master_branch and local_branch if there's no
3392
# binding? Maybe cleaner to just leave them unset? -- mbp
3394
result.master_branch = self.target
3395
result.local_branch = None
3399
def _pull(self, overwrite=False, stop_revision=None,
3400
possible_transports=None, _hook_master=None, run_hooks=True,
3401
_override_hook_target=None, local=False):
3404
This function is the core worker, used by GenericInterBranch.pull to
3405
avoid duplication when pulling source->master and source->local.
3407
:param _hook_master: Private parameter - set the branch to
3408
be supplied as the master to pull hooks.
3409
:param run_hooks: Private parameter - if false, this branch
3410
is being called because it's the master of the primary branch,
3411
so it should not run its hooks.
3412
:param _override_hook_target: Private parameter - set the branch to be
3413
supplied as the target_branch to pull hooks.
3414
:param local: Only update the local branch, and not the bound branch.
3416
# This type of branch can't be bound.
3418
raise errors.LocalRequiresBoundBranch()
3419
result = PullResult()
3420
result.source_branch = self.source
3421
if _override_hook_target is None:
3422
result.target_branch = self.target
3424
result.target_branch = _override_hook_target
3425
self.source.lock_read()
3427
# We assume that during 'pull' the target repository is closer than
3429
self.source.update_references(self.target)
3430
graph = self.target.repository.get_graph(self.source.repository)
3431
# TODO: Branch formats should have a flag that indicates
3432
# that revno's are expensive, and pull() should honor that flag.
3434
result.old_revno, result.old_revid = \
3435
self.target.last_revision_info()
3436
self.target.update_revisions(self.source, stop_revision,
3437
overwrite=overwrite, graph=graph)
3438
# TODO: The old revid should be specified when merging tags,
3439
# so a tags implementation that versions tags can only
3440
# pull in the most recent changes. -- JRV20090506
3441
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3443
result.new_revno, result.new_revid = self.target.last_revision_info()
3445
result.master_branch = _hook_master
3446
result.local_branch = result.target_branch
3448
result.master_branch = result.target_branch
3449
result.local_branch = None
3451
for hook in Branch.hooks['post_pull']:
3454
self.source.unlock()
3458
InterBranch.register_optimiser(GenericInterBranch)