920
969
"""Return last revision id, or NULL_REVISION."""
921
970
return self.last_revision_info()[1]
924
972
def last_revision_info(self):
925
973
"""Return information about the last revision.
927
975
: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):
977
with self.lock_read():
978
if self._last_revision_info_cache is None:
979
self._last_revision_info_cache = self._read_last_revision_info()
980
return self._last_revision_info_cache
982
def _read_last_revision_info(self):
983
raise NotImplementedError(self._read_last_revision_info)
985
def import_last_revision_info_and_tags(self, source, revno, revid,
981
987
"""Set the last revision info, importing from another repo if necessary.
983
989
This is used by the bound branch code to upload a revision to
984
990
the master branch first before updating the tip of the local branch.
991
Revisions referenced by source's tags are also transferred.
986
:param source_repo: Source repository to optionally fetch from
993
:param source: Source branch to optionally fetch from
987
994
:param revno: Revision number of the new tip
988
995
:param revid: Revision id of the new tip
996
:param lossy: Whether to discard metadata that can not be
998
:return: Tuple with the new revision number and revision id
999
(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)
1001
if not self.repository.has_same_location(source.repository):
1002
self.fetch(source, revid)
992
1003
self.set_last_revision_info(revno, revid)
1004
return (revno, revid)
994
1006
def revision_id_to_revno(self, revision_id):
995
1007
"""Given a revision id, return its revno"""
996
1008
if _mod_revision.is_null(revision_id):
998
history = self.revision_history()
1010
history = self._revision_history()
1000
1012
return history.index(revision_id) + 1
1001
1013
except ValueError:
1002
1014
raise errors.NoSuchRevision(self, revision_id)
1005
1016
def get_rev_id(self, revno, history=None):
1006
1017
"""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]
1018
with self.lock_read():
1020
return _mod_revision.NULL_REVISION
1021
last_revno, last_revid = self.last_revision_info()
1022
if revno == last_revno:
1024
if revno <= 0 or revno > last_revno:
1025
raise errors.NoSuchRevision(self, revno)
1026
distance_from_last = last_revno - revno
1027
if len(self._partial_revision_history_cache) <= distance_from_last:
1028
self._extend_partial_history(distance_from_last)
1029
return self._partial_revision_history_cache[distance_from_last]
1020
1031
def pull(self, source, overwrite=False, stop_revision=None,
1021
1032
possible_transports=None, *args, **kwargs):
1022
1033
"""Mirror source into this branch.
1914
1848
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)
1851
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1852
"""Branch format registry."""
1854
def __init__(self, other_registry=None):
1855
super(BranchFormatRegistry, self).__init__(other_registry)
1856
self._default_format = None
1857
self._default_format_key = None
1859
def get_default(self):
1860
"""Return the current default format."""
1861
if (self._default_format_key is not None and
1862
self._default_format is None):
1863
self._default_format = self.get(self._default_format_key)
1864
return self._default_format
1866
def set_default(self, format):
1867
"""Set the default format."""
1868
self._default_format = format
1869
self._default_format_key = None
1871
def set_default_key(self, format_string):
1872
"""Set the default format by its format string."""
1873
self._default_format_key = format_string
1874
self._default_format = None
2251
1877
network_format_registry = registry.FormatRegistry()
2256
1882
BranchFormat.network_name() for more detail.
1885
format_registry = BranchFormatRegistry(network_format_registry)
2260
1888
# formats which have no format string are not discoverable
2261
1889
# 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__)
1890
format_registry.register_lazy(
1891
b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1893
format_registry.register_lazy(
1894
b"Bazaar Branch Format 6 (bzr 0.15)\n",
1895
"breezy.bzr.branch", "BzrBranchFormat6")
1896
format_registry.register_lazy(
1897
b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1898
"breezy.bzr.branch", "BzrBranchFormat7")
1899
format_registry.register_lazy(
1900
b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1901
"breezy.bzr.branch", "BzrBranchFormat8")
1902
format_registry.register_lazy(
1903
b"Bazaar-NG Branch Reference Format 1\n",
1904
"breezy.bzr.branch", "BranchReferenceFormat")
1906
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
2278
1909
class BranchWriteLockResult(LogicalLockResult):
2279
1910
"""The result of write locking a branch.
2281
:ivar branch_token: The token obtained from the underlying branch lock, or
1912
:ivar token: The token obtained from the underlying branch lock, or
2283
1914
: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
1917
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)
1918
return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
2996
1921
######################################################################
3269
2182
[(other_last_revision, other_revno),
3270
2183
(this_last_revision, this_revno)])
3271
2184
self.target.set_last_revision_info(stop_revno, stop_revision)
3273
self.source.unlock()
3275
2186
def pull(self, overwrite=False, stop_revision=None,
2187
possible_transports=None, run_hooks=True,
2188
_override_hook_target=None, local=False):
2189
"""Pull from source into self, updating my master if any.
2191
:param run_hooks: Private parameter - if false, this branch
2192
is being called because it's the master of the primary branch,
2193
so it should not run its hooks.
2195
with self.target.lock_write():
2196
bound_location = self.target.get_bound_location()
2197
if local and not bound_location:
2198
raise errors.LocalRequiresBoundBranch()
2199
master_branch = None
2200
source_is_master = False
2202
# bound_location comes from a config file, some care has to be
2203
# taken to relate it to source.user_url
2204
normalized = urlutils.normalize_url(bound_location)
2206
relpath = self.source.user_transport.relpath(normalized)
2207
source_is_master = (relpath == '')
2208
except (errors.PathNotChild, urlutils.InvalidURL):
2209
source_is_master = False
2210
if not local and bound_location and not source_is_master:
2211
# not pulling from master, so we need to update master.
2212
master_branch = self.target.get_master_branch(possible_transports)
2213
master_branch.lock_write()
2216
# pull from source into master.
2217
master_branch.pull(self.source, overwrite, stop_revision,
2219
return self._pull(overwrite,
2220
stop_revision, _hook_master=master_branch,
2221
run_hooks=run_hooks,
2222
_override_hook_target=_override_hook_target,
2223
merge_tags_to_master=not source_is_master)
2226
master_branch.unlock()
2228
def push(self, overwrite=False, stop_revision=None, lossy=False,
2229
_override_hook_source_branch=None):
2230
"""See InterBranch.push.
2232
This is the basic concrete implementation of push()
2234
:param _override_hook_source_branch: If specified, run the hooks
2235
passing this Branch as the source, rather than self. This is for
2236
use of RemoteBranch, where push is delegated to the underlying
2240
raise errors.LossyPushToSameVCS(self.source, self.target)
2241
# TODO: Public option to disable running hooks - should be trivial but
2244
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
2245
op.add_cleanup(self.source.lock_read().unlock)
2246
op.add_cleanup(self.target.lock_write().unlock)
2247
return op.run(overwrite, stop_revision,
2248
_override_hook_source_branch=_override_hook_source_branch)
2250
def _basic_push(self, overwrite, stop_revision):
2251
"""Basic implementation of push without bound branches or hooks.
2253
Must be called with source read locked and target write locked.
2255
result = BranchPushResult()
2256
result.source_branch = self.source
2257
result.target_branch = self.target
2258
result.old_revno, result.old_revid = self.target.last_revision_info()
2259
self.source.update_references(self.target)
2260
overwrite = _fix_overwrite_type(overwrite)
2261
if result.old_revid != stop_revision:
2262
# We assume that during 'push' this repository is closer than
2264
graph = self.source.repository.get_graph(self.target.repository)
2265
self._update_revisions(stop_revision,
2266
overwrite=("history" in overwrite),
2268
if self.source._push_should_merge_tags():
2269
result.tag_updates, result.tag_conflicts = (
2270
self.source.tags.merge_to(
2271
self.target.tags, "tags" in overwrite))
2272
result.new_revno, result.new_revid = self.target.last_revision_info()
2275
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
2276
_override_hook_source_branch=None):
2277
"""Push from source into target, and into target's master if any.
2280
if _override_hook_source_branch:
2281
result.source_branch = _override_hook_source_branch
2282
for hook in Branch.hooks['post_push']:
2285
bound_location = self.target.get_bound_location()
2286
if bound_location and self.target.base != bound_location:
2287
# there is a master branch.
2289
# XXX: Why the second check? Is it even supported for a branch to
2290
# be bound to itself? -- mbp 20070507
2291
master_branch = self.target.get_master_branch()
2292
master_branch.lock_write()
2293
operation.add_cleanup(master_branch.unlock)
2294
# push into the master from the source branch.
2295
master_inter = InterBranch.get(self.source, master_branch)
2296
master_inter._basic_push(overwrite, stop_revision)
2297
# and push into the target branch from the source. Note that
2298
# we push from the source branch again, because it's considered
2299
# the highest bandwidth repository.
2300
result = self._basic_push(overwrite, stop_revision)
2301
result.master_branch = master_branch
2302
result.local_branch = self.target
2304
master_branch = None
2306
result = self._basic_push(overwrite, stop_revision)
2307
# TODO: Why set master_branch and local_branch if there's no
2308
# binding? Maybe cleaner to just leave them unset? -- mbp
2310
result.master_branch = self.target
2311
result.local_branch = None
2315
def _pull(self, overwrite=False, stop_revision=None,
3276
2316
possible_transports=None, _hook_master=None, run_hooks=True,
3277
_override_hook_target=None, local=False):
2317
_override_hook_target=None, local=False,
2318
merge_tags_to_master=True):
3278
2319
"""See Branch.pull.
2321
This function is the core worker, used by GenericInterBranch.pull to
2322
avoid duplication when pulling source->master and source->local.
3280
2324
:param _hook_master: Private parameter - set the branch to
3281
2325
be supplied as the master to pull hooks.
3282
2326
:param run_hooks: Private parameter - if false, this branch
3283
2327
is being called because it's the master of the primary branch,
3284
2328
so it should not run its hooks.
2329
is being called because it's the master of the primary branch,
2330
so it should not run its hooks.
3285
2331
:param _override_hook_target: Private parameter - set the branch to be
3286
2332
supplied as the target_branch to pull hooks.
3287
2333
:param local: Only update the local branch, and not the bound branch.