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
813
def supports_tags(self):
883
814
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
817
class BranchFormat(object):
922
818
"""An encapsulation of the initialization and open routines for a format.
1138
1043
# local is the local branch or None, master is the target branch,
1139
1044
# and an empty branch recieves new_revno of 0, new_revid of None.
1140
1045
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
1048
# install the default hooks into the Branch class.
1156
1049
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
1052
class BzrBranchFormat4(BranchFormat):
1198
1053
"""Bzr branch format 4.
1236
1091
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)
1094
class BzrBranchFormat5(BranchFormat):
1095
"""Bzr branch format 5.
1098
- a revision-history file.
1100
- a lock dir guarding the branch itself
1101
- all of this stored in a branch/ subdirectory
1102
- works with shared repositories.
1104
This format is new in bzr 0.8.
1107
def get_format_string(self):
1108
"""See BranchFormat.get_format_string()."""
1109
return "Bazaar-NG branch format 5\n"
1111
def get_format_description(self):
1112
"""See BranchFormat.get_format_description()."""
1113
return "Branch format 5"
1115
def initialize(self, a_bzrdir):
1116
"""Create a branch of this format in a_bzrdir."""
1117
utf8_files = [('revision-history', ''),
1118
('branch-name', ''),
1120
return self._initialize_helper(a_bzrdir, utf8_files)
1123
super(BzrBranchFormat5, self).__init__()
1124
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1246
1126
def open(self, a_bzrdir, _found=False):
1247
"""Return the branch object for a_bzrdir.
1127
"""Return the branch object for a_bzrdir
1249
1129
_found is a private parameter, do not use it. It is used to indicate
1250
1130
if format probing has already be done.
1253
1133
format = BranchFormat.find_format(a_bzrdir)
1254
if format.__class__ != self.__class__:
1255
raise AssertionError("wrong format %r found for %r" %
1134
assert format.__class__ == self.__class__
1258
1136
transport = a_bzrdir.get_branch_transport(None)
1259
1137
control_files = lockable_files.LockableFiles(transport, 'lock',
1260
1138
lockdir.LockDir)
1261
return self._branch_class()(_format=self,
1139
return BzrBranch5(_format=self,
1262
1140
_control_files=control_files,
1263
1141
a_bzrdir=a_bzrdir,
1264
1142
_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):
1144
raise NotBranchError(path=transport.base)
1147
class BzrBranchFormat6(BzrBranchFormat5):
1312
1148
"""Branch format with last-revision and tags.
1314
1150
Unlike previous formats, this has no explicit revision history. Instead,
1339
1172
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):
1174
def open(self, a_bzrdir, _found=False):
1175
"""Return the branch object for a_bzrdir
1177
_found is a private parameter, do not use it. It is used to indicate
1178
if format probing has already be done.
1181
format = BranchFormat.find_format(a_bzrdir)
1182
assert format.__class__ == self.__class__
1183
transport = a_bzrdir.get_branch_transport(None)
1184
control_files = lockable_files.LockableFiles(transport, 'lock',
1186
return BzrBranch6(_format=self,
1187
_control_files=control_files,
1189
_repository=a_bzrdir.find_repository())
1191
def supports_tags(self):
1482
1294
Note that it's "local" in the context of the filesystem; it doesn't
1483
1295
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1484
1296
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
1299
def __init__(self, _format=None,
1494
1300
_control_files=None, a_bzrdir=None, _repository=None):
1495
1301
"""Create new branch object at a particular location."""
1302
Branch.__init__(self)
1496
1303
if a_bzrdir is None:
1497
1304
raise ValueError('a_bzrdir must be supplied')
1499
1306
self.bzrdir = a_bzrdir
1307
# self._transport used to point to the directory containing the
1308
# control directory, but was not used - now it's just the transport
1309
# for the branch control files. mbp 20070212
1500
1310
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
1311
self._format = _format
1505
1312
if _control_files is None:
1506
1313
raise ValueError('BzrBranch _control_files is None')
1507
1314
self.control_files = _control_files
1508
1315
self._transport = _control_files._transport
1509
1316
self.repository = _repository
1510
Branch.__init__(self)
1512
1318
def __str__(self):
1513
1319
return '%s(%r)' % (self.__class__.__name__, self.base)
1575
1388
This performs the actual writing to disk.
1576
1389
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())
1390
self.control_files.put_bytes(
1391
'revision-history', '\n'.join(history))
1581
1393
@needs_write_lock
1582
1394
def set_revision_history(self, rev_history):
1583
1395
"""See Branch.set_revision_history."""
1584
1396
if 'evil' in debug.debug_flags:
1585
1397
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)
1398
self._clear_cached_state()
1598
1399
self._write_revision_history(rev_history)
1599
self._clear_cached_state()
1600
1400
self._cache_revision_history(rev_history)
1601
1401
for hook in Branch.hooks['set_rh']:
1602
1402
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
1404
@needs_write_lock
1637
1405
def set_last_revision_info(self, revno, revision_id):
1638
1406
"""Set the last revision of this branch.
1666
1429
if 'evil' in debug.debug_flags:
1667
1430
mutter_callsite(4, "_lefthand_history scales with history.")
1668
1431
# 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)
1432
stop_graph = self.repository.get_revision_graph(revision_id)
1433
if (last_rev is not None and last_rev != _mod_revision.NULL_REVISION
1434
and last_rev not in stop_graph):
1435
# our previous tip is not merged into stop_revision
1436
raise errors.DivergedBranches(self, other_branch)
1674
1437
# 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
1438
current_rev_id = revision_id
1679
1439
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)
1440
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1685
1441
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])
1442
current_rev_id_parents = stop_graph[current_rev_id]
1444
current_rev_id = current_rev_id_parents[0]
1446
current_rev_id = None
1688
1447
new_history.reverse()
1689
1448
return new_history
1702
1461
self.set_revision_history(self._lefthand_history(revision_id,
1703
1462
last_rev, other_branch))
1465
def update_revisions(self, other, stop_revision=None, overwrite=False):
1466
"""See Branch.update_revisions."""
1469
other_last_revno, other_last_revision = other.last_revision_info()
1470
if stop_revision is None:
1471
stop_revision = other_last_revision
1472
if _mod_revision.is_null(stop_revision):
1473
# if there are no commits, we're done.
1475
# whats the current last revision, before we fetch [and change it
1477
last_rev = _mod_revision.ensure_null(self.last_revision())
1478
# we fetch here so that we don't process data twice in the common
1479
# case of having something to pull, and so that the check for
1480
# already merged can operate on the just fetched graph, which will
1481
# be cached in memory.
1482
self.fetch(other, stop_revision)
1483
# Check to see if one is an ancestor of the other
1485
heads = self.repository.get_graph().heads([stop_revision,
1487
if heads == set([last_rev]):
1488
# The current revision is a decendent of the target,
1491
elif heads == set([stop_revision, last_rev]):
1492
# These branches have diverged
1493
raise errors.DivergedBranches(self, other)
1494
assert heads == set([stop_revision])
1495
if other_last_revision == stop_revision:
1496
self.set_last_revision_info(other_last_revno,
1497
other_last_revision)
1499
# TODO: jam 2007-11-29 Is there a way to determine the
1500
# revno without searching all of history??
1502
self.generate_revision_history(stop_revision)
1504
self.generate_revision_history(stop_revision,
1505
last_rev=last_rev, other_branch=other)
1705
1509
def basis_tree(self):
1706
1510
"""See Branch.basis_tree."""
1707
1511
return self.repository.revision_tree(self.last_revision())
1709
1513
@needs_write_lock
1710
1514
def pull(self, source, overwrite=False, stop_revision=None,
1711
_hook_master=None, run_hooks=True, possible_transports=None,
1712
_override_hook_target=None):
1515
_hook_master=None, run_hooks=True, possible_transports=None):
1713
1516
"""See Branch.pull.
1715
1518
:param _hook_master: Private parameter - set the branch to
1716
be supplied as the master to pull hooks.
1519
be supplied as the master to push hooks.
1717
1520
:param run_hooks: Private parameter - if false, this branch
1718
1521
is being called because it's the master of the primary branch,
1719
1522
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
1524
result = PullResult()
1724
1525
result.source_branch = source
1725
if _override_hook_target is None:
1726
result.target_branch = self
1728
result.target_branch = _override_hook_target
1526
result.target_branch = self
1729
1527
source.lock_read()
1731
# We assume that during 'pull' the local repository is closer than
1733
graph = self.repository.get_graph(source.repository)
1734
1529
result.old_revno, result.old_revid = self.last_revision_info()
1735
self.update_revisions(source, stop_revision, overwrite=overwrite,
1530
self.update_revisions(source, stop_revision, overwrite=overwrite)
1737
1531
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1738
1532
result.new_revno, result.new_revid = self.last_revision_info()
1739
1533
if _hook_master:
1740
1534
result.master_branch = _hook_master
1741
result.local_branch = result.target_branch
1535
result.local_branch = self
1743
result.master_branch = result.target_branch
1537
result.master_branch = self
1744
1538
result.local_branch = None
1746
1540
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):
1827
class BzrBranchExperimental(BzrBranch5):
1828
"""Bzr experimental branch format
1831
- a revision-history file.
1833
- a lock dir guarding the branch itself
1834
- all of this stored in a branch/ subdirectory
1835
- works with shared repositories.
1836
- a tag dictionary in the branch
1838
This format is new in bzr 0.15, but shouldn't be used for real data,
1841
This class acts as it's own BranchFormat.
1844
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1847
def get_format_string(cls):
1848
"""See BranchFormat.get_format_string()."""
1849
return "Bazaar-NG branch format experimental\n"
1852
def get_format_description(cls):
1853
"""See BranchFormat.get_format_description()."""
1854
return "Experimental branch format"
1857
def get_reference(cls, a_bzrdir):
1858
"""Get the target reference of the branch in a_bzrdir.
1860
format probing must have been completed before calling
1861
this method - it is assumed that the format of the branch
1862
in a_bzrdir is correct.
1864
:param a_bzrdir: The bzrdir to get the branch data from.
1865
:return: None if the branch is not a reference branch.
1870
def set_reference(self, a_bzrdir, to_branch):
1871
"""Set the target reference of the branch in a_bzrdir.
1873
format probing must have been completed before calling
1874
this method - it is assumed that the format of the branch
1875
in a_bzrdir is correct.
1877
:param a_bzrdir: The bzrdir to set the branch reference for.
1878
:param to_branch: branch that the checkout is to reference
1880
raise NotImplementedError(self.set_reference)
1883
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1885
branch_transport = a_bzrdir.get_branch_transport(cls)
1886
control_files = lockable_files.LockableFiles(branch_transport,
1887
lock_filename, lock_class)
1888
control_files.create_lock()
1889
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')
1891
for filename, content in utf8_files:
1892
control_files.put_utf8(filename, content)
1894
control_files.unlock()
1897
def initialize(cls, a_bzrdir):
1898
"""Create a branch of this format in a_bzrdir."""
1899
utf8_files = [('format', cls.get_format_string()),
1900
('revision-history', ''),
1901
('branch-name', ''),
1904
cls._initialize_control_files(a_bzrdir, utf8_files,
1905
'lock', lockdir.LockDir)
1906
return cls.open(a_bzrdir, _found=True)
1909
def open(cls, a_bzrdir, _found=False):
1910
"""Return the branch object for a_bzrdir
1912
_found is a private parameter, do not use it. It is used to indicate
1913
if format probing has already be done.
1916
format = BranchFormat.find_format(a_bzrdir)
1917
assert format.__class__ == cls
1918
transport = a_bzrdir.get_branch_transport(None)
1919
control_files = lockable_files.LockableFiles(transport, 'lock',
1921
return cls(_format=cls,
1922
_control_files=control_files,
1924
_repository=a_bzrdir.find_repository())
1927
def is_supported(cls):
1930
def _make_tags(self):
1931
return BasicTags(self)
1934
def supports_tags(cls):
1938
BranchFormat.register_format(BzrBranchExperimental)
1941
class BzrBranch6(BzrBranch5):
1944
def last_revision_info(self):
1945
revision_string = self.control_files.get('last-revision').read()
2067
1946
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2068
1947
revision_id = cache_utf8.get_cached_utf8(revision_id)
2069
1948
revno = int(revno)
2070
1949
return revno, revision_id
1951
def last_revision(self):
1952
"""Return last revision id, or None"""
1953
revision_id = self.last_revision_info()[1]
2072
1956
def _write_last_revision_info(self, revno, revision_id):
2073
1957
"""Simply write out the revision id, with no checks.
2078
1962
Intended to be called by set_last_revision_info and
2079
1963
_write_revision_history.
2081
revision_id = _mod_revision.ensure_null(revision_id)
1965
if revision_id is None:
1966
revision_id = 'null:'
2082
1967
out_string = '%d %s\n' % (revno, revision_id)
2083
self._transport.put_bytes('last-revision', out_string,
2084
mode=self.bzrdir._get_file_mode())
1968
self.control_files.put_bytes('last-revision', out_string)
2086
1970
@needs_write_lock
2087
1971
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
1972
if self._get_append_revisions_only():
2091
1973
self._check_history_violation(revision_id)
2092
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2093
1974
self._write_last_revision_info(revno, revision_id)
2094
1975
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
1977
def _check_history_violation(self, revision_id):
2099
1978
last_revision = _mod_revision.ensure_null(self.last_revision())
2105
1984
def _gen_revision_history(self):
2106
1985
"""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:
1987
history = list(self.repository.iter_reverse_revision_history(
1988
self.last_revision()))
2141
1992
def _write_revision_history(self, history):
2142
1993
"""Factored out of set_revision_history.
2217
2061
self.get_config().set_user_option('append_revisions_only', value,
2218
2062
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
2064
def _get_append_revisions_only(self):
2247
2065
value = self.get_config().get_user_option('append_revisions_only')
2248
2066
return value == 'True'
2279
2097
def _make_tags(self):
2280
2098
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
2101
######################################################################
2341
2102
# results of operations
2442
2199
new_branch.tags._set_tag_dict({})
2444
2201
# 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())
2202
new_branch.control_files.put_utf8('format',
2203
format.get_format_string())
2449
2205
# Clean up old files
2450
new_branch._transport.delete('revision-history')
2206
new_branch.control_files._transport.delete('revision-history')
2452
2208
branch.set_parent(None)
2453
except errors.NoSuchFile:
2455
2211
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())