1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
|
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from cStringIO import StringIO
from bzrlib.lazy_import import lazy_import
lazy_import(globals(), """
from copy import deepcopy
from unittest import TestSuite
from warnings import warn
import bzrlib
from bzrlib import (
bzrdir,
cache_utf8,
config as _mod_config,
errors,
lockdir,
lockable_files,
osutils,
revision as _mod_revision,
transport,
tree,
ui,
urlutils,
)
from bzrlib.config import BranchConfig, TreeConfig
from bzrlib.lockable_files import LockableFiles, TransportLock
from bzrlib.tag import (
BasicTags,
DisabledTags,
)
""")
from bzrlib.decorators import needs_read_lock, needs_write_lock
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
HistoryMissing, InvalidRevisionId,
InvalidRevisionNumber, LockError, NoSuchFile,
NoSuchRevision, NoWorkingTree, NotVersionedError,
NotBranchError, UninitializableFormat,
UnlistableStore, UnlistableBranch,
)
from bzrlib.symbol_versioning import (deprecated_function,
deprecated_method,
DEPRECATED_PARAMETER,
deprecated_passed,
zero_eight, zero_nine, zero_sixteen,
)
from bzrlib.trace import mutter, note
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
# TODO: Maybe include checks for common corruption of newlines, etc?
# TODO: Some operations like log might retrieve the same revisions
# repeatedly to calculate deltas. We could perhaps have a weakref
# cache in memory to make this faster. In general anything can be
# cached in memory between lock and unlock operations. .. nb thats
# what the transaction identity map provides
######################################################################
# branch objects
class Branch(object):
"""Branch holding a history of revisions.
base
Base directory/url of the branch.
hooks: An instance of BranchHooks.
"""
# this is really an instance variable - FIXME move it there
# - RBC 20060112
base = None
# override this to set the strategy for storing tags
def _make_tags(self):
return DisabledTags(self)
def __init__(self, *ignored, **ignored_too):
self.tags = self._make_tags()
self._revision_history_cache = None
def break_lock(self):
"""Break a lock if one is present from another instance.
Uses the ui factory to ask for confirmation if the lock may be from
an active process.
This will probe the repository for its lock as well.
"""
self.control_files.break_lock()
self.repository.break_lock()
master = self.get_master_branch()
if master is not None:
master.break_lock()
@staticmethod
@deprecated_method(zero_eight)
def open_downlevel(base):
"""Open a branch which may be of an old format."""
return Branch.open(base, _unsupported=True)
@staticmethod
def open(base, _unsupported=False):
"""Open the branch rooted at base.
For instance, if the branch is at URL/.bzr/branch,
Branch.open(URL) -> a Branch instance.
"""
control = bzrdir.BzrDir.open(base, _unsupported)
return control.open_branch(_unsupported)
@staticmethod
def open_containing(url):
"""Open an existing branch which contains url.
This probes for a branch at url, and searches upwards from there.
Basically we keep looking up until we find the control directory or
run into the root. If there isn't one, raises NotBranchError.
If there is one and it is either an unrecognised format or an unsupported
format, UnknownFormatError or UnsupportedFormatError are raised.
If there is one, it is returned, along with the unused portion of url.
"""
control, relpath = bzrdir.BzrDir.open_containing(url)
return control.open_branch(), relpath
@staticmethod
@deprecated_function(zero_eight)
def initialize(base):
"""Create a new working tree and branch, rooted at 'base' (url)
NOTE: This will soon be deprecated in favour of creation
through a BzrDir.
"""
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
@deprecated_function(zero_eight)
def setup_caching(self, cache_root):
"""Subclasses that care about caching should override this, and set
up cached stores located under cache_root.
NOTE: This is unused.
"""
pass
def get_config(self):
return BranchConfig(self)
def _get_nick(self):
return self.get_config().get_nickname()
def _set_nick(self, nick):
self.get_config().set_user_option('nickname', nick)
nick = property(_get_nick, _set_nick)
def is_locked(self):
raise NotImplementedError(self.is_locked)
def lock_write(self):
raise NotImplementedError(self.lock_write)
def lock_read(self):
raise NotImplementedError(self.lock_read)
def unlock(self):
raise NotImplementedError(self.unlock)
def peek_lock_mode(self):
"""Return lock mode for the Branch: 'r', 'w' or None"""
raise NotImplementedError(self.peek_lock_mode)
def get_physical_lock_status(self):
raise NotImplementedError(self.get_physical_lock_status)
def abspath(self, name):
"""Return absolute filename for something in the branch
XXX: Robert Collins 20051017 what is this used for? why is it a branch
method and not a tree method.
"""
raise NotImplementedError(self.abspath)
def bind(self, other):
"""Bind the local branch the other branch.
:param other: The branch to bind to
:type other: Branch
"""
raise errors.UpgradeRequired(self.base)
@needs_write_lock
def fetch(self, from_branch, last_revision=None, pb=None):
"""Copy revisions from from_branch into this branch.
:param from_branch: Where to copy from.
:param last_revision: What revision to stop at (None for at the end
of the branch.
:param pb: An optional progress bar to use.
Returns the copied revision count and the failed revisions in a tuple:
(copied, failures).
"""
if self.base == from_branch.base:
return (0, [])
if pb is None:
nested_pb = ui.ui_factory.nested_progress_bar()
pb = nested_pb
else:
nested_pb = None
from_branch.lock_read()
try:
if last_revision is None:
pb.update('get source history')
last_revision = from_branch.last_revision()
if last_revision is None:
last_revision = _mod_revision.NULL_REVISION
return self.repository.fetch(from_branch.repository,
revision_id=last_revision,
pb=nested_pb)
finally:
if nested_pb is not None:
nested_pb.finished()
from_branch.unlock()
def get_bound_location(self):
"""Return the URL of the branch we are bound to.
Older format branches cannot bind, please be sure to use a metadir
branch.
"""
return None
def get_old_bound_location(self):
"""Return the URL of the branch we used to be bound to
"""
raise errors.UpgradeRequired(self.base)
def get_commit_builder(self, parents, config=None, timestamp=None,
timezone=None, committer=None, revprops=None,
revision_id=None):
"""Obtain a CommitBuilder for this branch.
:param parents: Revision ids of the parents of the new revision.
:param config: Optional configuration to use.
:param timestamp: Optional timestamp recorded for commit.
:param timezone: Optional timezone for timestamp.
:param committer: Optional committer to set for commit.
:param revprops: Optional dictionary of revision properties.
:param revision_id: Optional revision id.
"""
if config is None:
config = self.get_config()
return self.repository.get_commit_builder(self, parents, config,
timestamp, timezone, committer, revprops, revision_id)
def get_master_branch(self):
"""Return the branch we are bound to.
:return: Either a Branch, or None
"""
return None
def get_revision_delta(self, revno):
"""Return the delta for one revision.
The delta is relative to its mainline predecessor, or the
empty tree for revision 1.
"""
assert isinstance(revno, int)
rh = self.revision_history()
if not (1 <= revno <= len(rh)):
raise InvalidRevisionNumber(revno)
return self.repository.get_revision_delta(rh[revno-1])
@deprecated_method(zero_sixteen)
def get_root_id(self):
"""Return the id of this branches root
Deprecated: branches don't have root ids-- trees do.
Use basis_tree().get_root_id() instead.
"""
raise NotImplementedError(self.get_root_id)
def print_file(self, file, revision_id):
"""Print `file` to stdout."""
raise NotImplementedError(self.print_file)
def append_revision(self, *revision_ids):
raise NotImplementedError(self.append_revision)
def set_revision_history(self, rev_history):
raise NotImplementedError(self.set_revision_history)
def _cache_revision_history(self, rev_history):
"""Set the cached revision history to rev_history.
The revision_history method will use this cache to avoid regenerating
the revision history.
This API is semi-public; it only for use by subclasses, all other code
should consider it to be private.
"""
self._revision_history_cache = rev_history
def _clear_cached_state(self):
"""Clear any cached data on this branch, e.g. cached revision history.
This means the next call to revision_history will need to call
_gen_revision_history.
This API is semi-public; it only for use by subclasses, all other code
should consider it to be private.
"""
self._revision_history_cache = None
def _gen_revision_history(self):
"""Return sequence of revision hashes on to this branch.
Unlike revision_history, this method always regenerates or rereads the
revision history, i.e. it does not cache the result, so repeated calls
may be expensive.
Concrete subclasses should override this instead of revision_history so
that subclasses do not need to deal with caching logic.
This API is semi-public; it only for use by subclasses, all other code
should consider it to be private.
"""
raise NotImplementedError(self._gen_revision_history)
@needs_read_lock
def revision_history(self):
"""Return sequence of revision hashes on to this branch.
This method will cache the revision history for as long as it is safe to
do so.
"""
if self._revision_history_cache is not None:
history = self._revision_history_cache
else:
history = self._gen_revision_history()
self._cache_revision_history(history)
return list(history)
def revno(self):
"""Return current revision number for this branch.
That is equivalent to the number of revisions committed to
this branch.
"""
return len(self.revision_history())
def unbind(self):
"""Older format branches cannot bind or unbind."""
raise errors.UpgradeRequired(self.base)
def set_append_revisions_only(self, enabled):
"""Older format branches are never restricted to append-only"""
raise errors.UpgradeRequired(self.base)
def last_revision(self):
"""Return last revision id, or None"""
ph = self.revision_history()
if ph:
return ph[-1]
else:
return None
def last_revision_info(self):
"""Return information about the last revision.
:return: A tuple (revno, last_revision_id).
"""
rh = self.revision_history()
revno = len(rh)
if revno:
return (revno, rh[-1])
else:
return (0, _mod_revision.NULL_REVISION)
def missing_revisions(self, other, stop_revision=None):
"""Return a list of new revisions that would perfectly fit.
If self and other have not diverged, return a list of the revisions
present in other, but missing from self.
"""
self_history = self.revision_history()
self_len = len(self_history)
other_history = other.revision_history()
other_len = len(other_history)
common_index = min(self_len, other_len) -1
if common_index >= 0 and \
self_history[common_index] != other_history[common_index]:
raise DivergedBranches(self, other)
if stop_revision is None:
stop_revision = other_len
else:
assert isinstance(stop_revision, int)
if stop_revision > other_len:
raise errors.NoSuchRevision(self, stop_revision)
return other_history[self_len:stop_revision]
def update_revisions(self, other, stop_revision=None):
"""Pull in new perfect-fit revisions.
:param other: Another Branch to pull from
:param stop_revision: Updated until the given revision
:return: None
"""
raise NotImplementedError(self.update_revisions)
def revision_id_to_revno(self, revision_id):
"""Given a revision id, return its revno"""
if revision_id is None:
return 0
revision_id = osutils.safe_revision_id(revision_id)
history = self.revision_history()
try:
return history.index(revision_id) + 1
except ValueError:
raise bzrlib.errors.NoSuchRevision(self, revision_id)
def get_rev_id(self, revno, history=None):
"""Find the revision id of the specified revno."""
if revno == 0:
return None
if history is None:
history = self.revision_history()
if revno <= 0 or revno > len(history):
raise bzrlib.errors.NoSuchRevision(self, revno)
return history[revno - 1]
def pull(self, source, overwrite=False, stop_revision=None):
"""Mirror source into this branch.
This branch is considered to be 'local', having low latency.
:returns: PullResult instance
"""
raise NotImplementedError(self.pull)
def push(self, target, overwrite=False, stop_revision=None):
"""Mirror this branch into target.
This branch is considered to be 'local', having low latency.
"""
raise NotImplementedError(self.push)
def basis_tree(self):
"""Return `Tree` object for last revision."""
return self.repository.revision_tree(self.last_revision())
def rename_one(self, from_rel, to_rel):
"""Rename one file.
This can change the directory or the filename or both.
"""
raise NotImplementedError(self.rename_one)
def move(self, from_paths, to_name):
"""Rename files.
to_name must exist as a versioned directory.
If to_name exists and is a directory, the files are moved into
it, keeping their old names. If it is a directory,
Note that to_name is only the last component of the new name;
this doesn't change the directory.
This returns a list of (from_path, to_path) pairs for each
entry that is moved.
"""
raise NotImplementedError(self.move)
def get_parent(self):
"""Return the parent location of the branch.
This is the default location for push/pull/missing. The usual
pattern is that the user can override it by specifying a
location.
"""
raise NotImplementedError(self.get_parent)
def _set_config_location(self, name, url, config=None,
make_relative=False):
if config is None:
config = self.get_config()
if url is None:
url = ''
elif make_relative:
url = urlutils.relative_url(self.base, url)
config.set_user_option(name, url)
def _get_config_location(self, name, config=None):
if config is None:
config = self.get_config()
location = config.get_user_option(name)
if location == '':
location = None
return location
def get_submit_branch(self):
"""Return the submit location of the branch.
This is the default location for bundle. The usual
pattern is that the user can override it by specifying a
location.
"""
return self.get_config().get_user_option('submit_branch')
def set_submit_branch(self, location):
"""Return the submit location of the branch.
This is the default location for bundle. The usual
pattern is that the user can override it by specifying a
location.
"""
self.get_config().set_user_option('submit_branch', location)
def get_public_branch(self):
"""Return the public location of the branch.
This is is used by merge directives.
"""
return self._get_config_location('public_branch')
def set_public_branch(self, location):
"""Return the submit location of the branch.
This is the default location for bundle. The usual
pattern is that the user can override it by specifying a
location.
"""
self._set_config_location('public_branch', location)
def get_push_location(self):
"""Return the None or the location to push this branch to."""
raise NotImplementedError(self.get_push_location)
def set_push_location(self, location):
"""Set a new push location for this branch."""
raise NotImplementedError(self.set_push_location)
def set_parent(self, url):
raise NotImplementedError(self.set_parent)
@needs_write_lock
def update(self):
"""Synchronise this branch with the master branch if any.
:return: None or the last_revision pivoted out during the update.
"""
return None
def check_revno(self, revno):
"""\
Check whether a revno corresponds to any revision.
Zero (the NULL revision) is considered valid.
"""
if revno != 0:
self.check_real_revno(revno)
def check_real_revno(self, revno):
"""\
Check whether a revno corresponds to a real revision.
Zero (the NULL revision) is considered invalid
"""
if revno < 1 or revno > self.revno():
raise InvalidRevisionNumber(revno)
@needs_read_lock
def clone(self, to_bzrdir, revision_id=None):
"""Clone this branch into to_bzrdir preserving all semantic values.
revision_id: if not None, the revision history in the new branch will
be truncated to end with revision_id.
"""
result = self._format.initialize(to_bzrdir)
self.copy_content_into(result, revision_id=revision_id)
return result
@needs_read_lock
def sprout(self, to_bzrdir, revision_id=None):
"""Create a new line of development from the branch, into to_bzrdir.
revision_id: if not None, the revision history in the new branch will
be truncated to end with revision_id.
"""
result = self._format.initialize(to_bzrdir)
self.copy_content_into(result, revision_id=revision_id)
result.set_parent(self.bzrdir.root_transport.base)
return result
def _synchronize_history(self, destination, revision_id):
"""Synchronize last revision and revision history between branches.
This version is most efficient when the destination is also a
BzrBranch5, but works for BzrBranch6 as long as the revision
history is the true lefthand parent history, and all of the revisions
are in the destination's repository. If not, set_revision_history
will fail.
:param destination: The branch to copy the history into
:param revision_id: The revision-id to truncate history at. May
be None to copy complete history.
"""
new_history = self.revision_history()
if revision_id is not None:
revision_id = osutils.safe_revision_id(revision_id)
try:
new_history = new_history[:new_history.index(revision_id) + 1]
except ValueError:
rev = self.repository.get_revision(revision_id)
new_history = rev.get_history(self.repository)[1:]
destination.set_revision_history(new_history)
@needs_read_lock
def copy_content_into(self, destination, revision_id=None):
"""Copy the content of self into destination.
revision_id: if not None, the revision history in the new branch will
be truncated to end with revision_id.
"""
self._synchronize_history(destination, revision_id)
try:
parent = self.get_parent()
except errors.InaccessibleParent, e:
mutter('parent was not accessible to copy: %s', e)
else:
if parent:
destination.set_parent(parent)
self.tags.merge_to(destination.tags)
@needs_read_lock
def check(self):
"""Check consistency of the branch.
In particular this checks that revisions given in the revision-history
do actually match up in the revision graph, and that they're all
present in the repository.
Callers will typically also want to check the repository.
:return: A BranchCheckResult.
"""
mainline_parent_id = None
for revision_id in self.revision_history():
try:
revision = self.repository.get_revision(revision_id)
except errors.NoSuchRevision, e:
raise errors.BzrCheckError("mainline revision {%s} not in repository"
% revision_id)
# In general the first entry on the revision history has no parents.
# But it's not illegal for it to have parents listed; this can happen
# in imports from Arch when the parents weren't reachable.
if mainline_parent_id is not None:
if mainline_parent_id not in revision.parent_ids:
raise errors.BzrCheckError("previous revision {%s} not listed among "
"parents of {%s}"
% (mainline_parent_id, revision_id))
mainline_parent_id = revision_id
return BranchCheckResult(self)
def _get_checkout_format(self):
"""Return the most suitable metadir for a checkout of this branch.
Weaves are used if this branch's repostory uses weaves.
"""
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
from bzrlib.repofmt import weaverepo
format = bzrdir.BzrDirMetaFormat1()
format.repository_format = weaverepo.RepositoryFormat7()
else:
format = self.repository.bzrdir.checkout_metadir()
format.set_branch_format(self._format)
return format
def create_checkout(self, to_location, revision_id=None,
lightweight=False):
"""Create a checkout of a branch.
:param to_location: The url to produce the checkout at
:param revision_id: The revision to check out
:param lightweight: If True, produce a lightweight checkout, otherwise,
produce a bound branch (heavyweight checkout)
:return: The tree of the created checkout
"""
t = transport.get_transport(to_location)
try:
t.mkdir('.')
except errors.FileExists:
pass
if lightweight:
format = self._get_checkout_format()
checkout = format.initialize_on_transport(t)
BranchReferenceFormat().initialize(checkout, self)
else:
format = self._get_checkout_format()
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
to_location, force_new_tree=False, format=format)
checkout = checkout_branch.bzrdir
checkout_branch.bind(self)
# pull up to the specified revision_id to set the initial
# branch tip correctly, and seed it with history.
checkout_branch.pull(self, stop_revision=revision_id)
tree = checkout.create_workingtree(revision_id)
basis_tree = tree.basis_tree()
basis_tree.lock_read()
try:
for path, file_id in basis_tree.iter_references():
reference_parent = self.reference_parent(file_id, path)
reference_parent.create_checkout(tree.abspath(path),
basis_tree.get_reference_revision(file_id, path),
lightweight)
finally:
basis_tree.unlock()
return tree
def reference_parent(self, file_id, path):
"""Return the parent branch for a tree-reference file_id
:param file_id: The file_id of the tree reference
:param path: The path of the file_id in the tree
:return: A branch associated with the file_id
"""
# FIXME should provide multiple branches, based on config
return Branch.open(self.bzrdir.root_transport.clone(path).base)
def supports_tags(self):
return self._format.supports_tags()
class BranchFormat(object):
"""An encapsulation of the initialization and open routines for a format.
Formats provide three things:
* An initialization routine,
* a format string,
* an open routine.
Formats are placed in an dict by their format string for reference
during branch opening. Its not required that these be instances, they
can be classes themselves with class methods - it simply depends on
whether state is needed for a given format or not.
Once a format is deprecated, just deprecate the initialize and open
methods on the format class. Do not deprecate the object, as the
object will be created every time regardless.
"""
_default_format = None
"""The default format used for new branches."""
_formats = {}
"""The known formats."""
@classmethod
def find_format(klass, a_bzrdir):
"""Return the format for the branch object in a_bzrdir."""
try:
transport = a_bzrdir.get_branch_transport(None)
format_string = transport.get("format").read()
return klass._formats[format_string]
except NoSuchFile:
raise NotBranchError(path=transport.base)
except KeyError:
raise errors.UnknownFormatError(format=format_string)
@classmethod
def get_default_format(klass):
"""Return the current default format."""
return klass._default_format
def get_format_string(self):
"""Return the ASCII format string that identifies this format."""
raise NotImplementedError(self.get_format_string)
def get_format_description(self):
"""Return the short format description for this format."""
raise NotImplementedError(self.get_format_description)
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
set_format=True):
"""Initialize a branch in a bzrdir, with specified files
:param a_bzrdir: The bzrdir to initialize the branch in
:param utf8_files: The files to create as a list of
(filename, content) tuples
:param set_format: If True, set the format with
self.get_format_string. (BzrBranch4 has its format set
elsewhere)
:return: a branch in this format
"""
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
branch_transport = a_bzrdir.get_branch_transport(self)
lock_map = {
'metadir': ('lock', lockdir.LockDir),
'branch4': ('branch-lock', lockable_files.TransportLock),
}
lock_name, lock_class = lock_map[lock_type]
control_files = lockable_files.LockableFiles(branch_transport,
lock_name, lock_class)
control_files.create_lock()
control_files.lock_write()
if set_format:
control_files.put_utf8('format', self.get_format_string())
try:
for file, content in utf8_files:
control_files.put_utf8(file, content)
finally:
control_files.unlock()
return self.open(a_bzrdir, _found=True)
def initialize(self, a_bzrdir):
"""Create a branch of this format in a_bzrdir."""
raise NotImplementedError(self.initialize)
def is_supported(self):
"""Is this format supported?
Supported formats can be initialized and opened.
Unsupported formats may not support initialization or committing or
some other features depending on the reason for not being supported.
"""
return True
def open(self, a_bzrdir, _found=False):
"""Return the branch object for a_bzrdir
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
raise NotImplementedError(self.open)
@classmethod
def register_format(klass, format):
klass._formats[format.get_format_string()] = format
@classmethod
def set_default_format(klass, format):
klass._default_format = format
@classmethod
def unregister_format(klass, format):
assert klass._formats[format.get_format_string()] is format
del klass._formats[format.get_format_string()]
def __str__(self):
return self.get_format_string().rstrip()
def supports_tags(self):
"""True if this format supports tags stored in the branch"""
return False # by default
# XXX: Probably doesn't really belong here -- mbp 20070212
def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
lock_class):
branch_transport = a_bzrdir.get_branch_transport(self)
control_files = lockable_files.LockableFiles(branch_transport,
lock_filename, lock_class)
control_files.create_lock()
control_files.lock_write()
try:
for filename, content in utf8_files:
control_files.put_utf8(filename, content)
finally:
control_files.unlock()
class BranchHooks(dict):
"""A dictionary mapping hook name to a list of callables for branch hooks.
e.g. ['set_rh'] Is the list of items to be called when the
set_revision_history function is invoked.
"""
def __init__(self):
"""Create the default hooks.
These are all empty initially, because by default nothing should get
notified.
"""
dict.__init__(self)
# Introduced in 0.15:
# invoked whenever the revision history has been set
# with set_revision_history. The api signature is
# (branch, revision_history), and the branch will
# be write-locked.
self['set_rh'] = []
# invoked after a push operation completes.
# the api signature is
# (push_result)
# containing the members
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
# where local is the local branch or None, master is the target
# master branch, and the rest should be self explanatory. The source
# is read locked and the target branches write locked. Source will
# be the local low-latency branch.
self['post_push'] = []
# invoked after a pull operation completes.
# the api signature is
# (pull_result)
# containing the members
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
# where local is the local branch or None, master is the target
# master branch, and the rest should be self explanatory. The source
# is read locked and the target branches write locked. The local
# branch is the low-latency branch.
self['post_pull'] = []
# invoked after a commit operation completes.
# the api signature is
# (local, master, old_revno, old_revid, new_revno, new_revid)
# old_revid is NULL_REVISION for the first commit to a branch.
self['post_commit'] = []
# invoked after a uncommit operation completes.
# the api signature is
# (local, master, old_revno, old_revid, new_revno, new_revid) where
# local is the local branch or None, master is the target branch,
# and an empty branch recieves new_revno of 0, new_revid of None.
self['post_uncommit'] = []
def install_hook(self, hook_name, a_callable):
"""Install a_callable in to the hook hook_name.
:param hook_name: A hook name. See the __init__ method of BranchHooks
for the complete list of hooks.
:param a_callable: The callable to be invoked when the hook triggers.
The exact signature will depend on the hook - see the __init__
method of BranchHooks for details on each hook.
"""
try:
self[hook_name].append(a_callable)
except KeyError:
raise errors.UnknownHook('branch', hook_name)
# install the default hooks into the Branch class.
Branch.hooks = BranchHooks()
class BzrBranchFormat4(BranchFormat):
"""Bzr branch format 4.
This format has:
- a revision-history file.
- a branch-lock lock file [ to be shared with the bzrdir ]
"""
def get_format_description(self):
"""See BranchFormat.get_format_description()."""
return "Branch format 4"
def initialize(self, a_bzrdir):
"""Create a branch of this format in a_bzrdir."""
utf8_files = [('revision-history', ''),
('branch-name', ''),
]
return self._initialize_helper(a_bzrdir, utf8_files,
lock_type='branch4', set_format=False)
def __init__(self):
super(BzrBranchFormat4, self).__init__()
self._matchingbzrdir = bzrdir.BzrDirFormat6()
def open(self, a_bzrdir, _found=False):
"""Return the branch object for a_bzrdir
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
if not _found:
# we are being called directly and must probe.
raise NotImplementedError
return BzrBranch(_format=self,
_control_files=a_bzrdir._control_files,
a_bzrdir=a_bzrdir,
_repository=a_bzrdir.open_repository())
def __str__(self):
return "Bazaar-NG branch format 4"
class BzrBranchFormat5(BranchFormat):
"""Bzr branch format 5.
This format has:
- a revision-history file.
- a format string
- a lock dir guarding the branch itself
- all of this stored in a branch/ subdirectory
- works with shared repositories.
This format is new in bzr 0.8.
"""
def get_format_string(self):
"""See BranchFormat.get_format_string()."""
return "Bazaar-NG branch format 5\n"
def get_format_description(self):
"""See BranchFormat.get_format_description()."""
return "Branch format 5"
def initialize(self, a_bzrdir):
"""Create a branch of this format in a_bzrdir."""
utf8_files = [('revision-history', ''),
('branch-name', ''),
]
return self._initialize_helper(a_bzrdir, utf8_files)
def __init__(self):
super(BzrBranchFormat5, self).__init__()
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
def open(self, a_bzrdir, _found=False):
"""Return the branch object for a_bzrdir
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
if not _found:
format = BranchFormat.find_format(a_bzrdir)
assert format.__class__ == self.__class__
transport = a_bzrdir.get_branch_transport(None)
control_files = lockable_files.LockableFiles(transport, 'lock',
lockdir.LockDir)
return BzrBranch5(_format=self,
_control_files=control_files,
a_bzrdir=a_bzrdir,
_repository=a_bzrdir.find_repository())
class BzrBranchFormat6(BzrBranchFormat5):
"""Branch format with last-revision
Unlike previous formats, this has no explicit revision history. Instead,
this just stores the last-revision, and the left-hand history leading
up to there is the history.
This format was introduced in bzr 0.15
"""
def get_format_string(self):
"""See BranchFormat.get_format_string()."""
return "Bazaar Branch Format 6 (bzr 0.15)\n"
def get_format_description(self):
"""See BranchFormat.get_format_description()."""
return "Branch format 6"
def initialize(self, a_bzrdir):
"""Create a branch of this format in a_bzrdir."""
utf8_files = [('last-revision', '0 null:\n'),
('branch-name', ''),
('branch.conf', ''),
('tags', ''),
]
return self._initialize_helper(a_bzrdir, utf8_files)
def open(self, a_bzrdir, _found=False):
"""Return the branch object for a_bzrdir
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
if not _found:
format = BranchFormat.find_format(a_bzrdir)
assert format.__class__ == self.__class__
transport = a_bzrdir.get_branch_transport(None)
control_files = lockable_files.LockableFiles(transport, 'lock',
lockdir.LockDir)
return BzrBranch6(_format=self,
_control_files=control_files,
a_bzrdir=a_bzrdir,
_repository=a_bzrdir.find_repository())
def supports_tags(self):
return True
class BranchReferenceFormat(BranchFormat):
"""Bzr branch reference format.
Branch references are used in implementing checkouts, they
act as an alias to the real branch which is at some other url.
This format has:
- A location file
- a format string
"""
def get_format_string(self):
"""See BranchFormat.get_format_string()."""
return "Bazaar-NG Branch Reference Format 1\n"
def get_format_description(self):
"""See BranchFormat.get_format_description()."""
return "Checkout reference format 1"
def initialize(self, a_bzrdir, target_branch=None):
"""Create a branch of this format in a_bzrdir."""
if target_branch is None:
# this format does not implement branch itself, thus the implicit
# creation contract must see it as uninitializable
raise errors.UninitializableFormat(self)
mutter('creating branch reference in %s', a_bzrdir.transport.base)
branch_transport = a_bzrdir.get_branch_transport(self)
branch_transport.put_bytes('location',
target_branch.bzrdir.root_transport.base)
branch_transport.put_bytes('format', self.get_format_string())
return self.open(a_bzrdir, _found=True)
def __init__(self):
super(BranchReferenceFormat, self).__init__()
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
def _make_reference_clone_function(format, a_branch):
"""Create a clone() routine for a branch dynamically."""
def clone(to_bzrdir, revision_id=None):
"""See Branch.clone()."""
return format.initialize(to_bzrdir, a_branch)
# cannot obey revision_id limits when cloning a reference ...
# FIXME RBC 20060210 either nuke revision_id for clone, or
# emit some sort of warning/error to the caller ?!
return clone
def open(self, a_bzrdir, _found=False):
"""Return the branch that the branch reference in a_bzrdir points at.
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
if not _found:
format = BranchFormat.find_format(a_bzrdir)
assert format.__class__ == self.__class__
transport = a_bzrdir.get_branch_transport(None)
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
result = real_bzrdir.open_branch()
# this changes the behaviour of result.clone to create a new reference
# rather than a copy of the content of the branch.
# I did not use a proxy object because that needs much more extensive
# testing, and we are only changing one behaviour at the moment.
# If we decide to alter more behaviours - i.e. the implicit nickname
# then this should be refactored to introduce a tested proxy branch
# and a subclass of that for use in overriding clone() and ....
# - RBC 20060210
result.clone = self._make_reference_clone_function(result)
return result
# formats which have no format string are not discoverable
# and not independently creatable, so are not registered.
__default_format = BzrBranchFormat5()
BranchFormat.register_format(__default_format)
BranchFormat.register_format(BranchReferenceFormat())
BranchFormat.register_format(BzrBranchFormat6())
BranchFormat.set_default_format(__default_format)
_legacy_formats = [BzrBranchFormat4(),
]
class BzrBranch(Branch):
"""A branch stored in the actual filesystem.
Note that it's "local" in the context of the filesystem; it doesn't
really matter if it's on an nfs/smb/afs/coda/... share, as long as
it's writable, and can be accessed via the normal filesystem API.
"""
def __init__(self, _format=None,
_control_files=None, a_bzrdir=None, _repository=None):
"""Create new branch object at a particular location."""
Branch.__init__(self)
if a_bzrdir is None:
raise ValueError('a_bzrdir must be supplied')
else:
self.bzrdir = a_bzrdir
# self._transport used to point to the directory containing the
# control directory, but was not used - now it's just the transport
# for the branch control files. mbp 20070212
self._base = self.bzrdir.transport.clone('..').base
self._format = _format
if _control_files is None:
raise ValueError('BzrBranch _control_files is None')
self.control_files = _control_files
self._transport = _control_files._transport
self.repository = _repository
def __str__(self):
return '%s(%r)' % (self.__class__.__name__, self.base)
__repr__ = __str__
def _get_base(self):
"""Returns the directory containing the control directory."""
return self._base
base = property(_get_base, doc="The URL for the root of this branch.")
def abspath(self, name):
"""See Branch.abspath."""
return self.control_files._transport.abspath(name)
@deprecated_method(zero_sixteen)
@needs_read_lock
def get_root_id(self):
"""See Branch.get_root_id."""
tree = self.repository.revision_tree(self.last_revision())
return tree.inventory.root.file_id
def is_locked(self):
return self.control_files.is_locked()
def lock_write(self):
self.repository.lock_write()
try:
self.control_files.lock_write()
except:
self.repository.unlock()
raise
def lock_read(self):
self.repository.lock_read()
try:
self.control_files.lock_read()
except:
self.repository.unlock()
raise
def unlock(self):
# TODO: test for failed two phase locks. This is known broken.
try:
self.control_files.unlock()
finally:
self.repository.unlock()
if not self.control_files.is_locked():
# we just released the lock
self._clear_cached_state()
def peek_lock_mode(self):
if self.control_files._lock_count == 0:
return None
else:
return self.control_files._lock_mode
def get_physical_lock_status(self):
return self.control_files.get_physical_lock_status()
@needs_read_lock
def print_file(self, file, revision_id):
"""See Branch.print_file."""
return self.repository.print_file(file, revision_id)
@needs_write_lock
def append_revision(self, *revision_ids):
"""See Branch.append_revision."""
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
for revision_id in revision_ids:
_mod_revision.check_not_reserved_id(revision_id)
mutter("add {%s} to revision-history" % revision_id)
rev_history = self.revision_history()
rev_history.extend(revision_ids)
self.set_revision_history(rev_history)
def _write_revision_history(self, history):
"""Factored out of set_revision_history.
This performs the actual writing to disk.
It is intended to be called by BzrBranch5.set_revision_history."""
self.control_files.put_bytes(
'revision-history', '\n'.join(history))
@needs_write_lock
def set_revision_history(self, rev_history):
"""See Branch.set_revision_history."""
rev_history = [osutils.safe_revision_id(r) for r in rev_history]
self._write_revision_history(rev_history)
self._cache_revision_history(rev_history)
for hook in Branch.hooks['set_rh']:
hook(self, rev_history)
@needs_write_lock
def set_last_revision_info(self, revno, revision_id):
revision_id = osutils.safe_revision_id(revision_id)
history = self._lefthand_history(revision_id)
assert len(history) == revno, '%d != %d' % (len(history), revno)
self.set_revision_history(history)
def _gen_revision_history(self):
history = self.control_files.get('revision-history').read().split('\n')
if history[-1:] == ['']:
# There shouldn't be a trailing newline, but just in case.
history.pop()
return history
def _lefthand_history(self, revision_id, last_rev=None,
other_branch=None):
# stop_revision must be a descendant of last_revision
stop_graph = self.repository.get_revision_graph(revision_id)
if last_rev is not None and last_rev not in stop_graph:
# our previous tip is not merged into stop_revision
raise errors.DivergedBranches(self, other_branch)
# make a new revision history from the graph
current_rev_id = revision_id
new_history = []
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
new_history.append(current_rev_id)
current_rev_id_parents = stop_graph[current_rev_id]
try:
current_rev_id = current_rev_id_parents[0]
except IndexError:
current_rev_id = None
new_history.reverse()
return new_history
@needs_write_lock
def generate_revision_history(self, revision_id, last_rev=None,
other_branch=None):
"""Create a new revision history that will finish with revision_id.
:param revision_id: the new tip to use.
:param last_rev: The previous last_revision. If not None, then this
must be a ancestory of revision_id, or DivergedBranches is raised.
:param other_branch: The other branch that DivergedBranches should
raise with respect to.
"""
revision_id = osutils.safe_revision_id(revision_id)
self.set_revision_history(self._lefthand_history(revision_id,
last_rev, other_branch))
@needs_write_lock
def update_revisions(self, other, stop_revision=None):
"""See Branch.update_revisions."""
other.lock_read()
try:
if stop_revision is None:
stop_revision = other.last_revision()
if stop_revision is None:
# if there are no commits, we're done.
return
else:
stop_revision = osutils.safe_revision_id(stop_revision)
# whats the current last revision, before we fetch [and change it
# possibly]
last_rev = self.last_revision()
# we fetch here regardless of whether we need to so that we pickup
# filled in ghosts.
self.fetch(other, stop_revision)
my_ancestry = self.repository.get_ancestry(last_rev)
if stop_revision in my_ancestry:
# last_revision is a descendant of stop_revision
return
self.generate_revision_history(stop_revision, last_rev=last_rev,
other_branch=other)
finally:
other.unlock()
def basis_tree(self):
"""See Branch.basis_tree."""
return self.repository.revision_tree(self.last_revision())
@deprecated_method(zero_eight)
def working_tree(self):
"""Create a Working tree object for this branch."""
from bzrlib.transport.local import LocalTransport
if (self.base.find('://') != -1 or
not isinstance(self._transport, LocalTransport)):
raise NoWorkingTree(self.base)
return self.bzrdir.open_workingtree()
@needs_write_lock
def pull(self, source, overwrite=False, stop_revision=None,
_hook_master=None, _run_hooks=True):
"""See Branch.pull.
:param _hook_master: Private parameter - set the branch to
be supplied as the master to push hooks.
:param _run_hooks: Private parameter - allow disabling of
hooks, used when pushing to a master branch.
"""
result = PullResult()
result.source_branch = source
result.target_branch = self
source.lock_read()
try:
result.old_revno, result.old_revid = self.last_revision_info()
try:
self.update_revisions(source, stop_revision)
except DivergedBranches:
if not overwrite:
raise
if overwrite:
if stop_revision is None:
stop_revision = source.last_revision()
self.generate_revision_history(stop_revision)
result.tag_conflicts = source.tags.merge_to(self.tags)
result.new_revno, result.new_revid = self.last_revision_info()
if _hook_master:
result.master_branch = _hook_master
result.local_branch = self
else:
result.master_branch = self
result.local_branch = None
if _run_hooks:
for hook in Branch.hooks['post_pull']:
hook(result)
finally:
source.unlock()
return result
def _get_parent_location(self):
_locs = ['parent', 'pull', 'x-pull']
for l in _locs:
try:
return self.control_files.get(l).read().strip('\n')
except NoSuchFile:
pass
return None
@needs_read_lock
def push(self, target, overwrite=False, stop_revision=None,
_hook_master=None, _run_hooks=True):
"""See Branch.push.
:param _hook_master: Private parameter - set the branch to
be supplied as the master to push hooks.
:param _run_hooks: Private parameter - allow disabling of
hooks, used when pushing to a master branch.
"""
result = PushResult()
result.source_branch = self
result.target_branch = target
target.lock_write()
try:
result.old_revno, result.old_revid = target.last_revision_info()
try:
target.update_revisions(self, stop_revision)
except DivergedBranches:
if not overwrite:
raise
if overwrite:
target.set_revision_history(self.revision_history())
result.tag_conflicts = self.tags.merge_to(target.tags)
result.new_revno, result.new_revid = target.last_revision_info()
if _hook_master:
result.master_branch = _hook_master
result.local_branch = target
else:
result.master_branch = target
result.local_branch = None
if _run_hooks:
for hook in Branch.hooks['post_push']:
hook(result)
finally:
target.unlock()
return result
def get_parent(self):
"""See Branch.get_parent."""
assert self.base[-1] == '/'
parent = self._get_parent_location()
if parent is None:
return parent
# This is an old-format absolute path to a local branch
# turn it into a url
if parent.startswith('/'):
parent = urlutils.local_path_to_url(parent.decode('utf8'))
try:
return urlutils.join(self.base[:-1], parent)
except errors.InvalidURLJoin, e:
raise errors.InaccessibleParent(parent, self.base)
def get_push_location(self):
"""See Branch.get_push_location."""
push_loc = self.get_config().get_user_option('push_location')
return push_loc
def set_push_location(self, location):
"""See Branch.set_push_location."""
self.get_config().set_user_option(
'push_location', location,
store=_mod_config.STORE_LOCATION_NORECURSE)
@needs_write_lock
def set_parent(self, url):
"""See Branch.set_parent."""
# TODO: Maybe delete old location files?
# URLs should never be unicode, even on the local fs,
# FIXUP this and get_parent in a future branch format bump:
# read and rewrite the file, and have the new format code read
# using .get not .get_utf8. RBC 20060125
if url is not None:
if isinstance(url, unicode):
try:
url = url.encode('ascii')
except UnicodeEncodeError:
raise bzrlib.errors.InvalidURL(url,
"Urls must be 7-bit ascii, "
"use bzrlib.urlutils.escape")
url = urlutils.relative_url(self.base, url)
self._set_parent_location(url)
def _set_parent_location(self, url):
if url is None:
self.control_files._transport.delete('parent')
else:
assert isinstance(url, str)
self.control_files.put_bytes('parent', url + '\n')
@deprecated_function(zero_nine)
def tree_config(self):
"""DEPRECATED; call get_config instead.
TreeConfig has become part of BranchConfig."""
return TreeConfig(self)
class BzrBranch5(BzrBranch):
"""A format 5 branch. This supports new features over plan branches.
It has support for a master_branch which is the data for bound branches.
"""
def __init__(self,
_format,
_control_files,
a_bzrdir,
_repository):
super(BzrBranch5, self).__init__(_format=_format,
_control_files=_control_files,
a_bzrdir=a_bzrdir,
_repository=_repository)
@needs_write_lock
def pull(self, source, overwrite=False, stop_revision=None,
_run_hooks=True):
"""Extends branch.pull to be bound branch aware.
:param _run_hooks: Private parameter used to force hook running
off during bound branch double-pushing.
"""
bound_location = self.get_bound_location()
master_branch = None
if bound_location and source.base != bound_location:
# not pulling from master, so we need to update master.
master_branch = self.get_master_branch()
master_branch.lock_write()
try:
if master_branch:
# pull from source into master.
master_branch.pull(source, overwrite, stop_revision,
_run_hooks=False)
return super(BzrBranch5, self).pull(source, overwrite,
stop_revision, _hook_master=master_branch,
_run_hooks=_run_hooks)
finally:
if master_branch:
master_branch.unlock()
@needs_read_lock
def push(self, target, overwrite=False, stop_revision=None):
"""Updates branch.push to be bound branch aware."""
bound_location = target.get_bound_location()
master_branch = None
if bound_location and target.base != bound_location:
# not pushing to master, so we need to update master.
master_branch = target.get_master_branch()
master_branch.lock_write()
try:
if master_branch:
# push into the master from this branch.
super(BzrBranch5, self).push(master_branch, overwrite,
stop_revision, _run_hooks=False)
# and push into the target branch from this. Note that we push from
# this branch again, because its considered the highest bandwidth
# repository.
return super(BzrBranch5, self).push(target, overwrite,
stop_revision, _hook_master=master_branch)
finally:
if master_branch:
master_branch.unlock()
def get_bound_location(self):
try:
return self.control_files.get_utf8('bound').read()[:-1]
except errors.NoSuchFile:
return None
@needs_read_lock
def get_master_branch(self):
"""Return the branch we are bound to.
:return: Either a Branch, or None
This could memoise the branch, but if thats done
it must be revalidated on each new lock.
So for now we just don't memoise it.
# RBC 20060304 review this decision.
"""
bound_loc = self.get_bound_location()
if not bound_loc:
return None
try:
return Branch.open(bound_loc)
except (errors.NotBranchError, errors.ConnectionError), e:
raise errors.BoundBranchConnectionFailure(
self, bound_loc, e)
@needs_write_lock
def set_bound_location(self, location):
"""Set the target where this branch is bound to.
:param location: URL to the target branch
"""
if location:
self.control_files.put_utf8('bound', location+'\n')
else:
try:
self.control_files._transport.delete('bound')
except NoSuchFile:
return False
return True
@needs_write_lock
def bind(self, other):
"""Bind this branch to the branch other.
This does not push or pull data between the branches, though it does
check for divergence to raise an error when the branches are not
either the same, or one a prefix of the other. That behaviour may not
be useful, so that check may be removed in future.
:param other: The branch to bind to
:type other: Branch
"""
# TODO: jam 20051230 Consider checking if the target is bound
# It is debatable whether you should be able to bind to
# a branch which is itself bound.
# Committing is obviously forbidden,
# but binding itself may not be.
# Since we *have* to check at commit time, we don't
# *need* to check here
# we want to raise diverged if:
# last_rev is not in the other_last_rev history, AND
# other_last_rev is not in our history, and do it without pulling
# history around
last_rev = self.last_revision()
if last_rev is not None:
other.lock_read()
try:
other_last_rev = other.last_revision()
if other_last_rev is not None:
# neither branch is new, we have to do some work to
# ascertain diversion.
remote_graph = other.repository.get_revision_graph(
other_last_rev)
local_graph = self.repository.get_revision_graph(last_rev)
if (last_rev not in remote_graph and
other_last_rev not in local_graph):
raise errors.DivergedBranches(self, other)
finally:
other.unlock()
self.set_bound_location(other.base)
@needs_write_lock
def unbind(self):
"""If bound, unbind"""
return self.set_bound_location(None)
@needs_write_lock
def update(self):
"""Synchronise this branch with the master branch if any.
:return: None or the last_revision that was pivoted out during the
update.
"""
master = self.get_master_branch()
if master is not None:
old_tip = self.last_revision()
self.pull(master, overwrite=True)
if old_tip in self.repository.get_ancestry(self.last_revision()):
return None
return old_tip
return None
class BzrBranchExperimental(BzrBranch5):
"""Bzr experimental branch format
This format has:
- a revision-history file.
- a format string
- a lock dir guarding the branch itself
- all of this stored in a branch/ subdirectory
- works with shared repositories.
- a tag dictionary in the branch
This format is new in bzr 0.15, but shouldn't be used for real data,
only for testing.
This class acts as it's own BranchFormat.
"""
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
@classmethod
def get_format_string(cls):
"""See BranchFormat.get_format_string()."""
return "Bazaar-NG branch format experimental\n"
@classmethod
def get_format_description(cls):
"""See BranchFormat.get_format_description()."""
return "Experimental branch format"
@classmethod
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
lock_class):
branch_transport = a_bzrdir.get_branch_transport(cls)
control_files = lockable_files.LockableFiles(branch_transport,
lock_filename, lock_class)
control_files.create_lock()
control_files.lock_write()
try:
for filename, content in utf8_files:
control_files.put_utf8(filename, content)
finally:
control_files.unlock()
@classmethod
def initialize(cls, a_bzrdir):
"""Create a branch of this format in a_bzrdir."""
utf8_files = [('format', cls.get_format_string()),
('revision-history', ''),
('branch-name', ''),
('tags', ''),
]
cls._initialize_control_files(a_bzrdir, utf8_files,
'lock', lockdir.LockDir)
return cls.open(a_bzrdir, _found=True)
@classmethod
def open(cls, a_bzrdir, _found=False):
"""Return the branch object for a_bzrdir
_found is a private parameter, do not use it. It is used to indicate
if format probing has already be done.
"""
if not _found:
format = BranchFormat.find_format(a_bzrdir)
assert format.__class__ == cls
transport = a_bzrdir.get_branch_transport(None)
control_files = lockable_files.LockableFiles(transport, 'lock',
lockdir.LockDir)
return cls(_format=cls,
_control_files=control_files,
a_bzrdir=a_bzrdir,
_repository=a_bzrdir.find_repository())
@classmethod
def is_supported(cls):
return True
def _make_tags(self):
return BasicTags(self)
@classmethod
def supports_tags(cls):
return True
BranchFormat.register_format(BzrBranchExperimental)
class BzrBranch6(BzrBranch5):
@needs_read_lock
def last_revision_info(self):
revision_string = self.control_files.get('last-revision').read()
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
revision_id = cache_utf8.get_cached_utf8(revision_id)
revno = int(revno)
return revno, revision_id
def last_revision(self):
"""Return last revision id, or None"""
revision_id = self.last_revision_info()[1]
if revision_id == _mod_revision.NULL_REVISION:
revision_id = None
return revision_id
def _write_last_revision_info(self, revno, revision_id):
"""Simply write out the revision id, with no checks.
Use set_last_revision_info to perform this safely.
Does not update the revision_history cache.
Intended to be called by set_last_revision_info and
_write_revision_history.
"""
if revision_id is None:
revision_id = 'null:'
out_string = '%d %s\n' % (revno, revision_id)
self.control_files.put_bytes('last-revision', out_string)
@needs_write_lock
def set_last_revision_info(self, revno, revision_id):
revision_id = osutils.safe_revision_id(revision_id)
if self._get_append_revisions_only():
self._check_history_violation(revision_id)
self._write_last_revision_info(revno, revision_id)
self._clear_cached_state()
def _check_history_violation(self, revision_id):
last_revision = self.last_revision()
if last_revision is None:
return
if last_revision not in self._lefthand_history(revision_id):
raise errors.AppendRevisionsOnlyViolation(self.base)
def _gen_revision_history(self):
"""Generate the revision history from last revision
"""
history = list(self.repository.iter_reverse_revision_history(
self.last_revision()))
history.reverse()
return history
def _write_revision_history(self, history):
"""Factored out of set_revision_history.
This performs the actual writing to disk, with format-specific checks.
It is intended to be called by BzrBranch5.set_revision_history.
"""
if len(history) == 0:
last_revision = 'null:'
else:
if history != self._lefthand_history(history[-1]):
raise errors.NotLefthandHistory(history)
last_revision = history[-1]
if self._get_append_revisions_only():
self._check_history_violation(last_revision)
self._write_last_revision_info(len(history), last_revision)
@needs_write_lock
def append_revision(self, *revision_ids):
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
if len(revision_ids) == 0:
return
prev_revno, prev_revision = self.last_revision_info()
for revision in self.repository.get_revisions(revision_ids):
if prev_revision == _mod_revision.NULL_REVISION:
if revision.parent_ids != []:
raise errors.NotLeftParentDescendant(self, prev_revision,
revision.revision_id)
else:
if revision.parent_ids[0] != prev_revision:
raise errors.NotLeftParentDescendant(self, prev_revision,
revision.revision_id)
prev_revision = revision.revision_id
self.set_last_revision_info(prev_revno + len(revision_ids),
revision_ids[-1])
@needs_write_lock
def _set_parent_location(self, url):
"""Set the parent branch"""
self._set_config_location('parent_location', url, make_relative=True)
@needs_read_lock
def _get_parent_location(self):
"""Set the parent branch"""
return self._get_config_location('parent_location')
def set_push_location(self, location):
"""See Branch.set_push_location."""
self._set_config_location('push_location', location)
def set_bound_location(self, location):
"""See Branch.set_push_location."""
result = None
config = self.get_config()
if location is None:
if config.get_user_option('bound') != 'True':
return False
else:
config.set_user_option('bound', 'False')
return True
else:
self._set_config_location('bound_location', location,
config=config)
config.set_user_option('bound', 'True')
return True
def _get_bound_location(self, bound):
"""Return the bound location in the config file.
Return None if the bound parameter does not match"""
config = self.get_config()
config_bound = (config.get_user_option('bound') == 'True')
if config_bound != bound:
return None
return self._get_config_location('bound_location', config=config)
def get_bound_location(self):
"""See Branch.set_push_location."""
return self._get_bound_location(True)
def get_old_bound_location(self):
"""See Branch.get_old_bound_location"""
return self._get_bound_location(False)
def set_append_revisions_only(self, enabled):
if enabled:
value = 'True'
else:
value = 'False'
self.get_config().set_user_option('append_revisions_only', value)
def _get_append_revisions_only(self):
value = self.get_config().get_user_option('append_revisions_only')
return value == 'True'
def _synchronize_history(self, destination, revision_id):
"""Synchronize last revision and revision history between branches.
This version is most efficient when the destination is also a
BzrBranch6, but works for BzrBranch5, as long as the destination's
repository contains all the lefthand ancestors of the intended
last_revision. If not, set_last_revision_info will fail.
:param destination: The branch to copy the history into
:param revision_id: The revision-id to truncate history at. May
be None to copy complete history.
"""
if revision_id is None:
revno, revision_id = self.last_revision_info()
else:
revno = self.revision_id_to_revno(revision_id)
destination.set_last_revision_info(revno, revision_id)
def _make_tags(self):
return BasicTags(self)
class BranchTestProviderAdapter(object):
"""A tool to generate a suite testing multiple branch formats at once.
This is done by copying the test once for each transport and injecting
the transport_server, transport_readonly_server, and branch_format
classes into each copy. Each copy is also given a new id() to make it
easy to identify.
"""
def __init__(self, transport_server, transport_readonly_server, formats):
self._transport_server = transport_server
self._transport_readonly_server = transport_readonly_server
self._formats = formats
def adapt(self, test):
result = TestSuite()
for branch_format, bzrdir_format in self._formats:
new_test = deepcopy(test)
new_test.transport_server = self._transport_server
new_test.transport_readonly_server = self._transport_readonly_server
new_test.bzrdir_format = bzrdir_format
new_test.branch_format = branch_format
def make_new_test_id():
# the format can be either a class or an instance
name = getattr(branch_format, '__name__',
branch_format.__class__.__name__)
new_id = "%s(%s)" % (new_test.id(), name)
return lambda: new_id
new_test.id = make_new_test_id()
result.addTest(new_test)
return result
######################################################################
# results of operations
class _Result(object):
def _show_tag_conficts(self, to_file):
if not getattr(self, 'tag_conflicts', None):
return
to_file.write('Conflicting tags:\n')
for name, value1, value2 in self.tag_conflicts:
to_file.write(' %s\n' % (name, ))
class PullResult(_Result):
"""Result of a Branch.pull operation.
:ivar old_revno: Revision number before pull.
:ivar new_revno: Revision number after pull.
:ivar old_revid: Tip revision id before pull.
:ivar new_revid: Tip revision id after pull.
:ivar source_branch: Source (local) branch object.
:ivar master_branch: Master branch of the target, or None.
:ivar target_branch: Target/destination branch object.
"""
def __int__(self):
# DEPRECATED: pull used to return the change in revno
return self.new_revno - self.old_revno
def report(self, to_file):
if self.old_revid == self.new_revid:
to_file.write('No revisions to pull.\n')
else:
to_file.write('Now on revision %d.\n' % self.new_revno)
self._show_tag_conficts(to_file)
class PushResult(_Result):
"""Result of a Branch.push operation.
:ivar old_revno: Revision number before push.
:ivar new_revno: Revision number after push.
:ivar old_revid: Tip revision id before push.
:ivar new_revid: Tip revision id after push.
:ivar source_branch: Source branch object.
:ivar master_branch: Master branch of the target, or None.
:ivar target_branch: Target/destination branch object.
"""
def __int__(self):
# DEPRECATED: push used to return the change in revno
return self.new_revno - self.old_revno
def report(self, to_file):
"""Write a human-readable description of the result."""
if self.old_revid == self.new_revid:
to_file.write('No new revisions to push.\n')
else:
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
self._show_tag_conficts(to_file)
class BranchCheckResult(object):
"""Results of checking branch consistency.
:see: Branch.check
"""
def __init__(self, branch):
self.branch = branch
def report_results(self, verbose):
"""Report the check results via trace.note.
:param verbose: Requests more detailed display of what was checked,
if any.
"""
note('checked branch %s format %s',
self.branch.base,
self.branch._format)
class Converter5to6(object):
"""Perform an in-place upgrade of format 5 to format 6"""
def convert(self, branch):
# Data for 5 and 6 can peacefully coexist.
format = BzrBranchFormat6()
new_branch = format.open(branch.bzrdir, _found=True)
# Copy source data into target
new_branch.set_last_revision_info(*branch.last_revision_info())
new_branch.set_parent(branch.get_parent())
new_branch.set_bound_location(branch.get_bound_location())
new_branch.set_push_location(branch.get_push_location())
# New branch has no tags by default
new_branch.tags._set_tag_dict({})
# Copying done; now update target format
new_branch.control_files.put_utf8('format',
format.get_format_string())
# Clean up old files
new_branch.control_files._transport.delete('revision-history')
try:
branch.set_parent(None)
except NoSuchFile:
pass
branch.set_bound_location(None)
|