14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
from cStringIO import StringIO
21
from bzrlib.lazy_import import lazy_import
17
from __future__ import absolute_import
21
from .lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
from itertools import chain
27
config as _mod_config,
33
revision as _mod_revision,
41
from bzrlib.config import BranchConfig, TransportConfig
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
43
from bzrlib.tag import (
29
config as _mod_config,
38
revision as _mod_revision,
47
from breezy.i18n import gettext, ngettext
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
from bzrlib.hooks import HookPoint, Hooks
51
from bzrlib.inter import InterObject
52
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
from bzrlib import registry
54
from bzrlib.symbol_versioning import (
50
# Explicitly import breezy.bzrdir so that the BzrProber
51
# is guaranteed to be registered.
59
from .decorators import (
64
from .hooks import Hooks
65
from .inter import InterObject
66
from .lock import _RelockDebugMixin, LogicalLockResult
70
from .symbol_versioning import (
58
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
61
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
62
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
class Branch(bzrdir.ControlComponent):
74
from .trace import mutter, mutter_callsite, note, is_quiet
77
class Branch(controldir.ControlComponent):
67
78
"""Branch holding a history of revisions.
70
81
Base directory/url of the branch; using control_url and
71
82
control_transport is more standardized.
73
hooks: An instance of BranchHooks.
83
:ivar hooks: An instance of BranchHooks.
84
:ivar _master_branch_cache: cached result of get_master_branch, see
75
87
# this is really an instance variable - FIXME move it there
792
880
old_repository = self.repository
793
881
if len(old_repository._fallback_repositories) != 1:
794
882
raise AssertionError("can't cope with fallback repositories "
795
"of %r" % (self.repository,))
796
# unlock it, including unlocking the fallback
883
"of %r (fallbacks: %r)" % (old_repository,
884
old_repository._fallback_repositories))
885
# Open the new repository object.
886
# Repositories don't offer an interface to remove fallback
887
# repositories today; take the conceptually simpler option and just
888
# reopen it. We reopen it starting from the URL so that we
889
# get a separate connection for RemoteRepositories and can
890
# stream from one of them to the other. This does mean doing
891
# separate SSH connection setup, but unstacking is not a
892
# common operation so it's tolerable.
893
new_bzrdir = controldir.ControlDir.open(
894
self.bzrdir.root_transport.base)
895
new_repository = new_bzrdir.find_repository()
896
if new_repository._fallback_repositories:
897
raise AssertionError("didn't expect %r to have "
898
"fallback_repositories"
899
% (self.repository,))
900
# Replace self.repository with the new repository.
901
# Do our best to transfer the lock state (i.e. lock-tokens and
902
# lock count) of self.repository to the new repository.
903
lock_token = old_repository.lock_write().repository_token
904
self.repository = new_repository
905
if isinstance(self, remote.RemoteBranch):
906
# Remote branches can have a second reference to the old
907
# repository that need to be replaced.
908
if self._real_branch is not None:
909
self._real_branch.repository = new_repository
910
self.repository.lock_write(token=lock_token)
911
if lock_token is not None:
912
old_repository.leave_lock_in_place()
797
913
old_repository.unlock()
914
if lock_token is not None:
915
# XXX: self.repository.leave_lock_in_place() before this
916
# function will not be preserved. Fortunately that doesn't
917
# affect the current default format (2a), and would be a
918
# corner-case anyway.
919
# - Andrew Bennetts, 2010/06/30
920
self.repository.dont_leave_lock_in_place()
924
old_repository.unlock()
925
except errors.LockNotHeld:
928
if old_lock_count == 0:
929
raise AssertionError(
930
'old_repository should have been locked at least once.')
931
for i in range(old_lock_count-1):
932
self.repository.lock_write()
933
# Fetch from the old repository into the new.
798
934
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
817
self.repository.lock_write()
818
936
# XXX: If you unstack a branch while it has a working tree
819
937
# with a pending merge, the pending-merged revisions will no
820
938
# 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(),
940
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
941
except errors.TagsNotSupported:
942
tags_to_fetch = set()
943
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
944
old_repository, required_ids=[self.last_revision()],
945
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
946
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
829
948
old_repository.unlock()
927
1047
:return: A tuple (revno, revision_id).
929
1049
if self._last_revision_info_cache is None:
930
self._last_revision_info_cache = self._last_revision_info()
1050
self._last_revision_info_cache = self._read_last_revision_info()
931
1051
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):
1053
def _read_last_revision_info(self):
1054
raise NotImplementedError(self._read_last_revision_info)
1056
def import_last_revision_info_and_tags(self, source, revno, revid,
981
1058
"""Set the last revision info, importing from another repo if necessary.
983
1060
This is used by the bound branch code to upload a revision to
984
1061
the master branch first before updating the tip of the local branch.
1062
Revisions referenced by source's tags are also transferred.
986
:param source_repo: Source repository to optionally fetch from
1064
:param source: Source branch to optionally fetch from
987
1065
:param revno: Revision number of the new tip
988
1066
:param revid: Revision id of the new tip
1067
:param lossy: Whether to discard metadata that can not be
1068
natively represented
1069
:return: Tuple with the new revision number and revision id
1070
(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)
1072
if not self.repository.has_same_location(source.repository):
1073
self.fetch(source, revid)
992
1074
self.set_last_revision_info(revno, revid)
1075
return (revno, revid)
994
1077
def revision_id_to_revno(self, revision_id):
995
1078
"""Given a revision id, return its revno"""
996
1079
if _mod_revision.is_null(revision_id):
998
history = self.revision_history()
1081
history = self._revision_history()
1000
1083
return history.index(revision_id) + 1
1001
1084
except ValueError:
1502
1590
object will be created every time regardless.
1505
_default_format = None
1506
"""The default format used for new branches."""
1509
"""The known formats."""
1511
can_set_append_revisions_only = True
1513
1593
def __eq__(self, other):
1514
1594
return self.__class__ is other.__class__
1516
1596
def __ne__(self, other):
1517
1597
return not (self == other)
1520
def find_format(klass, a_bzrdir, name=None):
1521
"""Return the format for the branch object in a_bzrdir."""
1523
transport = a_bzrdir.get_branch_transport(None, name=name)
1524
format_string = transport.get_bytes("format")
1525
return klass._formats[format_string]
1526
except errors.NoSuchFile:
1527
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1529
raise errors.UnknownFormatError(format=format_string, kind='branch')
1532
def get_default_format(klass):
1533
"""Return the current default format."""
1534
return klass._default_format
1536
def get_reference(self, a_bzrdir, name=None):
1537
"""Get the target reference of the branch in a_bzrdir.
1599
def get_reference(self, controldir, name=None):
1600
"""Get the target reference of the branch in controldir.
1539
1602
format probing must have been completed before calling
1540
1603
this method - it is assumed that the format of the branch
1541
in a_bzrdir is correct.
1604
in controldir is correct.
1543
:param a_bzrdir: The bzrdir to get the branch data from.
1606
:param controldir: The controldir to get the branch data from.
1544
1607
:param name: Name of the colocated branch to fetch
1545
1608
:return: None if the branch is not a reference branch.
1550
def set_reference(self, a_bzrdir, name, to_branch):
1551
"""Set the target reference of the branch in a_bzrdir.
1613
def set_reference(self, controldir, name, to_branch):
1614
"""Set the target reference of the branch in controldir.
1553
1616
format probing must have been completed before calling
1554
1617
this method - it is assumed that the format of the branch
1555
in a_bzrdir is correct.
1618
in controldir is correct.
1557
:param a_bzrdir: The bzrdir to set the branch reference for.
1620
:param controldir: The controldir to set the branch reference for.
1558
1621
:param name: Name of colocated branch to set, None for default
1559
1622
:param to_branch: branch that the checkout is to reference
1561
1624
raise NotImplementedError(self.set_reference)
1563
def get_format_string(self):
1564
"""Return the ASCII format string that identifies this format."""
1565
raise NotImplementedError(self.get_format_string)
1567
1626
def get_format_description(self):
1568
1627
"""Return the short format description for this format."""
1569
1628
raise NotImplementedError(self.get_format_description)
1571
def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1630
def _run_post_branch_init_hooks(self, controldir, name, branch):
1572
1631
hooks = Branch.hooks['post_branch_init']
1575
params = BranchInitHookParams(self, a_bzrdir, name, branch)
1634
params = BranchInitHookParams(self, controldir, name, branch)
1576
1635
for hook in hooks:
1579
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1580
lock_type='metadir', set_format=True):
1581
"""Initialize a branch in a bzrdir, with specified files
1583
:param a_bzrdir: The bzrdir to initialize the branch in
1584
:param utf8_files: The files to create as a list of
1585
(filename, content) tuples
1586
:param name: Name of colocated branch to create, if any
1587
:param set_format: If True, set the format with
1588
self.get_format_string. (BzrBranch4 has its format set
1590
:return: a branch in this format
1592
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1593
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1595
'metadir': ('lock', lockdir.LockDir),
1596
'branch4': ('branch-lock', lockable_files.TransportLock),
1598
lock_name, lock_class = lock_map[lock_type]
1599
control_files = lockable_files.LockableFiles(branch_transport,
1600
lock_name, lock_class)
1601
control_files.create_lock()
1603
control_files.lock_write()
1604
except errors.LockContention:
1605
if lock_type != 'branch4':
1611
utf8_files += [('format', self.get_format_string())]
1613
for (filename, content) in utf8_files:
1614
branch_transport.put_bytes(
1616
mode=a_bzrdir._get_file_mode())
1619
control_files.unlock()
1620
branch = self.open(a_bzrdir, name, _found=True)
1621
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1624
def initialize(self, a_bzrdir, name=None):
1625
"""Create a branch of this format in a_bzrdir.
1638
def initialize(self, controldir, name=None, repository=None,
1639
append_revisions_only=None):
1640
"""Create a branch of this format in controldir.
1627
1642
:param name: Name of the colocated branch to create.
1629
1644
raise NotImplementedError(self.initialize)
1745
1779
"basis revision. hooks MUST NOT modify this delta. "
1746
1780
" future_tree is an in-memory tree obtained from "
1747
1781
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1748
"tree.", (0,91), None))
1749
self.create_hook(HookPoint('post_commit',
1783
self.add_hook('post_commit',
1750
1784
"Called in the bzr client after a commit has completed. "
1751
1785
"post_commit is called with (local, master, old_revno, old_revid, "
1752
1786
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1753
"commit to a branch.", (0, 15), None))
1754
self.create_hook(HookPoint('post_uncommit',
1787
"commit to a branch.", (0, 15))
1788
self.add_hook('post_uncommit',
1755
1789
"Called in the bzr client after an uncommit completes. "
1756
1790
"post_uncommit is called with (local, master, old_revno, "
1757
1791
"old_revid, new_revno, new_revid) where local is the local branch "
1758
1792
"or None, master is the target branch, and an empty branch "
1759
"receives new_revno of 0, new_revid of None.", (0, 15), None))
1760
self.create_hook(HookPoint('pre_change_branch_tip',
1793
"receives new_revno of 0, new_revid of None.", (0, 15))
1794
self.add_hook('pre_change_branch_tip',
1761
1795
"Called in bzr client and server before a change to the tip of a "
1762
1796
"branch is made. pre_change_branch_tip is called with a "
1763
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1764
"commit, uncommit will all trigger this hook.", (1, 6), None))
1765
self.create_hook(HookPoint('post_change_branch_tip',
1797
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1798
"commit, uncommit will all trigger this hook.", (1, 6))
1799
self.add_hook('post_change_branch_tip',
1766
1800
"Called in bzr client and server after a change to the tip of a "
1767
1801
"branch is made. post_change_branch_tip is called with a "
1768
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1769
"commit, uncommit will all trigger this hook.", (1, 4), None))
1770
self.create_hook(HookPoint('transform_fallback_location',
1802
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1803
"commit, uncommit will all trigger this hook.", (1, 4))
1804
self.add_hook('transform_fallback_location',
1771
1805
"Called when a stacked branch is activating its fallback "
1772
1806
"locations. transform_fallback_location is called with (branch, "
1773
1807
"url), and should return a new url. Returning the same url "
1918
1947
self.revision_id)
1921
class BzrBranchFormat4(BranchFormat):
1922
"""Bzr branch format 4.
1925
- a revision-history file.
1926
- a branch-lock lock file [ to be shared with the bzrdir ]
1950
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
1951
"""Base class for branch formats that live in meta directories.
1929
def get_format_description(self):
1930
"""See BranchFormat.get_format_description()."""
1931
return "Branch format 4"
1933
def initialize(self, a_bzrdir, name=None):
1934
"""Create a branch of this format in a_bzrdir."""
1935
utf8_files = [('revision-history', ''),
1936
('branch-name', ''),
1938
return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1939
lock_type='branch4', set_format=False)
1941
1954
def __init__(self):
1942
super(BzrBranchFormat4, self).__init__()
1943
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1945
def network_name(self):
1946
"""The network name for this format is the control dirs disk label."""
1947
return self._matchingbzrdir.get_format_string()
1949
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1950
"""See BranchFormat.open()."""
1952
# we are being called directly and must probe.
1953
raise NotImplementedError
1954
return BzrBranch(_format=self,
1955
_control_files=a_bzrdir._control_files,
1958
_repository=a_bzrdir.open_repository())
1961
return "Bazaar-NG branch format 4"
1964
class BranchFormatMetadir(BranchFormat):
1965
"""Common logic for meta-dir based branch formats."""
1955
BranchFormat.__init__(self)
1956
bzrdir.BzrFormat.__init__(self)
1959
def find_format(klass, controldir, name=None):
1960
"""Return the format for the branch object in controldir."""
1962
transport = controldir.get_branch_transport(None, name=name)
1963
except errors.NoSuchFile:
1964
raise errors.NotBranchError(path=name, bzrdir=controldir)
1966
format_string = transport.get_bytes("format")
1967
except errors.NoSuchFile:
1968
raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1969
return klass._find_format(format_registry, 'branch', format_string)
1967
1971
def _branch_class(self):
1968
1972
"""What class to instantiate on open calls."""
1969
1973
raise NotImplementedError(self._branch_class)
1971
def network_name(self):
1972
"""A simple byte string uniquely identifying this format for RPC calls.
1974
Metadir branch formats use their format string.
1975
def _get_initial_config(self, append_revisions_only=None):
1976
if append_revisions_only:
1977
return "append_revisions_only = True\n"
1979
# Avoid writing anything if append_revisions_only is disabled,
1980
# as that is the default.
1983
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1985
"""Initialize a branch in a control dir, with specified files
1987
:param a_bzrdir: The bzrdir to initialize the branch in
1988
:param utf8_files: The files to create as a list of
1989
(filename, content) tuples
1990
:param name: Name of colocated branch to create, if any
1991
:return: a branch in this format
1976
return self.get_format_string()
1994
name = a_bzrdir._get_selected_branch()
1995
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1996
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1997
control_files = lockable_files.LockableFiles(branch_transport,
1998
'lock', lockdir.LockDir)
1999
control_files.create_lock()
2000
control_files.lock_write()
2002
utf8_files += [('format', self.as_string())]
2003
for (filename, content) in utf8_files:
2004
branch_transport.put_bytes(
2006
mode=a_bzrdir._get_file_mode())
2008
control_files.unlock()
2009
branch = self.open(a_bzrdir, name, _found=True,
2010
found_repository=repository)
2011
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1978
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2014
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2015
found_repository=None, possible_transports=None):
1979
2016
"""See BranchFormat.open()."""
2018
name = a_bzrdir._get_selected_branch()
1981
format = BranchFormat.find_format(a_bzrdir, name=name)
2020
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
1982
2021
if format.__class__ != self.__class__:
1983
2022
raise AssertionError("wrong format %r found for %r" %
1984
2023
(format, self))
1987
2026
control_files = lockable_files.LockableFiles(transport, 'lock',
1988
2027
lockdir.LockDir)
2028
if found_repository is None:
2029
found_repository = a_bzrdir.find_repository()
1989
2030
return self._branch_class()(_format=self,
1990
2031
_control_files=control_files,
1992
2033
a_bzrdir=a_bzrdir,
1993
_repository=a_bzrdir.find_repository(),
1994
ignore_fallbacks=ignore_fallbacks)
2034
_repository=found_repository,
2035
ignore_fallbacks=ignore_fallbacks,
2036
possible_transports=possible_transports)
1995
2037
except errors.NoSuchFile:
1996
2038
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1999
super(BranchFormatMetadir, self).__init__()
2000
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2001
self._matchingbzrdir.set_branch_format(self)
2003
def supports_tags(self):
2007
class BzrBranchFormat5(BranchFormatMetadir):
2008
"""Bzr branch format 5.
2011
- a revision-history file.
2013
- a lock dir guarding the branch itself
2014
- all of this stored in a branch/ subdirectory
2015
- works with shared repositories.
2017
This format is new in bzr 0.8.
2020
def _branch_class(self):
2023
def get_format_string(self):
2024
"""See BranchFormat.get_format_string()."""
2025
return "Bazaar-NG branch format 5\n"
2027
def get_format_description(self):
2028
"""See BranchFormat.get_format_description()."""
2029
return "Branch format 5"
2031
def initialize(self, a_bzrdir, name=None):
2032
"""Create a branch of this format in a_bzrdir."""
2033
utf8_files = [('revision-history', ''),
2034
('branch-name', ''),
2036
return self._initialize_helper(a_bzrdir, utf8_files, name)
2038
def supports_tags(self):
2041
def _matchingbzrdir(self):
2042
ret = bzrdir.BzrDirMetaFormat1()
2043
ret.set_branch_format(self)
2046
def supports_tags(self):
2049
def supports_leaving_lock(self):
2052
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
2054
BranchFormat.check_support_status(self,
2055
allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
2057
bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
2058
recommend_upgrade=recommend_upgrade, basedir=basedir)
2042
2061
class BzrBranchFormat6(BranchFormatMetadir):
2430
2515
"""See Branch.print_file."""
2431
2516
return self.repository.print_file(file, revision_id)
2433
def _write_revision_history(self, history):
2434
"""Factored out of set_revision_history.
2436
This performs the actual writing to disk.
2437
It is intended to be called by BzrBranch5.set_revision_history."""
2438
self._transport.put_bytes(
2439
'revision-history', '\n'.join(history),
2440
mode=self.bzrdir._get_file_mode())
2443
def set_revision_history(self, rev_history):
2444
"""See Branch.set_revision_history."""
2445
if 'evil' in debug.debug_flags:
2446
mutter_callsite(3, "set_revision_history scales with history.")
2447
check_not_reserved_id = _mod_revision.check_not_reserved_id
2448
for rev_id in rev_history:
2449
check_not_reserved_id(rev_id)
2450
if Branch.hooks['post_change_branch_tip']:
2451
# Don't calculate the last_revision_info() if there are no hooks
2453
old_revno, old_revid = self.last_revision_info()
2454
if len(rev_history) == 0:
2455
revid = _mod_revision.NULL_REVISION
2457
revid = rev_history[-1]
2458
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2459
self._write_revision_history(rev_history)
2460
self._clear_cached_state()
2461
self._cache_revision_history(rev_history)
2462
for hook in Branch.hooks['set_rh']:
2463
hook(self, rev_history)
2464
if Branch.hooks['post_change_branch_tip']:
2465
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2467
def _synchronize_history(self, destination, revision_id):
2468
"""Synchronize last revision and revision history between branches.
2470
This version is most efficient when the destination is also a
2471
BzrBranch5, but works for BzrBranch6 as long as the revision
2472
history is the true lefthand parent history, and all of the revisions
2473
are in the destination's repository. If not, set_revision_history
2476
:param destination: The branch to copy the history into
2477
:param revision_id: The revision-id to truncate history at. May
2478
be None to copy complete history.
2480
if not isinstance(destination._format, BzrBranchFormat5):
2481
super(BzrBranch, self)._synchronize_history(
2482
destination, revision_id)
2484
if revision_id == _mod_revision.NULL_REVISION:
2487
new_history = self.revision_history()
2488
if revision_id is not None and new_history != []:
2490
new_history = new_history[:new_history.index(revision_id) + 1]
2492
rev = self.repository.get_revision(revision_id)
2493
new_history = rev.get_history(self.repository)[1:]
2494
destination.set_revision_history(new_history)
2496
2518
@needs_write_lock
2497
2519
def set_last_revision_info(self, revno, revision_id):
2498
"""Set the last revision of this branch.
2500
The caller is responsible for checking that the revno is correct
2501
for this revision id.
2503
It may be possible to set the branch last revision to an id not
2504
present in the repository. However, branches can also be
2505
configured to check constraints on history, in which case this may not
2520
if not revision_id or not isinstance(revision_id, basestring):
2521
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2508
2522
revision_id = _mod_revision.ensure_null(revision_id)
2509
# this old format stores the full history, but this api doesn't
2510
# provide it, so we must generate, and might as well check it's
2512
history = self._lefthand_history(revision_id)
2513
if len(history) != revno:
2514
raise AssertionError('%d != %d' % (len(history), revno))
2515
self.set_revision_history(history)
2517
def _gen_revision_history(self):
2518
history = self._transport.get_bytes('revision-history').split('\n')
2519
if history[-1:] == ['']:
2520
# There shouldn't be a trailing newline, but just in case.
2525
def generate_revision_history(self, revision_id, last_rev=None,
2527
"""Create a new revision history that will finish with revision_id.
2529
:param revision_id: the new tip to use.
2530
:param last_rev: The previous last_revision. If not None, then this
2531
must be a ancestory of revision_id, or DivergedBranches is raised.
2532
:param other_branch: The other branch that DivergedBranches should
2533
raise with respect to.
2535
self.set_revision_history(self._lefthand_history(revision_id,
2536
last_rev, other_branch))
2523
old_revno, old_revid = self.last_revision_info()
2524
if self.get_append_revisions_only():
2525
self._check_history_violation(revision_id)
2526
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2527
self._write_last_revision_info(revno, revision_id)
2528
self._clear_cached_state()
2529
self._last_revision_info_cache = revno, revision_id
2530
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2538
2532
def basis_tree(self):
2539
2533
"""See Branch.basis_tree."""
2717
2716
self._last_revision_info_cache = None
2718
2717
self._reference_info = None
2720
def _last_revision_info(self):
2721
revision_string = self._transport.get_bytes('last-revision')
2722
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2723
revision_id = cache_utf8.get_cached_utf8(revision_id)
2725
return revno, revision_id
2727
def _write_last_revision_info(self, revno, revision_id):
2728
"""Simply write out the revision id, with no checks.
2730
Use set_last_revision_info to perform this safely.
2732
Does not update the revision_history cache.
2733
Intended to be called by set_last_revision_info and
2734
_write_revision_history.
2736
revision_id = _mod_revision.ensure_null(revision_id)
2737
out_string = '%d %s\n' % (revno, revision_id)
2738
self._transport.put_bytes('last-revision', out_string,
2739
mode=self.bzrdir._get_file_mode())
2742
def set_last_revision_info(self, revno, revision_id):
2743
revision_id = _mod_revision.ensure_null(revision_id)
2744
old_revno, old_revid = self.last_revision_info()
2745
if self._get_append_revisions_only():
2746
self._check_history_violation(revision_id)
2747
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2748
self._write_last_revision_info(revno, revision_id)
2749
self._clear_cached_state()
2750
self._last_revision_info_cache = revno, revision_id
2751
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2753
def _synchronize_history(self, destination, revision_id):
2754
"""Synchronize last revision and revision history between branches.
2756
:see: Branch._synchronize_history
2758
# XXX: The base Branch has a fast implementation of this method based
2759
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2760
# that uses set_revision_history. This class inherits from BzrBranch5,
2761
# but wants the fast implementation, so it calls
2762
# Branch._synchronize_history directly.
2763
Branch._synchronize_history(self, destination, revision_id)
2765
2719
def _check_history_violation(self, revision_id):
2766
last_revision = _mod_revision.ensure_null(self.last_revision())
2720
current_revid = self.last_revision()
2721
last_revision = _mod_revision.ensure_null(current_revid)
2767
2722
if _mod_revision.is_null(last_revision):
2769
if last_revision not in self._lefthand_history(revision_id):
2770
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2724
graph = self.repository.get_graph()
2725
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2726
if lh_ancestor == current_revid:
2728
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2772
2730
def _gen_revision_history(self):
2773
2731
"""Generate the revision history from last revision
3225
3144
raise NotImplementedError(self.push)
3147
def copy_content_into(self, revision_id=None):
3148
"""Copy the content of source into target
3150
revision_id: if not None, the revision history in the new branch will
3151
be truncated to end with revision_id.
3153
raise NotImplementedError(self.copy_content_into)
3156
def fetch(self, stop_revision=None, limit=None):
3159
:param stop_revision: Last revision to fetch
3160
:param limit: Optional rough limit of revisions to fetch
3162
raise NotImplementedError(self.fetch)
3165
def _fix_overwrite_type(overwrite):
3166
if isinstance(overwrite, bool):
3168
return ["history", "tags"]
3228
3174
class GenericInterBranch(InterBranch):
3229
"""InterBranch implementation that uses public Branch functions.
3233
def _get_branch_formats_to_test():
3234
return BranchFormat._default_format, BranchFormat._default_format
3236
def update_revisions(self, stop_revision=None, overwrite=False,
3238
"""See InterBranch.update_revisions()."""
3175
"""InterBranch implementation that uses public Branch functions."""
3178
def is_compatible(klass, source, target):
3179
# GenericBranch uses the public API, so always compatible
3183
def _get_branch_formats_to_test(klass):
3184
return [(format_registry.get_default(), format_registry.get_default())]
3187
def unwrap_format(klass, format):
3188
if isinstance(format, remote.RemoteBranchFormat):
3189
format._ensure_real()
3190
return format._custom_format
3194
def copy_content_into(self, revision_id=None):
3195
"""Copy the content of source into target
3197
revision_id: if not None, the revision history in the new branch will
3198
be truncated to end with revision_id.
3200
self.source.update_references(self.target)
3201
self.source._synchronize_history(self.target, revision_id)
3203
parent = self.source.get_parent()
3204
except errors.InaccessibleParent as e:
3205
mutter('parent was not accessible to copy: %s', e)
3208
self.target.set_parent(parent)
3209
if self.source._push_should_merge_tags():
3210
self.source.tags.merge_to(self.target.tags)
3213
def fetch(self, stop_revision=None, limit=None):
3214
if self.target.base == self.source.base:
3239
3216
self.source.lock_read()
3241
other_revno, other_last_revision = self.source.last_revision_info()
3242
stop_revno = None # unknown
3243
if stop_revision is None:
3244
stop_revision = other_last_revision
3245
if _mod_revision.is_null(stop_revision):
3246
# if there are no commits, we're done.
3248
stop_revno = other_revno
3250
# what's the current last revision, before we fetch [and change it
3252
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3253
# we fetch here so that we don't process data twice in the common
3254
# case of having something to pull, and so that the check for
3255
# already merged can operate on the just fetched graph, which will
3256
# be cached in memory.
3257
self.target.fetch(self.source, stop_revision)
3258
# Check to see if one is an ancestor of the other
3261
graph = self.target.repository.get_graph()
3262
if self.target._check_if_descendant_or_diverged(
3263
stop_revision, last_rev, graph, self.source):
3264
# stop_revision is a descendant of last_rev, but we aren't
3265
# overwriting, so we're done.
3267
if stop_revno is None:
3269
graph = self.target.repository.get_graph()
3270
this_revno, this_last_revision = \
3271
self.target.last_revision_info()
3272
stop_revno = graph.find_distance_to_null(stop_revision,
3273
[(other_last_revision, other_revno),
3274
(this_last_revision, this_revno)])
3275
self.target.set_last_revision_info(stop_revno, stop_revision)
3218
fetch_spec_factory = fetch.FetchSpecFactory()
3219
fetch_spec_factory.source_branch = self.source
3220
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3221
fetch_spec_factory.source_repo = self.source.repository
3222
fetch_spec_factory.target_repo = self.target.repository
3223
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3224
fetch_spec_factory.limit = limit
3225
fetch_spec = fetch_spec_factory.make_fetch_spec()
3226
return self.target.repository.fetch(self.source.repository,
3227
fetch_spec=fetch_spec)
3277
3229
self.source.unlock()
3232
def _update_revisions(self, stop_revision=None, overwrite=False,
3234
other_revno, other_last_revision = self.source.last_revision_info()
3235
stop_revno = None # unknown
3236
if stop_revision is None:
3237
stop_revision = other_last_revision
3238
if _mod_revision.is_null(stop_revision):
3239
# if there are no commits, we're done.
3241
stop_revno = other_revno
3243
# what's the current last revision, before we fetch [and change it
3245
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3246
# we fetch here so that we don't process data twice in the common
3247
# case of having something to pull, and so that the check for
3248
# already merged can operate on the just fetched graph, which will
3249
# be cached in memory.
3250
self.fetch(stop_revision=stop_revision)
3251
# Check to see if one is an ancestor of the other
3254
graph = self.target.repository.get_graph()
3255
if self.target._check_if_descendant_or_diverged(
3256
stop_revision, last_rev, graph, self.source):
3257
# stop_revision is a descendant of last_rev, but we aren't
3258
# overwriting, so we're done.
3260
if stop_revno is None:
3262
graph = self.target.repository.get_graph()
3263
this_revno, this_last_revision = \
3264
self.target.last_revision_info()
3265
stop_revno = graph.find_distance_to_null(stop_revision,
3266
[(other_last_revision, other_revno),
3267
(this_last_revision, this_revno)])
3268
self.target.set_last_revision_info(stop_revno, stop_revision)
3279
3271
def pull(self, overwrite=False, stop_revision=None,
3272
possible_transports=None, run_hooks=True,
3273
_override_hook_target=None, local=False):
3274
"""Pull from source into self, updating my master if any.
3276
:param run_hooks: Private parameter - if false, this branch
3277
is being called because it's the master of the primary branch,
3278
so it should not run its hooks.
3280
bound_location = self.target.get_bound_location()
3281
if local and not bound_location:
3282
raise errors.LocalRequiresBoundBranch()
3283
master_branch = None
3284
source_is_master = False
3286
# bound_location comes from a config file, some care has to be
3287
# taken to relate it to source.user_url
3288
normalized = urlutils.normalize_url(bound_location)
3290
relpath = self.source.user_transport.relpath(normalized)
3291
source_is_master = (relpath == '')
3292
except (errors.PathNotChild, errors.InvalidURL):
3293
source_is_master = False
3294
if not local and bound_location and not source_is_master:
3295
# not pulling from master, so we need to update master.
3296
master_branch = self.target.get_master_branch(possible_transports)
3297
master_branch.lock_write()
3300
# pull from source into master.
3301
master_branch.pull(self.source, overwrite, stop_revision,
3303
return self._pull(overwrite,
3304
stop_revision, _hook_master=master_branch,
3305
run_hooks=run_hooks,
3306
_override_hook_target=_override_hook_target,
3307
merge_tags_to_master=not source_is_master)
3310
master_branch.unlock()
3312
def push(self, overwrite=False, stop_revision=None, lossy=False,
3313
_override_hook_source_branch=None):
3314
"""See InterBranch.push.
3316
This is the basic concrete implementation of push()
3318
:param _override_hook_source_branch: If specified, run the hooks
3319
passing this Branch as the source, rather than self. This is for
3320
use of RemoteBranch, where push is delegated to the underlying
3324
raise errors.LossyPushToSameVCS(self.source, self.target)
3325
# TODO: Public option to disable running hooks - should be trivial but
3328
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3329
op.add_cleanup(self.source.lock_read().unlock)
3330
op.add_cleanup(self.target.lock_write().unlock)
3331
return op.run(overwrite, stop_revision,
3332
_override_hook_source_branch=_override_hook_source_branch)
3334
def _basic_push(self, overwrite, stop_revision):
3335
"""Basic implementation of push without bound branches or hooks.
3337
Must be called with source read locked and target write locked.
3339
result = BranchPushResult()
3340
result.source_branch = self.source
3341
result.target_branch = self.target
3342
result.old_revno, result.old_revid = self.target.last_revision_info()
3343
self.source.update_references(self.target)
3344
overwrite = _fix_overwrite_type(overwrite)
3345
if result.old_revid != stop_revision:
3346
# We assume that during 'push' this repository is closer than
3348
graph = self.source.repository.get_graph(self.target.repository)
3349
self._update_revisions(stop_revision,
3350
overwrite=("history" in overwrite),
3352
if self.source._push_should_merge_tags():
3353
result.tag_updates, result.tag_conflicts = (
3354
self.source.tags.merge_to(
3355
self.target.tags, "tags" in overwrite))
3356
result.new_revno, result.new_revid = self.target.last_revision_info()
3359
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3360
_override_hook_source_branch=None):
3361
"""Push from source into target, and into target's master if any.
3364
if _override_hook_source_branch:
3365
result.source_branch = _override_hook_source_branch
3366
for hook in Branch.hooks['post_push']:
3369
bound_location = self.target.get_bound_location()
3370
if bound_location and self.target.base != bound_location:
3371
# there is a master branch.
3373
# XXX: Why the second check? Is it even supported for a branch to
3374
# be bound to itself? -- mbp 20070507
3375
master_branch = self.target.get_master_branch()
3376
master_branch.lock_write()
3377
operation.add_cleanup(master_branch.unlock)
3378
# push into the master from the source branch.
3379
master_inter = InterBranch.get(self.source, master_branch)
3380
master_inter._basic_push(overwrite, stop_revision)
3381
# and push into the target branch from the source. Note that
3382
# we push from the source branch again, because it's considered
3383
# the highest bandwidth repository.
3384
result = self._basic_push(overwrite, stop_revision)
3385
result.master_branch = master_branch
3386
result.local_branch = self.target
3388
master_branch = None
3390
result = self._basic_push(overwrite, stop_revision)
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,
3280
3400
possible_transports=None, _hook_master=None, run_hooks=True,
3281
_override_hook_target=None, local=False):
3401
_override_hook_target=None, local=False,
3402
merge_tags_to_master=True):
3282
3403
"""See Branch.pull.
3405
This function is the core worker, used by GenericInterBranch.pull to
3406
avoid duplication when pulling source->master and source->local.
3284
3408
:param _hook_master: Private parameter - set the branch to
3285
3409
be supplied as the master to pull hooks.
3286
3410
:param run_hooks: Private parameter - if false, this branch
3287
3411
is being called because it's the master of the primary branch,
3288
3412
so it should not run its hooks.
3413
is being called because it's the master of the primary branch,
3414
so it should not run its hooks.
3289
3415
:param _override_hook_target: Private parameter - set the branch to be
3290
3416
supplied as the target_branch to pull hooks.
3291
3417
:param local: Only update the local branch, and not the bound branch.
3331
3461
self.source.unlock()
3334
def push(self, overwrite=False, stop_revision=None,
3335
_override_hook_source_branch=None):
3336
"""See InterBranch.push.
3338
This is the basic concrete implementation of push()
3340
:param _override_hook_source_branch: If specified, run
3341
the hooks passing this Branch as the source, rather than self.
3342
This is for use of RemoteBranch, where push is delegated to the
3343
underlying vfs-based Branch.
3345
# TODO: Public option to disable running hooks - should be trivial but
3347
self.source.lock_read()
3349
return _run_with_write_locked_target(
3350
self.target, self._push_with_bound_branches, overwrite,
3352
_override_hook_source_branch=_override_hook_source_branch)
3354
self.source.unlock()
3356
def _push_with_bound_branches(self, overwrite, stop_revision,
3357
_override_hook_source_branch=None):
3358
"""Push from source into target, and into target's master if any.
3361
if _override_hook_source_branch:
3362
result.source_branch = _override_hook_source_branch
3363
for hook in Branch.hooks['post_push']:
3366
bound_location = self.target.get_bound_location()
3367
if bound_location and self.target.base != bound_location:
3368
# there is a master branch.
3370
# XXX: Why the second check? Is it even supported for a branch to
3371
# be bound to itself? -- mbp 20070507
3372
master_branch = self.target.get_master_branch()
3373
master_branch.lock_write()
3375
# push into the master from the source branch.
3376
self.source._basic_push(master_branch, overwrite, stop_revision)
3377
# and push into the target branch from the source. Note that we
3378
# push from the source branch again, because its considered the
3379
# highest bandwidth repository.
3380
result = self.source._basic_push(self.target, overwrite,
3382
result.master_branch = master_branch
3383
result.local_branch = self.target
3387
master_branch.unlock()
3390
result = self.source._basic_push(self.target, overwrite,
3392
# TODO: Why set master_branch and local_branch if there's no
3393
# binding? Maybe cleaner to just leave them unset? -- mbp
3395
result.master_branch = self.target
3396
result.local_branch = None
3401
def is_compatible(self, source, target):
3402
# GenericBranch uses the public API, so always compatible
3406
class InterToBranch5(GenericInterBranch):
3409
def _get_branch_formats_to_test():
3410
return BranchFormat._default_format, BzrBranchFormat5()
3412
def pull(self, overwrite=False, stop_revision=None,
3413
possible_transports=None, run_hooks=True,
3414
_override_hook_target=None, local=False):
3415
"""Pull from source into self, updating my master if any.
3417
:param run_hooks: Private parameter - if false, this branch
3418
is being called because it's the master of the primary branch,
3419
so it should not run its hooks.
3421
bound_location = self.target.get_bound_location()
3422
if local and not bound_location:
3423
raise errors.LocalRequiresBoundBranch()
3424
master_branch = None
3425
if not local and bound_location and self.source.user_url != bound_location:
3426
# not pulling from master, so we need to update master.
3427
master_branch = self.target.get_master_branch(possible_transports)
3428
master_branch.lock_write()
3431
# pull from source into master.
3432
master_branch.pull(self.source, overwrite, stop_revision,
3434
return super(InterToBranch5, self).pull(overwrite,
3435
stop_revision, _hook_master=master_branch,
3436
run_hooks=run_hooks,
3437
_override_hook_target=_override_hook_target)
3440
master_branch.unlock()
3443
3465
InterBranch.register_optimiser(GenericInterBranch)
3444
InterBranch.register_optimiser(InterToBranch5)