759
795
if not self._format.supports_stacking():
760
raise errors.UnstackableBranchFormat(self._format, self.user_url)
761
# XXX: Changing from one fallback repository to another does not check
762
# that all the data you need is present in the new fallback.
763
# Possibly it should.
764
self._check_stackable_repo()
767
old_url = self.get_stacked_on_url()
768
except (errors.NotStacked, errors.UnstackableBranchFormat,
769
errors.UnstackableRepositoryFormat):
773
self._activate_fallback_location(url)
774
# write this out after the repository is stacked to avoid setting a
775
# stacked config that doesn't work.
776
self._set_config_location('stacked_on_location', url)
796
raise UnstackableBranchFormat(self._format, self.user_url)
797
with self.lock_write():
798
# XXX: Changing from one fallback repository to another does not
799
# check that all the data you need is present in the new fallback.
800
# Possibly it should.
801
self._check_stackable_repo()
804
self.get_stacked_on_url()
805
except (errors.NotStacked, UnstackableBranchFormat,
806
errors.UnstackableRepositoryFormat):
810
self._activate_fallback_location(
811
url, possible_transports=[self.controldir.root_transport])
812
# write this out after the repository is stacked to avoid setting a
813
# stacked config that doesn't work.
814
self._set_config_location('stacked_on_location', url)
778
816
def _unstack(self):
779
817
"""Change a branch to be unstacked, copying data as needed.
781
819
Don't call this directly, use set_stacked_on_url(None).
783
pb = ui.ui_factory.nested_progress_bar()
785
pb.update("Unstacking")
821
with ui.ui_factory.nested_progress_bar() as pb:
822
pb.update(gettext("Unstacking"))
786
823
# The basic approach here is to fetch the tip of the branch,
787
824
# including all available ghosts, from the existing stacked
788
# repository into a new repository object without the fallbacks.
825
# repository into a new repository object without the fallbacks.
790
827
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
791
828
# correct for CHKMap repostiories
792
829
old_repository = self.repository
793
830
if len(old_repository._fallback_repositories) != 1:
794
raise AssertionError("can't cope with fallback repositories "
795
"of %r" % (self.repository,))
796
# unlock it, including unlocking the fallback
831
raise AssertionError(
832
"can't cope with fallback repositories "
833
"of %r (fallbacks: %r)" % (
834
old_repository, old_repository._fallback_repositories))
835
# Open the new repository object.
836
# Repositories don't offer an interface to remove fallback
837
# repositories today; take the conceptually simpler option and just
838
# reopen it. We reopen it starting from the URL so that we
839
# get a separate connection for RemoteRepositories and can
840
# stream from one of them to the other. This does mean doing
841
# separate SSH connection setup, but unstacking is not a
842
# common operation so it's tolerable.
843
new_bzrdir = controldir.ControlDir.open(
844
self.controldir.root_transport.base)
845
new_repository = new_bzrdir.find_repository()
846
if new_repository._fallback_repositories:
847
raise AssertionError(
848
"didn't expect %r to have fallback_repositories"
849
% (self.repository,))
850
# Replace self.repository with the new repository.
851
# Do our best to transfer the lock state (i.e. lock-tokens and
852
# lock count) of self.repository to the new repository.
853
lock_token = old_repository.lock_write().repository_token
854
self.repository = new_repository
855
if isinstance(self, remote.RemoteBranch):
856
# Remote branches can have a second reference to the old
857
# repository that need to be replaced.
858
if self._real_branch is not None:
859
self._real_branch.repository = new_repository
860
self.repository.lock_write(token=lock_token)
861
if lock_token is not None:
862
old_repository.leave_lock_in_place()
797
863
old_repository.unlock()
798
old_repository.lock_read()
800
# Repositories don't offer an interface to remove fallback
801
# repositories today; take the conceptually simpler option and just
802
# reopen it. We reopen it starting from the URL so that we
803
# get a separate connection for RemoteRepositories and can
804
# stream from one of them to the other. This does mean doing
805
# separate SSH connection setup, but unstacking is not a
806
# common operation so it's tolerable.
807
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
808
new_repository = new_bzrdir.find_repository()
809
self.repository = new_repository
810
if self.repository._fallback_repositories:
811
raise AssertionError("didn't expect %r to have "
812
"fallback_repositories"
813
% (self.repository,))
814
# this is not paired with an unlock because it's just restoring
815
# the previous state; the lock's released when set_stacked_on_url
864
if lock_token is not None:
865
# XXX: self.repository.leave_lock_in_place() before this
866
# function will not be preserved. Fortunately that doesn't
867
# affect the current default format (2a), and would be a
868
# corner-case anyway.
869
# - Andrew Bennetts, 2010/06/30
870
self.repository.dont_leave_lock_in_place()
874
old_repository.unlock()
875
except errors.LockNotHeld:
878
if old_lock_count == 0:
879
raise AssertionError(
880
'old_repository should have been locked at least once.')
881
for i in range(old_lock_count - 1):
817
882
self.repository.lock_write()
883
# Fetch from the old repository into the new.
884
with old_repository.lock_read():
818
885
# XXX: If you unstack a branch while it has a working tree
819
886
# with a pending merge, the pending-merged revisions will no
820
887
# longer be present. You can (probably) revert and remerge.
822
# XXX: This only fetches up to the tip of the repository; it
823
# doesn't bring across any tags. That's fairly consistent
824
# with how branch works, but perhaps not ideal.
825
self.repository.fetch(old_repository,
826
revision_id=self.last_revision(),
829
old_repository.unlock()
833
def _set_tags_bytes(self, bytes):
834
"""Mirror method for _get_tags_bytes.
836
:seealso: Branch._get_tags_bytes.
838
return _run_with_write_locked_target(self, self._transport.put_bytes,
889
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
890
except errors.TagsNotSupported:
891
tags_to_fetch = set()
892
fetch_spec = vf_search.NotInOtherForRevs(
893
self.repository, old_repository,
894
required_ids=[self.last_revision()],
895
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
896
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
841
898
def _cache_revision_history(self, rev_history):
842
899
"""Set the cached revision history to rev_history.
920
972
"""Return last revision id, or NULL_REVISION."""
921
973
return self.last_revision_info()[1]
924
975
def last_revision_info(self):
925
976
"""Return information about the last revision.
927
978
:return: A tuple (revno, revision_id).
929
if self._last_revision_info_cache is None:
930
self._last_revision_info_cache = self._last_revision_info()
931
return self._last_revision_info_cache
933
def _last_revision_info(self):
934
rh = self.revision_history()
937
return (revno, rh[-1])
939
return (0, _mod_revision.NULL_REVISION)
941
@deprecated_method(deprecated_in((1, 6, 0)))
942
def missing_revisions(self, other, stop_revision=None):
943
"""Return a list of new revisions that would perfectly fit.
945
If self and other have not diverged, return a list of the revisions
946
present in other, but missing from self.
948
self_history = self.revision_history()
949
self_len = len(self_history)
950
other_history = other.revision_history()
951
other_len = len(other_history)
952
common_index = min(self_len, other_len) -1
953
if common_index >= 0 and \
954
self_history[common_index] != other_history[common_index]:
955
raise errors.DivergedBranches(self, other)
957
if stop_revision is None:
958
stop_revision = other_len
960
if stop_revision > other_len:
961
raise errors.NoSuchRevision(self, stop_revision)
962
return other_history[self_len:stop_revision]
965
def update_revisions(self, other, stop_revision=None, overwrite=False,
967
"""Pull in new perfect-fit revisions.
969
:param other: Another Branch to pull from
970
:param stop_revision: Updated until the given revision
971
:param overwrite: Always set the branch pointer, rather than checking
972
to see if it is a proper descendant.
973
:param graph: A Graph object that can be used to query history
974
information. This can be None.
977
return InterBranch.get(other, self).update_revisions(stop_revision,
980
def import_last_revision_info(self, source_repo, revno, revid):
980
with self.lock_read():
981
if self._last_revision_info_cache is None:
982
self._last_revision_info_cache = (
983
self._read_last_revision_info())
984
return self._last_revision_info_cache
986
def _read_last_revision_info(self):
987
raise NotImplementedError(self._read_last_revision_info)
989
def import_last_revision_info_and_tags(self, source, revno, revid,
981
991
"""Set the last revision info, importing from another repo if necessary.
983
993
This is used by the bound branch code to upload a revision to
984
994
the master branch first before updating the tip of the local branch.
995
Revisions referenced by source's tags are also transferred.
986
:param source_repo: Source repository to optionally fetch from
997
:param source: Source branch to optionally fetch from
987
998
:param revno: Revision number of the new tip
988
999
:param revid: Revision id of the new tip
1000
:param lossy: Whether to discard metadata that can not be
1001
natively represented
1002
:return: Tuple with the new revision number and revision id
1003
(should only be different from the arguments when lossy=True)
990
if not self.repository.has_same_location(source_repo):
991
self.repository.fetch(source_repo, revision_id=revid)
1005
if not self.repository.has_same_location(source.repository):
1006
self.fetch(source, revid)
992
1007
self.set_last_revision_info(revno, revid)
1008
return (revno, revid)
994
1010
def revision_id_to_revno(self, revision_id):
995
1011
"""Given a revision id, return its revno"""
996
1012
if _mod_revision.is_null(revision_id):
998
history = self.revision_history()
1014
history = self._revision_history()
1000
1016
return history.index(revision_id) + 1
1001
1017
except ValueError:
1002
1018
raise errors.NoSuchRevision(self, revision_id)
1005
1020
def get_rev_id(self, revno, history=None):
1006
1021
"""Find the revision id of the specified revno."""
1008
return _mod_revision.NULL_REVISION
1009
last_revno, last_revid = self.last_revision_info()
1010
if revno == last_revno:
1012
if revno <= 0 or revno > last_revno:
1013
raise errors.NoSuchRevision(self, revno)
1014
distance_from_last = last_revno - revno
1015
if len(self._partial_revision_history_cache) <= distance_from_last:
1016
self._extend_partial_history(distance_from_last)
1017
return self._partial_revision_history_cache[distance_from_last]
1022
with self.lock_read():
1024
return _mod_revision.NULL_REVISION
1025
last_revno, last_revid = self.last_revision_info()
1026
if revno == last_revno:
1028
if revno <= 0 or revno > last_revno:
1029
raise errors.NoSuchRevision(self, revno)
1030
distance_from_last = last_revno - revno
1031
if len(self._partial_revision_history_cache) <= distance_from_last:
1032
self._extend_partial_history(distance_from_last)
1033
return self._partial_revision_history_cache[distance_from_last]
1020
1035
def pull(self, source, overwrite=False, stop_revision=None,
1021
1036
possible_transports=None, *args, **kwargs):
1022
1037
"""Mirror source into this branch.
1909
1850
return self.__dict__ == other.__dict__
1911
1852
def __repr__(self):
1912
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1913
self.control_dir, self.to_branch,
1853
return "<%s for %s to (%s, %s)>" % (
1854
self.__class__.__name__, self.control_dir, self.to_branch,
1914
1855
self.revision_id)
1917
class BzrBranchFormat4(BranchFormat):
1918
"""Bzr branch format 4.
1921
- a revision-history file.
1922
- a branch-lock lock file [ to be shared with the bzrdir ]
1925
def get_format_description(self):
1926
"""See BranchFormat.get_format_description()."""
1927
return "Branch format 4"
1929
def initialize(self, a_bzrdir, name=None):
1930
"""Create a branch of this format in a_bzrdir."""
1931
utf8_files = [('revision-history', ''),
1932
('branch-name', ''),
1934
return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1935
lock_type='branch4', set_format=False)
1938
super(BzrBranchFormat4, self).__init__()
1939
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1941
def network_name(self):
1942
"""The network name for this format is the control dirs disk label."""
1943
return self._matchingbzrdir.get_format_string()
1945
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1946
"""See BranchFormat.open()."""
1948
# we are being called directly and must probe.
1949
raise NotImplementedError
1950
return BzrBranch(_format=self,
1951
_control_files=a_bzrdir._control_files,
1954
_repository=a_bzrdir.open_repository())
1957
return "Bazaar-NG branch format 4"
1960
class BranchFormatMetadir(BranchFormat):
1961
"""Common logic for meta-dir based branch formats."""
1963
def _branch_class(self):
1964
"""What class to instantiate on open calls."""
1965
raise NotImplementedError(self._branch_class)
1967
def network_name(self):
1968
"""A simple byte string uniquely identifying this format for RPC calls.
1970
Metadir branch formats use their format string.
1972
return self.get_format_string()
1974
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1975
"""See BranchFormat.open()."""
1977
format = BranchFormat.find_format(a_bzrdir, name=name)
1978
if format.__class__ != self.__class__:
1979
raise AssertionError("wrong format %r found for %r" %
1981
transport = a_bzrdir.get_branch_transport(None, name=name)
1983
control_files = lockable_files.LockableFiles(transport, 'lock',
1985
return self._branch_class()(_format=self,
1986
_control_files=control_files,
1989
_repository=a_bzrdir.find_repository(),
1990
ignore_fallbacks=ignore_fallbacks)
1991
except errors.NoSuchFile:
1992
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1995
super(BranchFormatMetadir, self).__init__()
1996
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1997
self._matchingbzrdir.set_branch_format(self)
1999
def supports_tags(self):
2003
class BzrBranchFormat5(BranchFormatMetadir):
2004
"""Bzr branch format 5.
2007
- a revision-history file.
2009
- a lock dir guarding the branch itself
2010
- all of this stored in a branch/ subdirectory
2011
- works with shared repositories.
2013
This format is new in bzr 0.8.
2016
def _branch_class(self):
2019
def get_format_string(self):
2020
"""See BranchFormat.get_format_string()."""
2021
return "Bazaar-NG branch format 5\n"
2023
def get_format_description(self):
2024
"""See BranchFormat.get_format_description()."""
2025
return "Branch format 5"
2027
def initialize(self, a_bzrdir, name=None):
2028
"""Create a branch of this format in a_bzrdir."""
2029
utf8_files = [('revision-history', ''),
2030
('branch-name', ''),
2032
return self._initialize_helper(a_bzrdir, utf8_files, name)
2034
def supports_tags(self):
2038
class BzrBranchFormat6(BranchFormatMetadir):
2039
"""Branch format with last-revision and tags.
2041
Unlike previous formats, this has no explicit revision history. Instead,
2042
this just stores the last-revision, and the left-hand history leading
2043
up to there is the history.
2045
This format was introduced in bzr 0.15
2046
and became the default in 0.91.
2049
def _branch_class(self):
2052
def get_format_string(self):
2053
"""See BranchFormat.get_format_string()."""
2054
return "Bazaar Branch Format 6 (bzr 0.15)\n"
2056
def get_format_description(self):
2057
"""See BranchFormat.get_format_description()."""
2058
return "Branch format 6"
2060
def initialize(self, a_bzrdir, name=None):
2061
"""Create a branch of this format in a_bzrdir."""
2062
utf8_files = [('last-revision', '0 null:\n'),
2063
('branch.conf', ''),
2066
return self._initialize_helper(a_bzrdir, utf8_files, name)
2068
def make_tags(self, branch):
2069
"""See bzrlib.branch.BranchFormat.make_tags()."""
2070
return BasicTags(branch)
2072
def supports_set_append_revisions_only(self):
2076
class BzrBranchFormat8(BranchFormatMetadir):
2077
"""Metadir format supporting storing locations of subtree branches."""
2079
def _branch_class(self):
2082
def get_format_string(self):
2083
"""See BranchFormat.get_format_string()."""
2084
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2086
def get_format_description(self):
2087
"""See BranchFormat.get_format_description()."""
2088
return "Branch format 8"
2090
def initialize(self, a_bzrdir, name=None):
2091
"""Create a branch of this format in a_bzrdir."""
2092
utf8_files = [('last-revision', '0 null:\n'),
2093
('branch.conf', ''),
2097
return self._initialize_helper(a_bzrdir, utf8_files, name)
2100
super(BzrBranchFormat8, self).__init__()
2101
self._matchingbzrdir.repository_format = \
2102
RepositoryFormatKnitPack5RichRoot()
2104
def make_tags(self, branch):
2105
"""See bzrlib.branch.BranchFormat.make_tags()."""
2106
return BasicTags(branch)
2108
def supports_set_append_revisions_only(self):
2111
def supports_stacking(self):
2114
supports_reference_locations = True
2117
class BzrBranchFormat7(BzrBranchFormat8):
2118
"""Branch format with last-revision, tags, and a stacked location pointer.
2120
The stacked location pointer is passed down to the repository and requires
2121
a repository format with supports_external_lookups = True.
2123
This format was introduced in bzr 1.6.
2126
def initialize(self, a_bzrdir, name=None):
2127
"""Create a branch of this format in a_bzrdir."""
2128
utf8_files = [('last-revision', '0 null:\n'),
2129
('branch.conf', ''),
2132
return self._initialize_helper(a_bzrdir, utf8_files, name)
2134
def _branch_class(self):
2137
def get_format_string(self):
2138
"""See BranchFormat.get_format_string()."""
2139
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2141
def get_format_description(self):
2142
"""See BranchFormat.get_format_description()."""
2143
return "Branch format 7"
2145
def supports_set_append_revisions_only(self):
2148
supports_reference_locations = False
2151
class BranchReferenceFormat(BranchFormat):
2152
"""Bzr branch reference format.
2154
Branch references are used in implementing checkouts, they
2155
act as an alias to the real branch which is at some other url.
2162
def get_format_string(self):
2163
"""See BranchFormat.get_format_string()."""
2164
return "Bazaar-NG Branch Reference Format 1\n"
2166
def get_format_description(self):
2167
"""See BranchFormat.get_format_description()."""
2168
return "Checkout reference format 1"
2170
def get_reference(self, a_bzrdir):
2171
"""See BranchFormat.get_reference()."""
2172
transport = a_bzrdir.get_branch_transport(None)
2173
return transport.get_bytes('location')
2175
def set_reference(self, a_bzrdir, to_branch):
2176
"""See BranchFormat.set_reference()."""
2177
transport = a_bzrdir.get_branch_transport(None)
2178
location = transport.put_bytes('location', to_branch.base)
2180
def initialize(self, a_bzrdir, name=None, target_branch=None):
2181
"""Create a branch of this format in a_bzrdir."""
2182
if target_branch is None:
2183
# this format does not implement branch itself, thus the implicit
2184
# creation contract must see it as uninitializable
2185
raise errors.UninitializableFormat(self)
2186
mutter('creating branch reference in %s', a_bzrdir.user_url)
2187
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2188
branch_transport.put_bytes('location',
2189
target_branch.bzrdir.user_url)
2190
branch_transport.put_bytes('format', self.get_format_string())
2192
a_bzrdir, name, _found=True,
2193
possible_transports=[target_branch.bzrdir.root_transport])
2194
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2198
super(BranchReferenceFormat, self).__init__()
2199
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2200
self._matchingbzrdir.set_branch_format(self)
2202
def _make_reference_clone_function(format, a_branch):
2203
"""Create a clone() routine for a branch dynamically."""
2204
def clone(to_bzrdir, revision_id=None,
2205
repository_policy=None):
2206
"""See Branch.clone()."""
2207
return format.initialize(to_bzrdir, target_branch=a_branch)
2208
# cannot obey revision_id limits when cloning a reference ...
2209
# FIXME RBC 20060210 either nuke revision_id for clone, or
2210
# emit some sort of warning/error to the caller ?!
2213
def open(self, a_bzrdir, name=None, _found=False, location=None,
2214
possible_transports=None, ignore_fallbacks=False):
2215
"""Return the branch that the branch reference in a_bzrdir points at.
2217
:param a_bzrdir: A BzrDir that contains a branch.
2218
:param name: Name of colocated branch to open, if any
2219
:param _found: a private parameter, do not use it. It is used to
2220
indicate if format probing has already be done.
2221
:param ignore_fallbacks: when set, no fallback branches will be opened
2222
(if there are any). Default is to open fallbacks.
2223
:param location: The location of the referenced branch. If
2224
unspecified, this will be determined from the branch reference in
2226
:param possible_transports: An optional reusable transports list.
2229
format = BranchFormat.find_format(a_bzrdir, name=name)
2230
if format.__class__ != self.__class__:
2231
raise AssertionError("wrong format %r found for %r" %
2233
if location is None:
2234
location = self.get_reference(a_bzrdir)
2235
real_bzrdir = bzrdir.BzrDir.open(
2236
location, possible_transports=possible_transports)
2237
result = real_bzrdir.open_branch(name=name,
2238
ignore_fallbacks=ignore_fallbacks)
2239
# this changes the behaviour of result.clone to create a new reference
2240
# rather than a copy of the content of the branch.
2241
# I did not use a proxy object because that needs much more extensive
2242
# testing, and we are only changing one behaviour at the moment.
2243
# If we decide to alter more behaviours - i.e. the implicit nickname
2244
# then this should be refactored to introduce a tested proxy branch
2245
# and a subclass of that for use in overriding clone() and ....
2247
result.clone = self._make_reference_clone_function(result)
1858
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1859
"""Branch format registry."""
1861
def __init__(self, other_registry=None):
1862
super(BranchFormatRegistry, self).__init__(other_registry)
1863
self._default_format = None
1864
self._default_format_key = None
1866
def get_default(self):
1867
"""Return the current default format."""
1868
if (self._default_format_key is not None
1869
and self._default_format is None):
1870
self._default_format = self.get(self._default_format_key)
1871
return self._default_format
1873
def set_default(self, format):
1874
"""Set the default format."""
1875
self._default_format = format
1876
self._default_format_key = None
1878
def set_default_key(self, format_string):
1879
"""Set the default format by its format string."""
1880
self._default_format_key = format_string
1881
self._default_format = None
2251
1884
network_format_registry = registry.FormatRegistry()
2256
1889
BranchFormat.network_name() for more detail.
1892
format_registry = BranchFormatRegistry(network_format_registry)
2260
1895
# formats which have no format string are not discoverable
2261
1896
# and not independently creatable, so are not registered.
2262
__format5 = BzrBranchFormat5()
2263
__format6 = BzrBranchFormat6()
2264
__format7 = BzrBranchFormat7()
2265
__format8 = BzrBranchFormat8()
2266
BranchFormat.register_format(__format5)
2267
BranchFormat.register_format(BranchReferenceFormat())
2268
BranchFormat.register_format(__format6)
2269
BranchFormat.register_format(__format7)
2270
BranchFormat.register_format(__format8)
2271
BranchFormat.set_default_format(__format7)
2272
_legacy_formats = [BzrBranchFormat4(),
2274
network_format_registry.register(
2275
_legacy_formats[0].network_name(), _legacy_formats[0].__class__)
1897
format_registry.register_lazy(
1898
b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1900
format_registry.register_lazy(
1901
b"Bazaar Branch Format 6 (bzr 0.15)\n",
1902
"breezy.bzr.branch", "BzrBranchFormat6")
1903
format_registry.register_lazy(
1904
b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1905
"breezy.bzr.branch", "BzrBranchFormat7")
1906
format_registry.register_lazy(
1907
b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1908
"breezy.bzr.branch", "BzrBranchFormat8")
1909
format_registry.register_lazy(
1910
b"Bazaar-NG Branch Reference Format 1\n",
1911
"breezy.bzr.branch", "BranchReferenceFormat")
1913
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
2278
1916
class BranchWriteLockResult(LogicalLockResult):
2279
1917
"""The result of write locking a branch.
2281
:ivar branch_token: The token obtained from the underlying branch lock, or
1919
:ivar token: The token obtained from the underlying branch lock, or
2283
1921
:ivar unlock: A callable which will unlock the lock.
2286
def __init__(self, unlock, branch_token):
2287
LogicalLockResult.__init__(self, unlock)
2288
self.branch_token = branch_token
2290
1924
def __repr__(self):
2291
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2295
class BzrBranch(Branch, _RelockDebugMixin):
2296
"""A branch stored in the actual filesystem.
2298
Note that it's "local" in the context of the filesystem; it doesn't
2299
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2300
it's writable, and can be accessed via the normal filesystem API.
2302
:ivar _transport: Transport for file operations on this branch's
2303
control files, typically pointing to the .bzr/branch directory.
2304
:ivar repository: Repository for this branch.
2305
:ivar base: The url of the base directory for this branch; the one
2306
containing the .bzr directory.
2307
:ivar name: Optional colocated branch name as it exists in the control
2311
def __init__(self, _format=None,
2312
_control_files=None, a_bzrdir=None, name=None,
2313
_repository=None, ignore_fallbacks=False):
2314
"""Create new branch object at a particular location."""
2315
if a_bzrdir is None:
2316
raise ValueError('a_bzrdir must be supplied')
2318
self.bzrdir = a_bzrdir
2319
self._base = self.bzrdir.transport.clone('..').base
2321
# XXX: We should be able to just do
2322
# self.base = self.bzrdir.root_transport.base
2323
# but this does not quite work yet -- mbp 20080522
2324
self._format = _format
2325
if _control_files is None:
2326
raise ValueError('BzrBranch _control_files is None')
2327
self.control_files = _control_files
2328
self._transport = _control_files._transport
2329
self.repository = _repository
2330
Branch.__init__(self)
2333
if self.name is None:
2334
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2336
return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2341
def _get_base(self):
2342
"""Returns the directory containing the control directory."""
2345
base = property(_get_base, doc="The URL for the root of this branch.")
2347
def _get_config(self):
2348
return TransportConfig(self._transport, 'branch.conf')
2350
def is_locked(self):
2351
return self.control_files.is_locked()
2353
def lock_write(self, token=None):
2354
"""Lock the branch for write operations.
2356
:param token: A token to permit reacquiring a previously held and
2358
:return: A BranchWriteLockResult.
2360
if not self.is_locked():
2361
self._note_lock('w')
2362
# All-in-one needs to always unlock/lock.
2363
repo_control = getattr(self.repository, 'control_files', None)
2364
if self.control_files == repo_control or not self.is_locked():
2365
self.repository._warn_if_deprecated(self)
2366
self.repository.lock_write()
2371
return BranchWriteLockResult(self.unlock,
2372
self.control_files.lock_write(token=token))
2375
self.repository.unlock()
2378
def lock_read(self):
2379
"""Lock the branch for read operations.
2381
:return: A bzrlib.lock.LogicalLockResult.
2383
if not self.is_locked():
2384
self._note_lock('r')
2385
# All-in-one needs to always unlock/lock.
2386
repo_control = getattr(self.repository, 'control_files', None)
2387
if self.control_files == repo_control or not self.is_locked():
2388
self.repository._warn_if_deprecated(self)
2389
self.repository.lock_read()
2394
self.control_files.lock_read()
2395
return LogicalLockResult(self.unlock)
2398
self.repository.unlock()
2401
@only_raises(errors.LockNotHeld, errors.LockBroken)
2404
self.control_files.unlock()
2406
# All-in-one needs to always unlock/lock.
2407
repo_control = getattr(self.repository, 'control_files', None)
2408
if (self.control_files == repo_control or
2409
not self.control_files.is_locked()):
2410
self.repository.unlock()
2411
if not self.control_files.is_locked():
2412
# we just released the lock
2413
self._clear_cached_state()
2415
def peek_lock_mode(self):
2416
if self.control_files._lock_count == 0:
2419
return self.control_files._lock_mode
2421
def get_physical_lock_status(self):
2422
return self.control_files.get_physical_lock_status()
2425
def print_file(self, file, revision_id):
2426
"""See Branch.print_file."""
2427
return self.repository.print_file(file, revision_id)
2429
def _write_revision_history(self, history):
2430
"""Factored out of set_revision_history.
2432
This performs the actual writing to disk.
2433
It is intended to be called by BzrBranch5.set_revision_history."""
2434
self._transport.put_bytes(
2435
'revision-history', '\n'.join(history),
2436
mode=self.bzrdir._get_file_mode())
2439
def set_revision_history(self, rev_history):
2440
"""See Branch.set_revision_history."""
2441
if 'evil' in debug.debug_flags:
2442
mutter_callsite(3, "set_revision_history scales with history.")
2443
check_not_reserved_id = _mod_revision.check_not_reserved_id
2444
for rev_id in rev_history:
2445
check_not_reserved_id(rev_id)
2446
if Branch.hooks['post_change_branch_tip']:
2447
# Don't calculate the last_revision_info() if there are no hooks
2449
old_revno, old_revid = self.last_revision_info()
2450
if len(rev_history) == 0:
2451
revid = _mod_revision.NULL_REVISION
2453
revid = rev_history[-1]
2454
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2455
self._write_revision_history(rev_history)
2456
self._clear_cached_state()
2457
self._cache_revision_history(rev_history)
2458
for hook in Branch.hooks['set_rh']:
2459
hook(self, rev_history)
2460
if Branch.hooks['post_change_branch_tip']:
2461
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2463
def _synchronize_history(self, destination, revision_id):
2464
"""Synchronize last revision and revision history between branches.
2466
This version is most efficient when the destination is also a
2467
BzrBranch5, but works for BzrBranch6 as long as the revision
2468
history is the true lefthand parent history, and all of the revisions
2469
are in the destination's repository. If not, set_revision_history
2472
:param destination: The branch to copy the history into
2473
:param revision_id: The revision-id to truncate history at. May
2474
be None to copy complete history.
2476
if not isinstance(destination._format, BzrBranchFormat5):
2477
super(BzrBranch, self)._synchronize_history(
2478
destination, revision_id)
2480
if revision_id == _mod_revision.NULL_REVISION:
2483
new_history = self.revision_history()
2484
if revision_id is not None and new_history != []:
2486
new_history = new_history[:new_history.index(revision_id) + 1]
2488
rev = self.repository.get_revision(revision_id)
2489
new_history = rev.get_history(self.repository)[1:]
2490
destination.set_revision_history(new_history)
2493
def set_last_revision_info(self, revno, revision_id):
2494
"""Set the last revision of this branch.
2496
The caller is responsible for checking that the revno is correct
2497
for this revision id.
2499
It may be possible to set the branch last revision to an id not
2500
present in the repository. However, branches can also be
2501
configured to check constraints on history, in which case this may not
2504
revision_id = _mod_revision.ensure_null(revision_id)
2505
# this old format stores the full history, but this api doesn't
2506
# provide it, so we must generate, and might as well check it's
2508
history = self._lefthand_history(revision_id)
2509
if len(history) != revno:
2510
raise AssertionError('%d != %d' % (len(history), revno))
2511
self.set_revision_history(history)
2513
def _gen_revision_history(self):
2514
history = self._transport.get_bytes('revision-history').split('\n')
2515
if history[-1:] == ['']:
2516
# There shouldn't be a trailing newline, but just in case.
2521
def generate_revision_history(self, revision_id, last_rev=None,
2523
"""Create a new revision history that will finish with revision_id.
2525
:param revision_id: the new tip to use.
2526
:param last_rev: The previous last_revision. If not None, then this
2527
must be a ancestory of revision_id, or DivergedBranches is raised.
2528
:param other_branch: The other branch that DivergedBranches should
2529
raise with respect to.
2531
self.set_revision_history(self._lefthand_history(revision_id,
2532
last_rev, other_branch))
2534
def basis_tree(self):
2535
"""See Branch.basis_tree."""
2536
return self.repository.revision_tree(self.last_revision())
2538
def _get_parent_location(self):
2539
_locs = ['parent', 'pull', 'x-pull']
2542
return self._transport.get_bytes(l).strip('\n')
2543
except errors.NoSuchFile:
2547
def _basic_push(self, target, overwrite, stop_revision):
2548
"""Basic implementation of push without bound branches or hooks.
2550
Must be called with source read locked and target write locked.
2552
result = BranchPushResult()
2553
result.source_branch = self
2554
result.target_branch = target
2555
result.old_revno, result.old_revid = target.last_revision_info()
2556
self.update_references(target)
2557
if result.old_revid != self.last_revision():
2558
# We assume that during 'push' this repository is closer than
2560
graph = self.repository.get_graph(target.repository)
2561
target.update_revisions(self, stop_revision,
2562
overwrite=overwrite, graph=graph)
2563
if self._push_should_merge_tags():
2564
result.tag_conflicts = self.tags.merge_to(target.tags,
2566
result.new_revno, result.new_revid = target.last_revision_info()
2569
def get_stacked_on_url(self):
2570
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2572
def set_push_location(self, location):
2573
"""See Branch.set_push_location."""
2574
self.get_config().set_user_option(
2575
'push_location', location,
2576
store=_mod_config.STORE_LOCATION_NORECURSE)
2578
def _set_parent_location(self, url):
2580
self._transport.delete('parent')
2582
self._transport.put_bytes('parent', url + '\n',
2583
mode=self.bzrdir._get_file_mode())
2586
class BzrBranch5(BzrBranch):
2587
"""A format 5 branch. This supports new features over plain branches.
2589
It has support for a master_branch which is the data for bound branches.
2592
def get_bound_location(self):
2594
return self._transport.get_bytes('bound')[:-1]
2595
except errors.NoSuchFile:
2599
def get_master_branch(self, possible_transports=None):
2600
"""Return the branch we are bound to.
2602
:return: Either a Branch, or None
2604
This could memoise the branch, but if thats done
2605
it must be revalidated on each new lock.
2606
So for now we just don't memoise it.
2607
# RBC 20060304 review this decision.
2609
bound_loc = self.get_bound_location()
2613
return Branch.open(bound_loc,
2614
possible_transports=possible_transports)
2615
except (errors.NotBranchError, errors.ConnectionError), e:
2616
raise errors.BoundBranchConnectionFailure(
2620
def set_bound_location(self, location):
2621
"""Set the target where this branch is bound to.
2623
:param location: URL to the target branch
2626
self._transport.put_bytes('bound', location+'\n',
2627
mode=self.bzrdir._get_file_mode())
2630
self._transport.delete('bound')
2631
except errors.NoSuchFile:
2636
def bind(self, other):
2637
"""Bind this branch to the branch other.
2639
This does not push or pull data between the branches, though it does
2640
check for divergence to raise an error when the branches are not
2641
either the same, or one a prefix of the other. That behaviour may not
2642
be useful, so that check may be removed in future.
2644
:param other: The branch to bind to
2647
# TODO: jam 20051230 Consider checking if the target is bound
2648
# It is debatable whether you should be able to bind to
2649
# a branch which is itself bound.
2650
# Committing is obviously forbidden,
2651
# but binding itself may not be.
2652
# Since we *have* to check at commit time, we don't
2653
# *need* to check here
2655
# we want to raise diverged if:
2656
# last_rev is not in the other_last_rev history, AND
2657
# other_last_rev is not in our history, and do it without pulling
2659
self.set_bound_location(other.base)
2663
"""If bound, unbind"""
2664
return self.set_bound_location(None)
2667
def update(self, possible_transports=None):
2668
"""Synchronise this branch with the master branch if any.
2670
:return: None or the last_revision that was pivoted out during the
2673
master = self.get_master_branch(possible_transports)
2674
if master is not None:
2675
old_tip = _mod_revision.ensure_null(self.last_revision())
2676
self.pull(master, overwrite=True)
2677
if self.repository.get_graph().is_ancestor(old_tip,
2678
_mod_revision.ensure_null(self.last_revision())):
2684
class BzrBranch8(BzrBranch5):
2685
"""A branch that stores tree-reference locations."""
2687
def _open_hook(self):
2688
if self._ignore_fallbacks:
2691
url = self.get_stacked_on_url()
2692
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2693
errors.UnstackableBranchFormat):
2696
for hook in Branch.hooks['transform_fallback_location']:
2697
url = hook(self, url)
2699
hook_name = Branch.hooks.get_hook_name(hook)
2700
raise AssertionError(
2701
"'transform_fallback_location' hook %s returned "
2702
"None, not a URL." % hook_name)
2703
self._activate_fallback_location(url)
2705
def __init__(self, *args, **kwargs):
2706
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2707
super(BzrBranch8, self).__init__(*args, **kwargs)
2708
self._last_revision_info_cache = None
2709
self._reference_info = None
2711
def _clear_cached_state(self):
2712
super(BzrBranch8, self)._clear_cached_state()
2713
self._last_revision_info_cache = None
2714
self._reference_info = None
2716
def _last_revision_info(self):
2717
revision_string = self._transport.get_bytes('last-revision')
2718
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2719
revision_id = cache_utf8.get_cached_utf8(revision_id)
2721
return revno, revision_id
2723
def _write_last_revision_info(self, revno, revision_id):
2724
"""Simply write out the revision id, with no checks.
2726
Use set_last_revision_info to perform this safely.
2728
Does not update the revision_history cache.
2729
Intended to be called by set_last_revision_info and
2730
_write_revision_history.
2732
revision_id = _mod_revision.ensure_null(revision_id)
2733
out_string = '%d %s\n' % (revno, revision_id)
2734
self._transport.put_bytes('last-revision', out_string,
2735
mode=self.bzrdir._get_file_mode())
2738
def set_last_revision_info(self, revno, revision_id):
2739
revision_id = _mod_revision.ensure_null(revision_id)
2740
old_revno, old_revid = self.last_revision_info()
2741
if self._get_append_revisions_only():
2742
self._check_history_violation(revision_id)
2743
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2744
self._write_last_revision_info(revno, revision_id)
2745
self._clear_cached_state()
2746
self._last_revision_info_cache = revno, revision_id
2747
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2749
def _synchronize_history(self, destination, revision_id):
2750
"""Synchronize last revision and revision history between branches.
2752
:see: Branch._synchronize_history
2754
# XXX: The base Branch has a fast implementation of this method based
2755
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2756
# that uses set_revision_history. This class inherits from BzrBranch5,
2757
# but wants the fast implementation, so it calls
2758
# Branch._synchronize_history directly.
2759
Branch._synchronize_history(self, destination, revision_id)
2761
def _check_history_violation(self, revision_id):
2762
last_revision = _mod_revision.ensure_null(self.last_revision())
2763
if _mod_revision.is_null(last_revision):
2765
if last_revision not in self._lefthand_history(revision_id):
2766
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2768
def _gen_revision_history(self):
2769
"""Generate the revision history from last revision
2771
last_revno, last_revision = self.last_revision_info()
2772
self._extend_partial_history(stop_index=last_revno-1)
2773
return list(reversed(self._partial_revision_history_cache))
2775
def _write_revision_history(self, history):
2776
"""Factored out of set_revision_history.
2778
This performs the actual writing to disk, with format-specific checks.
2779
It is intended to be called by BzrBranch5.set_revision_history.
2781
if len(history) == 0:
2782
last_revision = 'null:'
2784
if history != self._lefthand_history(history[-1]):
2785
raise errors.NotLefthandHistory(history)
2786
last_revision = history[-1]
2787
if self._get_append_revisions_only():
2788
self._check_history_violation(last_revision)
2789
self._write_last_revision_info(len(history), last_revision)
2792
def _set_parent_location(self, url):
2793
"""Set the parent branch"""
2794
self._set_config_location('parent_location', url, make_relative=True)
2797
def _get_parent_location(self):
2798
"""Set the parent branch"""
2799
return self._get_config_location('parent_location')
2802
def _set_all_reference_info(self, info_dict):
2803
"""Replace all reference info stored in a branch.
2805
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2808
writer = rio.RioWriter(s)
2809
for key, (tree_path, branch_location) in info_dict.iteritems():
2810
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2811
branch_location=branch_location)
2812
writer.write_stanza(stanza)
2813
self._transport.put_bytes('references', s.getvalue())
2814
self._reference_info = info_dict
2817
def _get_all_reference_info(self):
2818
"""Return all the reference info stored in a branch.
2820
:return: A dict of {file_id: (tree_path, branch_location)}
2822
if self._reference_info is not None:
2823
return self._reference_info
2824
rio_file = self._transport.get('references')
2826
stanzas = rio.read_stanzas(rio_file)
2827
info_dict = dict((s['file_id'], (s['tree_path'],
2828
s['branch_location'])) for s in stanzas)
2831
self._reference_info = info_dict
2834
def set_reference_info(self, file_id, tree_path, branch_location):
2835
"""Set the branch location to use for a tree reference.
2837
:param file_id: The file-id of the tree reference.
2838
:param tree_path: The path of the tree reference in the tree.
2839
:param branch_location: The location of the branch to retrieve tree
2842
info_dict = self._get_all_reference_info()
2843
info_dict[file_id] = (tree_path, branch_location)
2844
if None in (tree_path, branch_location):
2845
if tree_path is not None:
2846
raise ValueError('tree_path must be None when branch_location'
2848
if branch_location is not None:
2849
raise ValueError('branch_location must be None when tree_path'
2851
del info_dict[file_id]
2852
self._set_all_reference_info(info_dict)
2854
def get_reference_info(self, file_id):
2855
"""Get the tree_path and branch_location for a tree reference.
2857
:return: a tuple of (tree_path, branch_location)
2859
return self._get_all_reference_info().get(file_id, (None, None))
2861
def reference_parent(self, file_id, path, possible_transports=None):
2862
"""Return the parent branch for a tree-reference file_id.
2864
:param file_id: The file_id of the tree reference
2865
:param path: The path of the file_id in the tree
2866
:return: A branch associated with the file_id
2868
branch_location = self.get_reference_info(file_id)[1]
2869
if branch_location is None:
2870
return Branch.reference_parent(self, file_id, path,
2871
possible_transports)
2872
branch_location = urlutils.join(self.user_url, branch_location)
2873
return Branch.open(branch_location,
2874
possible_transports=possible_transports)
2876
def set_push_location(self, location):
2877
"""See Branch.set_push_location."""
2878
self._set_config_location('push_location', location)
2880
def set_bound_location(self, location):
2881
"""See Branch.set_push_location."""
2883
config = self.get_config()
2884
if location is None:
2885
if config.get_user_option('bound') != 'True':
2888
config.set_user_option('bound', 'False', warn_masked=True)
2891
self._set_config_location('bound_location', location,
2893
config.set_user_option('bound', 'True', warn_masked=True)
2896
def _get_bound_location(self, bound):
2897
"""Return the bound location in the config file.
2899
Return None if the bound parameter does not match"""
2900
config = self.get_config()
2901
config_bound = (config.get_user_option('bound') == 'True')
2902
if config_bound != bound:
2904
return self._get_config_location('bound_location', config=config)
2906
def get_bound_location(self):
2907
"""See Branch.set_push_location."""
2908
return self._get_bound_location(True)
2910
def get_old_bound_location(self):
2911
"""See Branch.get_old_bound_location"""
2912
return self._get_bound_location(False)
2914
def get_stacked_on_url(self):
2915
# you can always ask for the URL; but you might not be able to use it
2916
# if the repo can't support stacking.
2917
## self._check_stackable_repo()
2918
stacked_url = self._get_config_location('stacked_on_location')
2919
if stacked_url is None:
2920
raise errors.NotStacked(self)
2923
def _get_append_revisions_only(self):
2924
return self.get_config(
2925
).get_user_option_as_bool('append_revisions_only')
2928
def generate_revision_history(self, revision_id, last_rev=None,
2930
"""See BzrBranch5.generate_revision_history"""
2931
history = self._lefthand_history(revision_id, last_rev, other_branch)
2932
revno = len(history)
2933
self.set_last_revision_info(revno, revision_id)
2936
def get_rev_id(self, revno, history=None):
2937
"""Find the revision id of the specified revno."""
2939
return _mod_revision.NULL_REVISION
2941
last_revno, last_revision_id = self.last_revision_info()
2942
if revno <= 0 or revno > last_revno:
2943
raise errors.NoSuchRevision(self, revno)
2945
if history is not None:
2946
return history[revno - 1]
2948
index = last_revno - revno
2949
if len(self._partial_revision_history_cache) <= index:
2950
self._extend_partial_history(stop_index=index)
2951
if len(self._partial_revision_history_cache) > index:
2952
return self._partial_revision_history_cache[index]
2954
raise errors.NoSuchRevision(self, revno)
2957
def revision_id_to_revno(self, revision_id):
2958
"""Given a revision id, return its revno"""
2959
if _mod_revision.is_null(revision_id):
2962
index = self._partial_revision_history_cache.index(revision_id)
2964
self._extend_partial_history(stop_revision=revision_id)
2965
index = len(self._partial_revision_history_cache) - 1
2966
if self._partial_revision_history_cache[index] != revision_id:
2967
raise errors.NoSuchRevision(self, revision_id)
2968
return self.revno() - index
2971
class BzrBranch7(BzrBranch8):
2972
"""A branch with support for a fallback repository."""
2974
def set_reference_info(self, file_id, tree_path, branch_location):
2975
Branch.set_reference_info(self, file_id, tree_path, branch_location)
2977
def get_reference_info(self, file_id):
2978
Branch.get_reference_info(self, file_id)
2980
def reference_parent(self, file_id, path, possible_transports=None):
2981
return Branch.reference_parent(self, file_id, path,
2982
possible_transports)
2985
class BzrBranch6(BzrBranch7):
2986
"""See BzrBranchFormat6 for the capabilities of this branch.
2988
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2992
def get_stacked_on_url(self):
2993
raise errors.UnstackableBranchFormat(self._format, self.user_url)
1925
return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
2996
1928
######################################################################
3264
2201
if graph is None:
3265
2202
graph = self.target.repository.get_graph()
3266
2203
this_revno, this_last_revision = \
3267
self.target.last_revision_info()
3268
stop_revno = graph.find_distance_to_null(stop_revision,
3269
[(other_last_revision, other_revno),
3270
(this_last_revision, this_revno)])
2204
self.target.last_revision_info()
2205
stop_revno = graph.find_distance_to_null(
2206
stop_revision, [(other_last_revision, other_revno),
2207
(this_last_revision, this_revno)])
3271
2208
self.target.set_last_revision_info(stop_revno, stop_revision)
3273
self.source.unlock()
3275
2210
def pull(self, overwrite=False, stop_revision=None,
3276
possible_transports=None, _hook_master=None, run_hooks=True,
3277
_override_hook_target=None, local=False):
2211
possible_transports=None, run_hooks=True,
2212
_override_hook_target=None, local=False,
2214
"""Pull from source into self, updating my master if any.
2216
:param run_hooks: Private parameter - if false, this branch
2217
is being called because it's the master of the primary branch,
2218
so it should not run its hooks.
2220
with contextlib.ExitStack() as exit_stack:
2221
exit_stack.enter_context(self.target.lock_write())
2222
bound_location = self.target.get_bound_location()
2223
if local and not bound_location:
2224
raise errors.LocalRequiresBoundBranch()
2225
master_branch = None
2226
source_is_master = False
2228
# bound_location comes from a config file, some care has to be
2229
# taken to relate it to source.user_url
2230
normalized = urlutils.normalize_url(bound_location)
2232
relpath = self.source.user_transport.relpath(normalized)
2233
source_is_master = (relpath == '')
2234
except (errors.PathNotChild, urlutils.InvalidURL):
2235
source_is_master = False
2236
if not local and bound_location and not source_is_master:
2237
# not pulling from master, so we need to update master.
2238
master_branch = self.target.get_master_branch(
2239
possible_transports)
2240
exit_stack.enter_context(master_branch.lock_write())
2242
# pull from source into master.
2244
self.source, overwrite, stop_revision, run_hooks=False,
2245
tag_selector=tag_selector)
2247
overwrite, stop_revision, _hook_master=master_branch,
2248
run_hooks=run_hooks,
2249
_override_hook_target=_override_hook_target,
2250
merge_tags_to_master=not source_is_master,
2251
tag_selector=tag_selector)
2253
def push(self, overwrite=False, stop_revision=None, lossy=False,
2254
_override_hook_source_branch=None, tag_selector=None):
2255
"""See InterBranch.push.
2257
This is the basic concrete implementation of push()
2259
:param _override_hook_source_branch: If specified, run the hooks
2260
passing this Branch as the source, rather than self. This is for
2261
use of RemoteBranch, where push is delegated to the underlying
2265
raise errors.LossyPushToSameVCS(self.source, self.target)
2266
# TODO: Public option to disable running hooks - should be trivial but
2270
if _override_hook_source_branch:
2271
result.source_branch = _override_hook_source_branch
2272
for hook in Branch.hooks['post_push']:
2275
with self.source.lock_read(), self.target.lock_write():
2276
bound_location = self.target.get_bound_location()
2277
if bound_location and self.target.base != bound_location:
2278
# there is a master branch.
2280
# XXX: Why the second check? Is it even supported for a branch
2281
# to be bound to itself? -- mbp 20070507
2282
master_branch = self.target.get_master_branch()
2283
with master_branch.lock_write():
2284
# push into the master from the source branch.
2285
master_inter = InterBranch.get(self.source, master_branch)
2286
master_inter._basic_push(
2287
overwrite, stop_revision, tag_selector=tag_selector)
2288
# and push into the target branch from the source. Note
2289
# that we push from the source branch again, because it's
2290
# considered the highest bandwidth repository.
2291
result = self._basic_push(
2292
overwrite, stop_revision, tag_selector=tag_selector)
2293
result.master_branch = master_branch
2294
result.local_branch = self.target
2297
master_branch = None
2299
result = self._basic_push(
2300
overwrite, stop_revision, tag_selector=tag_selector)
2301
# TODO: Why set master_branch and local_branch if there's no
2302
# binding? Maybe cleaner to just leave them unset? -- mbp
2304
result.master_branch = self.target
2305
result.local_branch = None
2309
def _basic_push(self, overwrite, stop_revision, tag_selector=None):
2310
"""Basic implementation of push without bound branches or hooks.
2312
Must be called with source read locked and target write locked.
2314
result = BranchPushResult()
2315
result.source_branch = self.source
2316
result.target_branch = self.target
2317
result.old_revno, result.old_revid = self.target.last_revision_info()
2318
overwrite = _fix_overwrite_type(overwrite)
2319
if result.old_revid != stop_revision:
2320
# We assume that during 'push' this repository is closer than
2322
graph = self.source.repository.get_graph(self.target.repository)
2323
self._update_revisions(
2324
stop_revision, overwrite=("history" in overwrite), graph=graph)
2325
if self.source._push_should_merge_tags():
2326
result.tag_updates, result.tag_conflicts = (
2327
self.source.tags.merge_to(
2328
self.target.tags, "tags" in overwrite, selector=tag_selector))
2329
self.update_references()
2330
result.new_revno, result.new_revid = self.target.last_revision_info()
2333
def _pull(self, overwrite=False, stop_revision=None,
2334
possible_transports=None, _hook_master=None, run_hooks=True,
2335
_override_hook_target=None, local=False,
2336
merge_tags_to_master=True, tag_selector=None):
3278
2337
"""See Branch.pull.
2339
This function is the core worker, used by GenericInterBranch.pull to
2340
avoid duplication when pulling source->master and source->local.
3280
2342
:param _hook_master: Private parameter - set the branch to
3281
2343
be supplied as the master to pull hooks.
3282
2344
:param run_hooks: Private parameter - if false, this branch
3283
2345
is being called because it's the master of the primary branch,
3284
2346
so it should not run its hooks.
2347
is being called because it's the master of the primary branch,
2348
so it should not run its hooks.
3285
2349
:param _override_hook_target: Private parameter - set the branch to be
3286
2350
supplied as the target_branch to pull hooks.
3287
2351
:param local: Only update the local branch, and not the bound branch.