46
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
50
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
51
HistoryMissing, InvalidRevisionId,
52
InvalidRevisionNumber, LockError, NoSuchFile,
53
NoSuchRevision, NotVersionedError,
54
NotBranchError, UninitializableFormat,
55
UnlistableStore, UnlistableBranch,
47
57
from bzrlib.hooks import Hooks
48
from bzrlib.symbol_versioning import (
52
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
58
from bzrlib.symbol_versioning import (deprecated_function,
62
zero_eight, zero_nine, zero_sixteen,
65
from bzrlib.trace import mutter, mutter_callsite, note
55
68
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
328
335
The delta is relative to its mainline predecessor, or the
329
336
empty tree for revision 1.
338
assert isinstance(revno, int)
331
339
rh = self.revision_history()
332
340
if not (1 <= revno <= len(rh)):
333
raise errors.InvalidRevisionNumber(revno)
341
raise InvalidRevisionNumber(revno)
334
342
return self.repository.get_revision_delta(rh[revno-1])
336
def get_stacked_on_url(self):
337
"""Get the URL this branch is stacked against.
344
@deprecated_method(zero_sixteen)
345
def get_root_id(self):
346
"""Return the id of this branches root
339
:raises NotStacked: If the branch is not stacked.
340
:raises UnstackableBranchFormat: If the branch does not support
348
Deprecated: branches don't have root ids-- trees do.
349
Use basis_tree().get_root_id() instead.
343
raise NotImplementedError(self.get_stacked_on_url)
351
raise NotImplementedError(self.get_root_id)
345
353
def print_file(self, file, revision_id):
346
354
"""Print `file` to stdout."""
474
468
common_index = min(self_len, other_len) -1
475
469
if common_index >= 0 and \
476
470
self_history[common_index] != other_history[common_index]:
477
raise errors.DivergedBranches(self, other)
471
raise DivergedBranches(self, other)
479
473
if stop_revision is None:
480
474
stop_revision = other_len
476
assert isinstance(stop_revision, int)
482
477
if stop_revision > other_len:
483
478
raise errors.NoSuchRevision(self, stop_revision)
484
479
return other_history[self_len:stop_revision]
487
def update_revisions(self, other, stop_revision=None, overwrite=False,
481
def update_revisions(self, other, stop_revision=None):
489
482
"""Pull in new perfect-fit revisions.
491
484
:param other: Another Branch to pull from
492
485
:param stop_revision: Updated until the given revision
493
:param overwrite: Always set the branch pointer, rather than checking
494
to see if it is a proper descendant.
495
:param graph: A Graph object that can be used to query history
496
information. This can be None.
501
other_revno, other_last_revision = other.last_revision_info()
502
stop_revno = None # unknown
503
if stop_revision is None:
504
stop_revision = other_last_revision
505
if _mod_revision.is_null(stop_revision):
506
# if there are no commits, we're done.
508
stop_revno = other_revno
510
# what's the current last revision, before we fetch [and change it
512
last_rev = _mod_revision.ensure_null(self.last_revision())
513
# we fetch here so that we don't process data twice in the common
514
# case of having something to pull, and so that the check for
515
# already merged can operate on the just fetched graph, which will
516
# be cached in memory.
517
self.fetch(other, stop_revision)
518
# Check to see if one is an ancestor of the other
521
graph = self.repository.get_graph()
522
if self._check_if_descendant_or_diverged(
523
stop_revision, last_rev, graph, other):
524
# stop_revision is a descendant of last_rev, but we aren't
525
# overwriting, so we're done.
527
if stop_revno is None:
529
graph = self.repository.get_graph()
530
this_revno, this_last_revision = self.last_revision_info()
531
stop_revno = graph.find_distance_to_null(stop_revision,
532
[(other_last_revision, other_revno),
533
(this_last_revision, this_revno)])
534
self.set_last_revision_info(stop_revno, stop_revision)
488
raise NotImplementedError(self.update_revisions)
538
490
def revision_id_to_revno(self, revision_id):
539
491
"""Given a revision id, return its revno"""
882
808
def supports_tags(self):
883
809
return self._format.supports_tags()
885
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
887
"""Ensure that revision_b is a descendant of revision_a.
889
This is a helper function for update_revisions.
891
:raises: DivergedBranches if revision_b has diverged from revision_a.
892
:returns: True if revision_b is a descendant of revision_a.
894
relation = self._revision_relations(revision_a, revision_b, graph)
895
if relation == 'b_descends_from_a':
897
elif relation == 'diverged':
898
raise errors.DivergedBranches(self, other_branch)
899
elif relation == 'a_descends_from_b':
902
raise AssertionError("invalid relation: %r" % (relation,))
904
def _revision_relations(self, revision_a, revision_b, graph):
905
"""Determine the relationship between two revisions.
907
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
909
heads = graph.heads([revision_a, revision_b])
910
if heads == set([revision_b]):
911
return 'b_descends_from_a'
912
elif heads == set([revision_a, revision_b]):
913
# These branches have diverged
915
elif heads == set([revision_a]):
916
return 'a_descends_from_b'
918
raise AssertionError("invalid heads: %r" % (heads,))
921
812
class BranchFormat(object):
922
813
"""An encapsulation of the initialization and open routines for a format.
1138
1038
# local is the local branch or None, master is the target branch,
1139
1039
# and an empty branch recieves new_revno of 0, new_revid of None.
1140
1040
self['post_uncommit'] = []
1142
# Invoked before the tip of a branch changes.
1143
# the api signature is
1144
# (params) where params is a ChangeBranchTipParams with the members
1145
# (branch, old_revno, new_revno, old_revid, new_revid)
1146
self['pre_change_branch_tip'] = []
1148
# Invoked after the tip of a branch changes.
1149
# the api signature is
1150
# (params) where params is a ChangeBranchTipParams with the members
1151
# (branch, old_revno, new_revno, old_revid, new_revid)
1152
self['post_change_branch_tip'] = []
1155
1043
# install the default hooks into the Branch class.
1156
1044
Branch.hooks = BranchHooks()
1159
class ChangeBranchTipParams(object):
1160
"""Object holding parameters passed to *_change_branch_tip hooks.
1162
There are 5 fields that hooks may wish to access:
1164
:ivar branch: the branch being changed
1165
:ivar old_revno: revision number before the change
1166
:ivar new_revno: revision number after the change
1167
:ivar old_revid: revision id before the change
1168
:ivar new_revid: revision id after the change
1170
The revid fields are strings. The revno fields are integers.
1173
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1174
"""Create a group of ChangeBranchTip parameters.
1176
:param branch: The branch being changed.
1177
:param old_revno: Revision number before the change.
1178
:param new_revno: Revision number after the change.
1179
:param old_revid: Tip revision id before the change.
1180
:param new_revid: Tip revision id after the change.
1182
self.branch = branch
1183
self.old_revno = old_revno
1184
self.new_revno = new_revno
1185
self.old_revid = old_revid
1186
self.new_revid = new_revid
1188
def __eq__(self, other):
1189
return self.__dict__ == other.__dict__
1192
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1193
self.__class__.__name__, self.branch,
1194
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1197
1047
class BzrBranchFormat4(BranchFormat):
1198
1048
"""Bzr branch format 4.
1236
1086
return "Bazaar-NG branch format 4"
1239
class BranchFormatMetadir(BranchFormat):
1240
"""Common logic for meta-dir based branch formats."""
1242
def _branch_class(self):
1243
"""What class to instantiate on open calls."""
1244
raise NotImplementedError(self._branch_class)
1089
class BzrBranchFormat5(BranchFormat):
1090
"""Bzr branch format 5.
1093
- a revision-history file.
1095
- a lock dir guarding the branch itself
1096
- all of this stored in a branch/ subdirectory
1097
- works with shared repositories.
1099
This format is new in bzr 0.8.
1102
def get_format_string(self):
1103
"""See BranchFormat.get_format_string()."""
1104
return "Bazaar-NG branch format 5\n"
1106
def get_format_description(self):
1107
"""See BranchFormat.get_format_description()."""
1108
return "Branch format 5"
1110
def initialize(self, a_bzrdir):
1111
"""Create a branch of this format in a_bzrdir."""
1112
utf8_files = [('revision-history', ''),
1113
('branch-name', ''),
1115
return self._initialize_helper(a_bzrdir, utf8_files)
1118
super(BzrBranchFormat5, self).__init__()
1119
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1246
1121
def open(self, a_bzrdir, _found=False):
1247
"""Return the branch object for a_bzrdir.
1122
"""Return the branch object for a_bzrdir
1249
1124
_found is a private parameter, do not use it. It is used to indicate
1250
1125
if format probing has already be done.
1253
1128
format = BranchFormat.find_format(a_bzrdir)
1254
if format.__class__ != self.__class__:
1255
raise AssertionError("wrong format %r found for %r" %
1129
assert format.__class__ == self.__class__
1258
1131
transport = a_bzrdir.get_branch_transport(None)
1259
1132
control_files = lockable_files.LockableFiles(transport, 'lock',
1260
1133
lockdir.LockDir)
1261
return self._branch_class()(_format=self,
1134
return BzrBranch5(_format=self,
1262
1135
_control_files=control_files,
1263
1136
a_bzrdir=a_bzrdir,
1264
1137
_repository=a_bzrdir.find_repository())
1265
except errors.NoSuchFile:
1266
raise errors.NotBranchError(path=transport.base)
1269
super(BranchFormatMetadir, self).__init__()
1270
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1272
def supports_tags(self):
1276
class BzrBranchFormat5(BranchFormatMetadir):
1277
"""Bzr branch format 5.
1280
- a revision-history file.
1282
- a lock dir guarding the branch itself
1283
- all of this stored in a branch/ subdirectory
1284
- works with shared repositories.
1286
This format is new in bzr 0.8.
1289
def _branch_class(self):
1292
def get_format_string(self):
1293
"""See BranchFormat.get_format_string()."""
1294
return "Bazaar-NG branch format 5\n"
1296
def get_format_description(self):
1297
"""See BranchFormat.get_format_description()."""
1298
return "Branch format 5"
1300
def initialize(self, a_bzrdir):
1301
"""Create a branch of this format in a_bzrdir."""
1302
utf8_files = [('revision-history', ''),
1303
('branch-name', ''),
1305
return self._initialize_helper(a_bzrdir, utf8_files)
1307
def supports_tags(self):
1311
class BzrBranchFormat6(BranchFormatMetadir):
1139
raise NotBranchError(path=transport.base)
1142
class BzrBranchFormat6(BzrBranchFormat5):
1312
1143
"""Branch format with last-revision and tags.
1314
1145
Unlike previous formats, this has no explicit revision history. Instead,
1339
1167
return self._initialize_helper(a_bzrdir, utf8_files)
1342
class BzrBranchFormat7(BranchFormatMetadir):
1343
"""Branch format with last-revision, tags, and a stacked location pointer.
1345
The stacked location pointer is passed down to the repository and requires
1346
a repository format with supports_external_lookups = True.
1348
This format was introduced in bzr 1.6.
1351
def _branch_class(self):
1354
def get_format_string(self):
1355
"""See BranchFormat.get_format_string()."""
1356
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1358
def get_format_description(self):
1359
"""See BranchFormat.get_format_description()."""
1360
return "Branch format 7"
1362
def initialize(self, a_bzrdir):
1363
"""Create a branch of this format in a_bzrdir."""
1364
utf8_files = [('last-revision', '0 null:\n'),
1365
('branch.conf', ''),
1368
return self._initialize_helper(a_bzrdir, utf8_files)
1371
super(BzrBranchFormat7, self).__init__()
1372
self._matchingbzrdir.repository_format = \
1373
RepositoryFormatPackDevelopment1Subtree()
1375
def supports_stacking(self):
1169
def open(self, a_bzrdir, _found=False):
1170
"""Return the branch object for a_bzrdir
1172
_found is a private parameter, do not use it. It is used to indicate
1173
if format probing has already be done.
1176
format = BranchFormat.find_format(a_bzrdir)
1177
assert format.__class__ == self.__class__
1178
transport = a_bzrdir.get_branch_transport(None)
1179
control_files = lockable_files.LockableFiles(transport, 'lock',
1181
return BzrBranch6(_format=self,
1182
_control_files=control_files,
1184
_repository=a_bzrdir.find_repository())
1186
def supports_tags(self):
1482
1289
Note that it's "local" in the context of the filesystem; it doesn't
1483
1290
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1484
1291
it's writable, and can be accessed via the normal filesystem API.
1486
:ivar _transport: Transport for file operations on this branch's
1487
control files, typically pointing to the .bzr/branch directory.
1488
:ivar repository: Repository for this branch.
1489
:ivar base: The url of the base directory for this branch; the one
1490
containing the .bzr directory.
1493
1294
def __init__(self, _format=None,
1494
1295
_control_files=None, a_bzrdir=None, _repository=None):
1495
1296
"""Create new branch object at a particular location."""
1297
Branch.__init__(self)
1496
1298
if a_bzrdir is None:
1497
1299
raise ValueError('a_bzrdir must be supplied')
1499
1301
self.bzrdir = a_bzrdir
1302
# self._transport used to point to the directory containing the
1303
# control directory, but was not used - now it's just the transport
1304
# for the branch control files. mbp 20070212
1500
1305
self._base = self.bzrdir.transport.clone('..').base
1501
# XXX: We should be able to just do
1502
# self.base = self.bzrdir.root_transport.base
1503
# but this does not quite work yet -- mbp 20080522
1504
1306
self._format = _format
1505
1307
if _control_files is None:
1506
1308
raise ValueError('BzrBranch _control_files is None')
1507
1309
self.control_files = _control_files
1508
1310
self._transport = _control_files._transport
1509
1311
self.repository = _repository
1510
Branch.__init__(self)
1512
1313
def __str__(self):
1513
1314
return '%s(%r)' % (self.__class__.__name__, self.base)
1575
1383
This performs the actual writing to disk.
1576
1384
It is intended to be called by BzrBranch5.set_revision_history."""
1577
self._transport.put_bytes(
1578
'revision-history', '\n'.join(history),
1579
mode=self.bzrdir._get_file_mode())
1385
self.control_files.put_bytes(
1386
'revision-history', '\n'.join(history))
1581
1388
@needs_write_lock
1582
1389
def set_revision_history(self, rev_history):
1583
1390
"""See Branch.set_revision_history."""
1584
1391
if 'evil' in debug.debug_flags:
1585
1392
mutter_callsite(3, "set_revision_history scales with history.")
1586
check_not_reserved_id = _mod_revision.check_not_reserved_id
1587
for rev_id in rev_history:
1588
check_not_reserved_id(rev_id)
1589
if Branch.hooks['post_change_branch_tip']:
1590
# Don't calculate the last_revision_info() if there are no hooks
1592
old_revno, old_revid = self.last_revision_info()
1593
if len(rev_history) == 0:
1594
revid = _mod_revision.NULL_REVISION
1596
revid = rev_history[-1]
1597
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1393
self._clear_cached_state()
1598
1394
self._write_revision_history(rev_history)
1599
self._clear_cached_state()
1600
1395
self._cache_revision_history(rev_history)
1601
1396
for hook in Branch.hooks['set_rh']:
1602
1397
hook(self, rev_history)
1603
if Branch.hooks['post_change_branch_tip']:
1604
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1606
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1607
"""Run the pre_change_branch_tip hooks."""
1608
hooks = Branch.hooks['pre_change_branch_tip']
1611
old_revno, old_revid = self.last_revision_info()
1612
params = ChangeBranchTipParams(
1613
self, old_revno, new_revno, old_revid, new_revid)
1617
except errors.TipChangeRejected:
1620
exc_info = sys.exc_info()
1621
hook_name = Branch.hooks.get_hook_name(hook)
1622
raise errors.HookFailed(
1623
'pre_change_branch_tip', hook_name, exc_info)
1625
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1626
"""Run the post_change_branch_tip hooks."""
1627
hooks = Branch.hooks['post_change_branch_tip']
1630
new_revno, new_revid = self.last_revision_info()
1631
params = ChangeBranchTipParams(
1632
self, old_revno, new_revno, old_revid, new_revid)
1636
1399
@needs_write_lock
1637
1400
def set_last_revision_info(self, revno, revision_id):
1638
1401
"""Set the last revision of this branch.
1666
1424
if 'evil' in debug.debug_flags:
1667
1425
mutter_callsite(4, "_lefthand_history scales with history.")
1668
1426
# stop_revision must be a descendant of last_revision
1669
graph = self.repository.get_graph()
1670
if last_rev is not None:
1671
if not graph.is_ancestor(last_rev, revision_id):
1672
# our previous tip is not merged into stop_revision
1673
raise errors.DivergedBranches(self, other_branch)
1427
stop_graph = self.repository.get_revision_graph(revision_id)
1428
if (last_rev is not None and last_rev != _mod_revision.NULL_REVISION
1429
and last_rev not in stop_graph):
1430
# our previous tip is not merged into stop_revision
1431
raise errors.DivergedBranches(self, other_branch)
1674
1432
# make a new revision history from the graph
1675
parents_map = graph.get_parent_map([revision_id])
1676
if revision_id not in parents_map:
1677
raise errors.NoSuchRevision(self, revision_id)
1678
1433
current_rev_id = revision_id
1679
1434
new_history = []
1680
check_not_reserved_id = _mod_revision.check_not_reserved_id
1681
# Do not include ghosts or graph origin in revision_history
1682
while (current_rev_id in parents_map and
1683
len(parents_map[current_rev_id]) > 0):
1684
check_not_reserved_id(current_rev_id)
1435
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1685
1436
new_history.append(current_rev_id)
1686
current_rev_id = parents_map[current_rev_id][0]
1687
parents_map = graph.get_parent_map([current_rev_id])
1437
current_rev_id_parents = stop_graph[current_rev_id]
1439
current_rev_id = current_rev_id_parents[0]
1441
current_rev_id = None
1688
1442
new_history.reverse()
1689
1443
return new_history
1702
1456
self.set_revision_history(self._lefthand_history(revision_id,
1703
1457
last_rev, other_branch))
1460
def update_revisions(self, other, stop_revision=None, overwrite=False):
1461
"""See Branch.update_revisions."""
1464
other_last_revno, other_last_revision = other.last_revision_info()
1465
if stop_revision is None:
1466
stop_revision = other_last_revision
1467
if _mod_revision.is_null(stop_revision):
1468
# if there are no commits, we're done.
1470
# whats the current last revision, before we fetch [and change it
1472
last_rev = _mod_revision.ensure_null(self.last_revision())
1473
# we fetch here so that we don't process data twice in the common
1474
# case of having something to pull, and so that the check for
1475
# already merged can operate on the just fetched graph, which will
1476
# be cached in memory.
1477
self.fetch(other, stop_revision)
1478
# Check to see if one is an ancestor of the other
1480
heads = self.repository.get_graph().heads([stop_revision,
1482
if heads == set([last_rev]):
1483
# The current revision is a decendent of the target,
1486
elif heads == set([stop_revision, last_rev]):
1487
# These branches have diverged
1488
raise errors.DivergedBranches(self, other)
1489
assert heads == set([stop_revision])
1490
if other_last_revision == stop_revision:
1491
self.set_last_revision_info(other_last_revno,
1492
other_last_revision)
1494
# TODO: jam 2007-11-29 Is there a way to determine the
1495
# revno without searching all of history??
1497
self.generate_revision_history(stop_revision)
1499
self.generate_revision_history(stop_revision,
1500
last_rev=last_rev, other_branch=other)
1705
1504
def basis_tree(self):
1706
1505
"""See Branch.basis_tree."""
1707
1506
return self.repository.revision_tree(self.last_revision())
1709
1508
@needs_write_lock
1710
1509
def pull(self, source, overwrite=False, stop_revision=None,
1711
_hook_master=None, run_hooks=True, possible_transports=None,
1712
_override_hook_target=None):
1510
_hook_master=None, run_hooks=True, possible_transports=None):
1713
1511
"""See Branch.pull.
1715
1513
:param _hook_master: Private parameter - set the branch to
1716
be supplied as the master to pull hooks.
1514
be supplied as the master to push hooks.
1717
1515
:param run_hooks: Private parameter - if false, this branch
1718
1516
is being called because it's the master of the primary branch,
1719
1517
so it should not run its hooks.
1720
:param _override_hook_target: Private parameter - set the branch to be
1721
supplied as the target_branch to pull hooks.
1723
1519
result = PullResult()
1724
1520
result.source_branch = source
1725
if _override_hook_target is None:
1726
result.target_branch = self
1728
result.target_branch = _override_hook_target
1521
result.target_branch = self
1729
1522
source.lock_read()
1731
# We assume that during 'pull' the local repository is closer than
1733
graph = self.repository.get_graph(source.repository)
1734
1524
result.old_revno, result.old_revid = self.last_revision_info()
1735
self.update_revisions(source, stop_revision, overwrite=overwrite,
1525
self.update_revisions(source, stop_revision, overwrite=overwrite)
1737
1526
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1738
1527
result.new_revno, result.new_revid = self.last_revision_info()
1739
1528
if _hook_master:
1740
1529
result.master_branch = _hook_master
1741
result.local_branch = result.target_branch
1530
result.local_branch = self
1743
result.master_branch = result.target_branch
1532
result.master_branch = self
1744
1533
result.local_branch = None
1746
1535
for hook in Branch.hooks['post_pull']:
2028
class BzrBranch7(BzrBranch5):
2029
"""A branch with support for a fallback repository."""
2031
def _get_fallback_repository(self, url):
2032
"""Get the repository we fallback to at url."""
2033
url = urlutils.join(self.base, url)
2034
return bzrdir.BzrDir.open(url).open_branch().repository
2036
def _activate_fallback_location(self, url):
2037
"""Activate the branch/repository from url as a fallback repository."""
2038
self.repository.add_fallback_repository(
2039
self._get_fallback_repository(url))
2041
def _open_hook(self):
1822
class BzrBranchExperimental(BzrBranch5):
1823
"""Bzr experimental branch format
1826
- a revision-history file.
1828
- a lock dir guarding the branch itself
1829
- all of this stored in a branch/ subdirectory
1830
- works with shared repositories.
1831
- a tag dictionary in the branch
1833
This format is new in bzr 0.15, but shouldn't be used for real data,
1836
This class acts as it's own BranchFormat.
1839
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1842
def get_format_string(cls):
1843
"""See BranchFormat.get_format_string()."""
1844
return "Bazaar-NG branch format experimental\n"
1847
def get_format_description(cls):
1848
"""See BranchFormat.get_format_description()."""
1849
return "Experimental branch format"
1852
def get_reference(cls, a_bzrdir):
1853
"""Get the target reference of the branch in a_bzrdir.
1855
format probing must have been completed before calling
1856
this method - it is assumed that the format of the branch
1857
in a_bzrdir is correct.
1859
:param a_bzrdir: The bzrdir to get the branch data from.
1860
:return: None if the branch is not a reference branch.
1865
def set_reference(self, a_bzrdir, to_branch):
1866
"""Set the target reference of the branch in a_bzrdir.
1868
format probing must have been completed before calling
1869
this method - it is assumed that the format of the branch
1870
in a_bzrdir is correct.
1872
:param a_bzrdir: The bzrdir to set the branch reference for.
1873
:param to_branch: branch that the checkout is to reference
1875
raise NotImplementedError(self.set_reference)
1878
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1880
branch_transport = a_bzrdir.get_branch_transport(cls)
1881
control_files = lockable_files.LockableFiles(branch_transport,
1882
lock_filename, lock_class)
1883
control_files.create_lock()
1884
control_files.lock_write()
2043
url = self.get_stacked_on_url()
2044
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2045
errors.UnstackableBranchFormat):
2048
self._activate_fallback_location(url)
2050
def _check_stackable_repo(self):
2051
if not self.repository._format.supports_external_lookups:
2052
raise errors.UnstackableRepositoryFormat(self.repository._format,
2053
self.repository.base)
2055
def __init__(self, *args, **kwargs):
2056
super(BzrBranch7, self).__init__(*args, **kwargs)
2057
self._last_revision_info_cache = None
2058
self._partial_revision_history_cache = []
2060
def _clear_cached_state(self):
2061
super(BzrBranch7, self)._clear_cached_state()
2062
self._last_revision_info_cache = None
2063
self._partial_revision_history_cache = []
2065
def _last_revision_info(self):
2066
revision_string = self._transport.get_bytes('last-revision')
1886
for filename, content in utf8_files:
1887
control_files.put_utf8(filename, content)
1889
control_files.unlock()
1892
def initialize(cls, a_bzrdir):
1893
"""Create a branch of this format in a_bzrdir."""
1894
utf8_files = [('format', cls.get_format_string()),
1895
('revision-history', ''),
1896
('branch-name', ''),
1899
cls._initialize_control_files(a_bzrdir, utf8_files,
1900
'lock', lockdir.LockDir)
1901
return cls.open(a_bzrdir, _found=True)
1904
def open(cls, a_bzrdir, _found=False):
1905
"""Return the branch object for a_bzrdir
1907
_found is a private parameter, do not use it. It is used to indicate
1908
if format probing has already be done.
1911
format = BranchFormat.find_format(a_bzrdir)
1912
assert format.__class__ == cls
1913
transport = a_bzrdir.get_branch_transport(None)
1914
control_files = lockable_files.LockableFiles(transport, 'lock',
1916
return cls(_format=cls,
1917
_control_files=control_files,
1919
_repository=a_bzrdir.find_repository())
1922
def is_supported(cls):
1925
def _make_tags(self):
1926
return BasicTags(self)
1929
def supports_tags(cls):
1933
BranchFormat.register_format(BzrBranchExperimental)
1936
class BzrBranch6(BzrBranch5):
1939
def last_revision_info(self):
1940
revision_string = self.control_files.get('last-revision').read()
2067
1941
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2068
1942
revision_id = cache_utf8.get_cached_utf8(revision_id)
2069
1943
revno = int(revno)
2070
1944
return revno, revision_id
1946
def last_revision(self):
1947
"""Return last revision id, or None"""
1948
revision_id = self.last_revision_info()[1]
2072
1951
def _write_last_revision_info(self, revno, revision_id):
2073
1952
"""Simply write out the revision id, with no checks.
2078
1957
Intended to be called by set_last_revision_info and
2079
1958
_write_revision_history.
2081
revision_id = _mod_revision.ensure_null(revision_id)
1960
if revision_id is None:
1961
revision_id = 'null:'
2082
1962
out_string = '%d %s\n' % (revno, revision_id)
2083
self._transport.put_bytes('last-revision', out_string,
2084
mode=self.bzrdir._get_file_mode())
1963
self.control_files.put_bytes('last-revision', out_string)
2086
1965
@needs_write_lock
2087
1966
def set_last_revision_info(self, revno, revision_id):
2088
revision_id = _mod_revision.ensure_null(revision_id)
2089
old_revno, old_revid = self.last_revision_info()
2090
1967
if self._get_append_revisions_only():
2091
1968
self._check_history_violation(revision_id)
2092
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2093
1969
self._write_last_revision_info(revno, revision_id)
2094
1970
self._clear_cached_state()
2095
self._last_revision_info_cache = revno, revision_id
2096
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2098
1972
def _check_history_violation(self, revision_id):
2099
1973
last_revision = _mod_revision.ensure_null(self.last_revision())
2105
1979
def _gen_revision_history(self):
2106
1980
"""Generate the revision history from last revision
2108
last_revno, last_revision = self.last_revision_info()
2109
self._extend_partial_history(stop_index=last_revno-1)
2110
return list(reversed(self._partial_revision_history_cache))
2112
def _extend_partial_history(self, stop_index=None, stop_revision=None):
2113
"""Extend the partial history to include a given index
2115
If a stop_index is supplied, stop when that index has been reached.
2116
If a stop_revision is supplied, stop when that revision is
2117
encountered. Otherwise, stop when the beginning of history is
2120
:param stop_index: The index which should be present. When it is
2121
present, history extension will stop.
2122
:param revision_id: The revision id which should be present. When
2123
it is encountered, history extension will stop.
2125
repo = self.repository
2126
if len(self._partial_revision_history_cache) == 0:
2127
iterator = repo.iter_reverse_revision_history(self.last_revision())
2129
start_revision = self._partial_revision_history_cache[-1]
2130
iterator = repo.iter_reverse_revision_history(start_revision)
2131
#skip the last revision in the list
2132
next_revision = iterator.next()
2133
for revision_id in iterator:
2134
self._partial_revision_history_cache.append(revision_id)
2135
if (stop_index is not None and
2136
len(self._partial_revision_history_cache) > stop_index):
2138
if revision_id == stop_revision:
1982
history = list(self.repository.iter_reverse_revision_history(
1983
self.last_revision()))
2141
1987
def _write_revision_history(self, history):
2142
1988
"""Factored out of set_revision_history.
2217
2056
self.get_config().set_user_option('append_revisions_only', value,
2218
2057
warn_masked=True)
2220
def set_stacked_on_url(self, url):
2221
self._check_stackable_repo()
2224
old_url = self.get_stacked_on_url()
2225
except (errors.NotStacked, errors.UnstackableBranchFormat,
2226
errors.UnstackableRepositoryFormat):
2229
# repositories don't offer an interface to remove fallback
2230
# repositories today; take the conceptually simpler option and just
2232
self.repository = self.bzrdir.find_repository()
2233
# for every revision reference the branch has, ensure it is pulled
2235
source_repository = self._get_fallback_repository(old_url)
2236
for revision_id in chain([self.last_revision()],
2237
self.tags.get_reverse_tag_dict()):
2238
self.repository.fetch(source_repository, revision_id,
2241
self._activate_fallback_location(url)
2242
# write this out after the repository is stacked to avoid setting a
2243
# stacked config that doesn't work.
2244
self._set_config_location('stacked_on_location', url)
2246
2059
def _get_append_revisions_only(self):
2247
2060
value = self.get_config().get_user_option('append_revisions_only')
2248
2061
return value == 'True'
2279
2092
def _make_tags(self):
2280
2093
return BasicTags(self)
2283
def generate_revision_history(self, revision_id, last_rev=None,
2285
"""See BzrBranch5.generate_revision_history"""
2286
history = self._lefthand_history(revision_id, last_rev, other_branch)
2287
revno = len(history)
2288
self.set_last_revision_info(revno, revision_id)
2291
def get_rev_id(self, revno, history=None):
2292
"""Find the revision id of the specified revno."""
2294
return _mod_revision.NULL_REVISION
2296
last_revno, last_revision_id = self.last_revision_info()
2297
if revno <= 0 or revno > last_revno:
2298
raise errors.NoSuchRevision(self, revno)
2300
if history is not None:
2301
return history[revno - 1]
2303
index = last_revno - revno
2304
if len(self._partial_revision_history_cache) <= index:
2305
self._extend_partial_history(stop_index=index)
2306
if len(self._partial_revision_history_cache) > index:
2307
return self._partial_revision_history_cache[index]
2309
raise errors.NoSuchRevision(self, revno)
2312
def revision_id_to_revno(self, revision_id):
2313
"""Given a revision id, return its revno"""
2314
if _mod_revision.is_null(revision_id):
2317
index = self._partial_revision_history_cache.index(revision_id)
2319
self._extend_partial_history(stop_revision=revision_id)
2320
index = len(self._partial_revision_history_cache) - 1
2321
if self._partial_revision_history_cache[index] != revision_id:
2322
raise errors.NoSuchRevision(self, revision_id)
2323
return self.revno() - index
2326
class BzrBranch6(BzrBranch7):
2327
"""See BzrBranchFormat6 for the capabilities of this branch.
2329
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2333
def get_stacked_on_url(self):
2334
raise errors.UnstackableBranchFormat(self._format, self.base)
2336
def set_stacked_on_url(self, url):
2337
raise errors.UnstackableBranchFormat(self._format, self.base)
2340
2096
######################################################################
2341
2097
# results of operations
2442
2194
new_branch.tags._set_tag_dict({})
2444
2196
# Copying done; now update target format
2445
new_branch._transport.put_bytes('format',
2446
format.get_format_string(),
2447
mode=new_branch.bzrdir._get_file_mode())
2197
new_branch.control_files.put_utf8('format',
2198
format.get_format_string())
2449
2200
# Clean up old files
2450
new_branch._transport.delete('revision-history')
2201
new_branch.control_files._transport.delete('revision-history')
2452
2203
branch.set_parent(None)
2453
except errors.NoSuchFile:
2455
2206
branch.set_bound_location(None)
2458
class Converter6to7(object):
2459
"""Perform an in-place upgrade of format 6 to format 7"""
2461
def convert(self, branch):
2462
format = BzrBranchFormat7()
2463
branch._set_config_location('stacked_on_location', '')
2464
# update target format
2465
branch._transport.put_bytes('format', format.get_format_string())