/usr/lib/python2.7/dist-packages/mercurial/revlog.py is in mercurial-common 4.5.3-1ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 | # revlog.py - storage back-end for mercurial
#
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""Storage back-end for Mercurial.
This provides efficient delta storage with O(1) retrieve and append
and O(changes) merge between branches.
"""
from __future__ import absolute_import
import binascii
import collections
import errno
import hashlib
import heapq
import os
import struct
import zlib
# import stuff from node for others to import from revlog
from .node import (
bin,
hex,
nullid,
nullrev,
wdirhex,
wdirid,
wdirrev,
)
from .i18n import _
from .thirdparty import (
attr,
)
from . import (
ancestor,
error,
mdiff,
policy,
pycompat,
templatefilters,
util,
)
parsers = policy.importmod(r'parsers')
# Aliased for performance.
_zlibdecompress = zlib.decompress
# revlog header flags
REVLOGV0 = 0
REVLOGV1 = 1
# Dummy value until file format is finalized.
# Reminder: change the bounds check in revlog.__init__ when this is changed.
REVLOGV2 = 0xDEAD
FLAG_INLINE_DATA = (1 << 16)
FLAG_GENERALDELTA = (1 << 17)
REVLOG_DEFAULT_FLAGS = FLAG_INLINE_DATA
REVLOG_DEFAULT_FORMAT = REVLOGV1
REVLOG_DEFAULT_VERSION = REVLOG_DEFAULT_FORMAT | REVLOG_DEFAULT_FLAGS
REVLOGV1_FLAGS = FLAG_INLINE_DATA | FLAG_GENERALDELTA
REVLOGV2_FLAGS = REVLOGV1_FLAGS
# revlog index flags
REVIDX_ISCENSORED = (1 << 15) # revision has censor metadata, must be verified
REVIDX_ELLIPSIS = (1 << 14) # revision hash does not match data (narrowhg)
REVIDX_EXTSTORED = (1 << 13) # revision data is stored externally
REVIDX_DEFAULT_FLAGS = 0
# stable order in which flags need to be processed and their processors applied
REVIDX_FLAGS_ORDER = [
REVIDX_ISCENSORED,
REVIDX_ELLIPSIS,
REVIDX_EXTSTORED,
]
REVIDX_KNOWN_FLAGS = util.bitsfrom(REVIDX_FLAGS_ORDER)
# bitmark for flags that could cause rawdata content change
REVIDX_RAWTEXT_CHANGING_FLAGS = REVIDX_ISCENSORED | REVIDX_EXTSTORED
# max size of revlog with inline data
_maxinline = 131072
_chunksize = 1048576
RevlogError = error.RevlogError
LookupError = error.LookupError
CensoredNodeError = error.CensoredNodeError
ProgrammingError = error.ProgrammingError
# Store flag processors (cf. 'addflagprocessor()' to register)
_flagprocessors = {
REVIDX_ISCENSORED: None,
}
def addflagprocessor(flag, processor):
"""Register a flag processor on a revision data flag.
Invariant:
- Flags need to be defined in REVIDX_KNOWN_FLAGS and REVIDX_FLAGS_ORDER,
and REVIDX_RAWTEXT_CHANGING_FLAGS if they can alter rawtext.
- Only one flag processor can be registered on a specific flag.
- flagprocessors must be 3-tuples of functions (read, write, raw) with the
following signatures:
- (read) f(self, rawtext) -> text, bool
- (write) f(self, text) -> rawtext, bool
- (raw) f(self, rawtext) -> bool
"text" is presented to the user. "rawtext" is stored in revlog data, not
directly visible to the user.
The boolean returned by these transforms is used to determine whether
the returned text can be used for hash integrity checking. For example,
if "write" returns False, then "text" is used to generate hash. If
"write" returns True, that basically means "rawtext" returned by "write"
should be used to generate hash. Usually, "write" and "read" return
different booleans. And "raw" returns a same boolean as "write".
Note: The 'raw' transform is used for changegroup generation and in some
debug commands. In this case the transform only indicates whether the
contents can be used for hash integrity checks.
"""
if not flag & REVIDX_KNOWN_FLAGS:
msg = _("cannot register processor on unknown flag '%#x'.") % (flag)
raise ProgrammingError(msg)
if flag not in REVIDX_FLAGS_ORDER:
msg = _("flag '%#x' undefined in REVIDX_FLAGS_ORDER.") % (flag)
raise ProgrammingError(msg)
if flag in _flagprocessors:
msg = _("cannot register multiple processors on flag '%#x'.") % (flag)
raise error.Abort(msg)
_flagprocessors[flag] = processor
def getoffset(q):
return int(q >> 16)
def gettype(q):
return int(q & 0xFFFF)
def offset_type(offset, type):
if (type & ~REVIDX_KNOWN_FLAGS) != 0:
raise ValueError('unknown revlog index flags')
return int(int(offset) << 16 | type)
_nullhash = hashlib.sha1(nullid)
def hash(text, p1, p2):
"""generate a hash from the given text and its parent hashes
This hash combines both the current file contents and its history
in a manner that makes it easy to distinguish nodes with the same
content in the revision graph.
"""
# As of now, if one of the parent node is null, p2 is null
if p2 == nullid:
# deep copy of a hash is faster than creating one
s = _nullhash.copy()
s.update(p1)
else:
# none of the parent nodes are nullid
if p1 < p2:
a = p1
b = p2
else:
a = p2
b = p1
s = hashlib.sha1(a)
s.update(b)
s.update(text)
return s.digest()
def _trimchunk(revlog, revs, startidx, endidx=None):
"""returns revs[startidx:endidx] without empty trailing revs
"""
length = revlog.length
if endidx is None:
endidx = len(revs)
# Trim empty revs at the end, but never the very first revision of a chain
while endidx > 1 and endidx > startidx and length(revs[endidx - 1]) == 0:
endidx -= 1
return revs[startidx:endidx]
def _slicechunk(revlog, revs):
"""slice revs to reduce the amount of unrelated data to be read from disk.
``revs`` is sliced into groups that should be read in one time.
Assume that revs are sorted.
"""
start = revlog.start
length = revlog.length
if len(revs) <= 1:
yield revs
return
startbyte = start(revs[0])
endbyte = start(revs[-1]) + length(revs[-1])
readdata = deltachainspan = endbyte - startbyte
chainpayload = sum(length(r) for r in revs)
if deltachainspan:
density = chainpayload / float(deltachainspan)
else:
density = 1.0
# Store the gaps in a heap to have them sorted by decreasing size
gapsheap = []
heapq.heapify(gapsheap)
prevend = None
for i, rev in enumerate(revs):
revstart = start(rev)
revlen = length(rev)
# Skip empty revisions to form larger holes
if revlen == 0:
continue
if prevend is not None:
gapsize = revstart - prevend
# only consider holes that are large enough
if gapsize > revlog._srmingapsize:
heapq.heappush(gapsheap, (-gapsize, i))
prevend = revstart + revlen
# Collect the indices of the largest holes until the density is acceptable
indicesheap = []
heapq.heapify(indicesheap)
while gapsheap and density < revlog._srdensitythreshold:
oppgapsize, gapidx = heapq.heappop(gapsheap)
heapq.heappush(indicesheap, gapidx)
# the gap sizes are stored as negatives to be sorted decreasingly
# by the heap
readdata -= (-oppgapsize)
if readdata > 0:
density = chainpayload / float(readdata)
else:
density = 1.0
# Cut the revs at collected indices
previdx = 0
while indicesheap:
idx = heapq.heappop(indicesheap)
chunk = _trimchunk(revlog, revs, previdx, idx)
if chunk:
yield chunk
previdx = idx
chunk = _trimchunk(revlog, revs, previdx)
if chunk:
yield chunk
@attr.s(slots=True, frozen=True)
class _deltainfo(object):
distance = attr.ib()
deltalen = attr.ib()
data = attr.ib()
base = attr.ib()
chainbase = attr.ib()
chainlen = attr.ib()
compresseddeltalen = attr.ib()
class _deltacomputer(object):
def __init__(self, revlog):
self.revlog = revlog
def _getcandidaterevs(self, p1, p2, cachedelta):
"""
Provides revisions that present an interest to be diffed against,
grouped by level of easiness.
"""
revlog = self.revlog
curr = len(revlog)
prev = curr - 1
p1r, p2r = revlog.rev(p1), revlog.rev(p2)
# should we try to build a delta?
if prev != nullrev and revlog.storedeltachains:
tested = set()
# This condition is true most of the time when processing
# changegroup data into a generaldelta repo. The only time it
# isn't true is if this is the first revision in a delta chain
# or if ``format.generaldelta=true`` disabled ``lazydeltabase``.
if cachedelta and revlog._generaldelta and revlog._lazydeltabase:
# Assume what we received from the server is a good choice
# build delta will reuse the cache
yield (cachedelta[0],)
tested.add(cachedelta[0])
if revlog._generaldelta:
# exclude already lazy tested base if any
parents = [p for p in (p1r, p2r)
if p != nullrev and p not in tested]
if parents and not revlog._aggressivemergedeltas:
# Pick whichever parent is closer to us (to minimize the
# chance of having to build a fulltext).
parents = [max(parents)]
tested.update(parents)
yield parents
if prev not in tested:
# other approach failed try against prev to hopefully save us a
# fulltext.
yield (prev,)
def buildtext(self, revinfo, fh):
"""Builds a fulltext version of a revision
revinfo: _revisioninfo instance that contains all needed info
fh: file handle to either the .i or the .d revlog file,
depending on whether it is inlined or not
"""
btext = revinfo.btext
if btext[0] is not None:
return btext[0]
revlog = self.revlog
cachedelta = revinfo.cachedelta
flags = revinfo.flags
node = revinfo.node
baserev = cachedelta[0]
delta = cachedelta[1]
# special case deltas which replace entire base; no need to decode
# base revision. this neatly avoids censored bases, which throw when
# they're decoded.
hlen = struct.calcsize(">lll")
if delta[:hlen] == mdiff.replacediffheader(revlog.rawsize(baserev),
len(delta) - hlen):
btext[0] = delta[hlen:]
else:
# deltabase is rawtext before changed by flag processors, which is
# equivalent to non-raw text
basetext = revlog.revision(baserev, _df=fh, raw=False)
btext[0] = mdiff.patch(basetext, delta)
try:
res = revlog._processflags(btext[0], flags, 'read', raw=True)
btext[0], validatehash = res
if validatehash:
revlog.checkhash(btext[0], node, p1=revinfo.p1, p2=revinfo.p2)
if flags & REVIDX_ISCENSORED:
raise RevlogError(_('node %s is not censored') % node)
except CensoredNodeError:
# must pass the censored index flag to add censored revisions
if not flags & REVIDX_ISCENSORED:
raise
return btext[0]
def _builddeltadiff(self, base, revinfo, fh):
revlog = self.revlog
t = self.buildtext(revinfo, fh)
if revlog.iscensored(base):
# deltas based on a censored revision must replace the
# full content in one patch, so delta works everywhere
header = mdiff.replacediffheader(revlog.rawsize(base), len(t))
delta = header + t
else:
ptext = revlog.revision(base, _df=fh, raw=True)
delta = mdiff.textdiff(ptext, t)
return delta
def _builddeltainfo(self, revinfo, base, fh):
# can we use the cached delta?
if revinfo.cachedelta and revinfo.cachedelta[0] == base:
delta = revinfo.cachedelta[1]
else:
delta = self._builddeltadiff(base, revinfo, fh)
revlog = self.revlog
header, data = revlog.compress(delta)
deltalen = len(header) + len(data)
chainbase = revlog.chainbase(base)
offset = revlog.end(len(revlog) - 1)
dist = deltalen + offset - revlog.start(chainbase)
if revlog._generaldelta:
deltabase = base
else:
deltabase = chainbase
chainlen, compresseddeltalen = revlog._chaininfo(base)
chainlen += 1
compresseddeltalen += deltalen
return _deltainfo(dist, deltalen, (header, data), deltabase,
chainbase, chainlen, compresseddeltalen)
def finddeltainfo(self, revinfo, fh):
"""Find an acceptable delta against a candidate revision
revinfo: information about the revision (instance of _revisioninfo)
fh: file handle to either the .i or the .d revlog file,
depending on whether it is inlined or not
Returns the first acceptable candidate revision, as ordered by
_getcandidaterevs
"""
cachedelta = revinfo.cachedelta
p1 = revinfo.p1
p2 = revinfo.p2
revlog = self.revlog
deltainfo = None
for candidaterevs in self._getcandidaterevs(p1, p2, cachedelta):
nominateddeltas = []
for candidaterev in candidaterevs:
# no delta for rawtext-changing revs (see "candelta" for why)
if revlog.flags(candidaterev) & REVIDX_RAWTEXT_CHANGING_FLAGS:
continue
candidatedelta = self._builddeltainfo(revinfo, candidaterev, fh)
if revlog._isgooddeltainfo(candidatedelta, revinfo.textlen):
nominateddeltas.append(candidatedelta)
if nominateddeltas:
deltainfo = min(nominateddeltas, key=lambda x: x.deltalen)
break
return deltainfo
@attr.s(slots=True, frozen=True)
class _revisioninfo(object):
"""Information about a revision that allows building its fulltext
node: expected hash of the revision
p1, p2: parent revs of the revision
btext: built text cache consisting of a one-element list
cachedelta: (baserev, uncompressed_delta) or None
flags: flags associated to the revision storage
One of btext[0] or cachedelta must be set.
"""
node = attr.ib()
p1 = attr.ib()
p2 = attr.ib()
btext = attr.ib()
textlen = attr.ib()
cachedelta = attr.ib()
flags = attr.ib()
# index v0:
# 4 bytes: offset
# 4 bytes: compressed length
# 4 bytes: base rev
# 4 bytes: link rev
# 20 bytes: parent 1 nodeid
# 20 bytes: parent 2 nodeid
# 20 bytes: nodeid
indexformatv0 = struct.Struct(">4l20s20s20s")
indexformatv0_pack = indexformatv0.pack
indexformatv0_unpack = indexformatv0.unpack
class revlogoldio(object):
def __init__(self):
self.size = indexformatv0.size
def parseindex(self, data, inline):
s = self.size
index = []
nodemap = {nullid: nullrev}
n = off = 0
l = len(data)
while off + s <= l:
cur = data[off:off + s]
off += s
e = indexformatv0_unpack(cur)
# transform to revlogv1 format
e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3],
nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6])
index.append(e2)
nodemap[e[6]] = n
n += 1
# add the magic null revision at -1
index.append((0, 0, 0, -1, -1, -1, -1, nullid))
return index, nodemap, None
def packentry(self, entry, node, version, rev):
if gettype(entry[0]):
raise RevlogError(_('index entry flags need revlog version 1'))
e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4],
node(entry[5]), node(entry[6]), entry[7])
return indexformatv0_pack(*e2)
# index ng:
# 6 bytes: offset
# 2 bytes: flags
# 4 bytes: compressed length
# 4 bytes: uncompressed length
# 4 bytes: base rev
# 4 bytes: link rev
# 4 bytes: parent 1 rev
# 4 bytes: parent 2 rev
# 32 bytes: nodeid
indexformatng = struct.Struct(">Qiiiiii20s12x")
indexformatng_pack = indexformatng.pack
versionformat = struct.Struct(">I")
versionformat_pack = versionformat.pack
versionformat_unpack = versionformat.unpack
# corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
# signed integer)
_maxentrysize = 0x7fffffff
class revlogio(object):
def __init__(self):
self.size = indexformatng.size
def parseindex(self, data, inline):
# call the C implementation to parse the index data
index, cache = parsers.parse_index2(data, inline)
return index, getattr(index, 'nodemap', None), cache
def packentry(self, entry, node, version, rev):
p = indexformatng_pack(*entry)
if rev == 0:
p = versionformat_pack(version) + p[4:]
return p
class revlog(object):
"""
the underlying revision storage object
A revlog consists of two parts, an index and the revision data.
The index is a file with a fixed record size containing
information on each revision, including its nodeid (hash), the
nodeids of its parents, the position and offset of its data within
the data file, and the revision it's based on. Finally, each entry
contains a linkrev entry that can serve as a pointer to external
data.
The revision data itself is a linear collection of data chunks.
Each chunk represents a revision and is usually represented as a
delta against the previous chunk. To bound lookup time, runs of
deltas are limited to about 2 times the length of the original
version data. This makes retrieval of a version proportional to
its size, or O(1) relative to the number of revisions.
Both pieces of the revlog are written to in an append-only
fashion, which means we never need to rewrite a file to insert or
remove data, and can use some simple techniques to avoid the need
for locking while reading.
If checkambig, indexfile is opened with checkambig=True at
writing, to avoid file stat ambiguity.
If mmaplargeindex is True, and an mmapindexthreshold is set, the
index will be mmapped rather than read if it is larger than the
configured threshold.
"""
def __init__(self, opener, indexfile, datafile=None, checkambig=False,
mmaplargeindex=False):
"""
create a revlog object
opener is a function that abstracts the file opening operation
and can be used to implement COW semantics or the like.
"""
self.indexfile = indexfile
self.datafile = datafile or (indexfile[:-2] + ".d")
self.opener = opener
# When True, indexfile is opened with checkambig=True at writing, to
# avoid file stat ambiguity.
self._checkambig = checkambig
# 3-tuple of (node, rev, text) for a raw revision.
self._cache = None
# Maps rev to chain base rev.
self._chainbasecache = util.lrucachedict(100)
# 2-tuple of (offset, data) of raw data from the revlog at an offset.
self._chunkcache = (0, '')
# How much data to read and cache into the raw revlog data cache.
self._chunkcachesize = 65536
self._maxchainlen = None
self._aggressivemergedeltas = False
self.index = []
# Mapping of partial identifiers to full nodes.
self._pcache = {}
# Mapping of revision integer to full node.
self._nodecache = {nullid: nullrev}
self._nodepos = None
self._compengine = 'zlib'
self._maxdeltachainspan = -1
self._withsparseread = False
self._srdensitythreshold = 0.25
self._srmingapsize = 262144
mmapindexthreshold = None
v = REVLOG_DEFAULT_VERSION
opts = getattr(opener, 'options', None)
if opts is not None:
if 'revlogv2' in opts:
# version 2 revlogs always use generaldelta.
v = REVLOGV2 | FLAG_GENERALDELTA | FLAG_INLINE_DATA
elif 'revlogv1' in opts:
if 'generaldelta' in opts:
v |= FLAG_GENERALDELTA
else:
v = 0
if 'chunkcachesize' in opts:
self._chunkcachesize = opts['chunkcachesize']
if 'maxchainlen' in opts:
self._maxchainlen = opts['maxchainlen']
if 'aggressivemergedeltas' in opts:
self._aggressivemergedeltas = opts['aggressivemergedeltas']
self._lazydeltabase = bool(opts.get('lazydeltabase', False))
if 'compengine' in opts:
self._compengine = opts['compengine']
if 'maxdeltachainspan' in opts:
self._maxdeltachainspan = opts['maxdeltachainspan']
if mmaplargeindex and 'mmapindexthreshold' in opts:
mmapindexthreshold = opts['mmapindexthreshold']
self._withsparseread = bool(opts.get('with-sparse-read', False))
if 'sparse-read-density-threshold' in opts:
self._srdensitythreshold = opts['sparse-read-density-threshold']
if 'sparse-read-min-gap-size' in opts:
self._srmingapsize = opts['sparse-read-min-gap-size']
if self._chunkcachesize <= 0:
raise RevlogError(_('revlog chunk cache size %r is not greater '
'than 0') % self._chunkcachesize)
elif self._chunkcachesize & (self._chunkcachesize - 1):
raise RevlogError(_('revlog chunk cache size %r is not a power '
'of 2') % self._chunkcachesize)
indexdata = ''
self._initempty = True
try:
f = self.opener(self.indexfile)
if (mmapindexthreshold is not None and
self.opener.fstat(f).st_size >= mmapindexthreshold):
indexdata = util.buffer(util.mmapread(f))
else:
indexdata = f.read()
f.close()
if len(indexdata) > 0:
v = versionformat_unpack(indexdata[:4])[0]
self._initempty = False
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
self.version = v
self._inline = v & FLAG_INLINE_DATA
self._generaldelta = v & FLAG_GENERALDELTA
flags = v & ~0xFFFF
fmt = v & 0xFFFF
if fmt == REVLOGV0:
if flags:
raise RevlogError(_('unknown flags (%#04x) in version %d '
'revlog %s') %
(flags >> 16, fmt, self.indexfile))
elif fmt == REVLOGV1:
if flags & ~REVLOGV1_FLAGS:
raise RevlogError(_('unknown flags (%#04x) in version %d '
'revlog %s') %
(flags >> 16, fmt, self.indexfile))
elif fmt == REVLOGV2:
if flags & ~REVLOGV2_FLAGS:
raise RevlogError(_('unknown flags (%#04x) in version %d '
'revlog %s') %
(flags >> 16, fmt, self.indexfile))
else:
raise RevlogError(_('unknown version (%d) in revlog %s') %
(fmt, self.indexfile))
self.storedeltachains = True
self._io = revlogio()
if self.version == REVLOGV0:
self._io = revlogoldio()
try:
d = self._io.parseindex(indexdata, self._inline)
except (ValueError, IndexError):
raise RevlogError(_("index %s is corrupted") % (self.indexfile))
self.index, nodemap, self._chunkcache = d
if nodemap is not None:
self.nodemap = self._nodecache = nodemap
if not self._chunkcache:
self._chunkclear()
# revnum -> (chain-length, sum-delta-length)
self._chaininfocache = {}
# revlog header -> revlog compressor
self._decompressors = {}
@util.propertycache
def _compressor(self):
return util.compengines[self._compengine].revlogcompressor()
def tip(self):
return self.node(len(self.index) - 2)
def __contains__(self, rev):
return 0 <= rev < len(self)
def __len__(self):
return len(self.index) - 1
def __iter__(self):
return iter(xrange(len(self)))
def revs(self, start=0, stop=None):
"""iterate over all rev in this revlog (from start to stop)"""
step = 1
if stop is not None:
if start > stop:
step = -1
stop += step
else:
stop = len(self)
return xrange(start, stop, step)
@util.propertycache
def nodemap(self):
self.rev(self.node(0))
return self._nodecache
def hasnode(self, node):
try:
self.rev(node)
return True
except KeyError:
return False
def candelta(self, baserev, rev):
"""whether two revisions (baserev, rev) can be delta-ed or not"""
# Disable delta if either rev requires a content-changing flag
# processor (ex. LFS). This is because such flag processor can alter
# the rawtext content that the delta will be based on, and two clients
# could have a same revlog node with different flags (i.e. different
# rawtext contents) and the delta could be incompatible.
if ((self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS)
or (self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS)):
return False
return True
def clearcaches(self):
self._cache = None
self._chainbasecache.clear()
self._chunkcache = (0, '')
self._pcache = {}
try:
self._nodecache.clearcaches()
except AttributeError:
self._nodecache = {nullid: nullrev}
self._nodepos = None
def rev(self, node):
try:
return self._nodecache[node]
except TypeError:
raise
except RevlogError:
# parsers.c radix tree lookup failed
if node == wdirid:
raise error.WdirUnsupported
raise LookupError(node, self.indexfile, _('no node'))
except KeyError:
# pure python cache lookup failed
n = self._nodecache
i = self.index
p = self._nodepos
if p is None:
p = len(i) - 2
for r in xrange(p, -1, -1):
v = i[r][7]
n[v] = r
if v == node:
self._nodepos = r - 1
return r
if node == wdirid:
raise error.WdirUnsupported
raise LookupError(node, self.indexfile, _('no node'))
# Accessors for index entries.
# First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes
# are flags.
def start(self, rev):
return int(self.index[rev][0] >> 16)
def flags(self, rev):
return self.index[rev][0] & 0xFFFF
def length(self, rev):
return self.index[rev][1]
def rawsize(self, rev):
"""return the length of the uncompressed text for a given revision"""
l = self.index[rev][2]
if l >= 0:
return l
t = self.revision(rev, raw=True)
return len(t)
def size(self, rev):
"""length of non-raw text (processed by a "read" flag processor)"""
# fast path: if no "read" flag processor could change the content,
# size is rawsize. note: ELLIPSIS is known to not change the content.
flags = self.flags(rev)
if flags & (REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0:
return self.rawsize(rev)
return len(self.revision(rev, raw=False))
def chainbase(self, rev):
base = self._chainbasecache.get(rev)
if base is not None:
return base
index = self.index
base = index[rev][3]
while base != rev:
rev = base
base = index[rev][3]
self._chainbasecache[rev] = base
return base
def linkrev(self, rev):
return self.index[rev][4]
def parentrevs(self, rev):
try:
entry = self.index[rev]
except IndexError:
if rev == wdirrev:
raise error.WdirUnsupported
raise
return entry[5], entry[6]
def node(self, rev):
try:
return self.index[rev][7]
except IndexError:
if rev == wdirrev:
raise error.WdirUnsupported
raise
# Derived from index values.
def end(self, rev):
return self.start(rev) + self.length(rev)
def parents(self, node):
i = self.index
d = i[self.rev(node)]
return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline
def chainlen(self, rev):
return self._chaininfo(rev)[0]
def _chaininfo(self, rev):
chaininfocache = self._chaininfocache
if rev in chaininfocache:
return chaininfocache[rev]
index = self.index
generaldelta = self._generaldelta
iterrev = rev
e = index[iterrev]
clen = 0
compresseddeltalen = 0
while iterrev != e[3]:
clen += 1
compresseddeltalen += e[1]
if generaldelta:
iterrev = e[3]
else:
iterrev -= 1
if iterrev in chaininfocache:
t = chaininfocache[iterrev]
clen += t[0]
compresseddeltalen += t[1]
break
e = index[iterrev]
else:
# Add text length of base since decompressing that also takes
# work. For cache hits the length is already included.
compresseddeltalen += e[1]
r = (clen, compresseddeltalen)
chaininfocache[rev] = r
return r
def _deltachain(self, rev, stoprev=None):
"""Obtain the delta chain for a revision.
``stoprev`` specifies a revision to stop at. If not specified, we
stop at the base of the chain.
Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
revs in ascending order and ``stopped`` is a bool indicating whether
``stoprev`` was hit.
"""
# Try C implementation.
try:
return self.index.deltachain(rev, stoprev, self._generaldelta)
except AttributeError:
pass
chain = []
# Alias to prevent attribute lookup in tight loop.
index = self.index
generaldelta = self._generaldelta
iterrev = rev
e = index[iterrev]
while iterrev != e[3] and iterrev != stoprev:
chain.append(iterrev)
if generaldelta:
iterrev = e[3]
else:
iterrev -= 1
e = index[iterrev]
if iterrev == stoprev:
stopped = True
else:
chain.append(iterrev)
stopped = False
chain.reverse()
return chain, stopped
def ancestors(self, revs, stoprev=0, inclusive=False):
"""Generate the ancestors of 'revs' in reverse topological order.
Does not generate revs lower than stoprev.
See the documentation for ancestor.lazyancestors for more details."""
return ancestor.lazyancestors(self.parentrevs, revs, stoprev=stoprev,
inclusive=inclusive)
def descendants(self, revs):
"""Generate the descendants of 'revs' in revision order.
Yield a sequence of revision numbers starting with a child of
some rev in revs, i.e., each revision is *not* considered a
descendant of itself. Results are ordered by revision number (a
topological sort)."""
first = min(revs)
if first == nullrev:
for i in self:
yield i
return
seen = set(revs)
for i in self.revs(start=first + 1):
for x in self.parentrevs(i):
if x != nullrev and x in seen:
seen.add(i)
yield i
break
def findcommonmissing(self, common=None, heads=None):
"""Return a tuple of the ancestors of common and the ancestors of heads
that are not ancestors of common. In revset terminology, we return the
tuple:
::common, (::heads) - (::common)
The list is sorted by revision number, meaning it is
topologically sorted.
'heads' and 'common' are both lists of node IDs. If heads is
not supplied, uses all of the revlog's heads. If common is not
supplied, uses nullid."""
if common is None:
common = [nullid]
if heads is None:
heads = self.heads()
common = [self.rev(n) for n in common]
heads = [self.rev(n) for n in heads]
# we want the ancestors, but inclusive
class lazyset(object):
def __init__(self, lazyvalues):
self.addedvalues = set()
self.lazyvalues = lazyvalues
def __contains__(self, value):
return value in self.addedvalues or value in self.lazyvalues
def __iter__(self):
added = self.addedvalues
for r in added:
yield r
for r in self.lazyvalues:
if not r in added:
yield r
def add(self, value):
self.addedvalues.add(value)
def update(self, values):
self.addedvalues.update(values)
has = lazyset(self.ancestors(common))
has.add(nullrev)
has.update(common)
# take all ancestors from heads that aren't in has
missing = set()
visit = collections.deque(r for r in heads if r not in has)
while visit:
r = visit.popleft()
if r in missing:
continue
else:
missing.add(r)
for p in self.parentrevs(r):
if p not in has:
visit.append(p)
missing = list(missing)
missing.sort()
return has, [self.node(miss) for miss in missing]
def incrementalmissingrevs(self, common=None):
"""Return an object that can be used to incrementally compute the
revision numbers of the ancestors of arbitrary sets that are not
ancestors of common. This is an ancestor.incrementalmissingancestors
object.
'common' is a list of revision numbers. If common is not supplied, uses
nullrev.
"""
if common is None:
common = [nullrev]
return ancestor.incrementalmissingancestors(self.parentrevs, common)
def findmissingrevs(self, common=None, heads=None):
"""Return the revision numbers of the ancestors of heads that
are not ancestors of common.
More specifically, return a list of revision numbers corresponding to
nodes N such that every N satisfies the following constraints:
1. N is an ancestor of some node in 'heads'
2. N is not an ancestor of any node in 'common'
The list is sorted by revision number, meaning it is
topologically sorted.
'heads' and 'common' are both lists of revision numbers. If heads is
not supplied, uses all of the revlog's heads. If common is not
supplied, uses nullid."""
if common is None:
common = [nullrev]
if heads is None:
heads = self.headrevs()
inc = self.incrementalmissingrevs(common=common)
return inc.missingancestors(heads)
def findmissing(self, common=None, heads=None):
"""Return the ancestors of heads that are not ancestors of common.
More specifically, return a list of nodes N such that every N
satisfies the following constraints:
1. N is an ancestor of some node in 'heads'
2. N is not an ancestor of any node in 'common'
The list is sorted by revision number, meaning it is
topologically sorted.
'heads' and 'common' are both lists of node IDs. If heads is
not supplied, uses all of the revlog's heads. If common is not
supplied, uses nullid."""
if common is None:
common = [nullid]
if heads is None:
heads = self.heads()
common = [self.rev(n) for n in common]
heads = [self.rev(n) for n in heads]
inc = self.incrementalmissingrevs(common=common)
return [self.node(r) for r in inc.missingancestors(heads)]
def nodesbetween(self, roots=None, heads=None):
"""Return a topological path from 'roots' to 'heads'.
Return a tuple (nodes, outroots, outheads) where 'nodes' is a
topologically sorted list of all nodes N that satisfy both of
these constraints:
1. N is a descendant of some node in 'roots'
2. N is an ancestor of some node in 'heads'
Every node is considered to be both a descendant and an ancestor
of itself, so every reachable node in 'roots' and 'heads' will be
included in 'nodes'.
'outroots' is the list of reachable nodes in 'roots', i.e., the
subset of 'roots' that is returned in 'nodes'. Likewise,
'outheads' is the subset of 'heads' that is also in 'nodes'.
'roots' and 'heads' are both lists of node IDs. If 'roots' is
unspecified, uses nullid as the only root. If 'heads' is
unspecified, uses list of all of the revlog's heads."""
nonodes = ([], [], [])
if roots is not None:
roots = list(roots)
if not roots:
return nonodes
lowestrev = min([self.rev(n) for n in roots])
else:
roots = [nullid] # Everybody's a descendant of nullid
lowestrev = nullrev
if (lowestrev == nullrev) and (heads is None):
# We want _all_ the nodes!
return ([self.node(r) for r in self], [nullid], list(self.heads()))
if heads is None:
# All nodes are ancestors, so the latest ancestor is the last
# node.
highestrev = len(self) - 1
# Set ancestors to None to signal that every node is an ancestor.
ancestors = None
# Set heads to an empty dictionary for later discovery of heads
heads = {}
else:
heads = list(heads)
if not heads:
return nonodes
ancestors = set()
# Turn heads into a dictionary so we can remove 'fake' heads.
# Also, later we will be using it to filter out the heads we can't
# find from roots.
heads = dict.fromkeys(heads, False)
# Start at the top and keep marking parents until we're done.
nodestotag = set(heads)
# Remember where the top was so we can use it as a limit later.
highestrev = max([self.rev(n) for n in nodestotag])
while nodestotag:
# grab a node to tag
n = nodestotag.pop()
# Never tag nullid
if n == nullid:
continue
# A node's revision number represents its place in a
# topologically sorted list of nodes.
r = self.rev(n)
if r >= lowestrev:
if n not in ancestors:
# If we are possibly a descendant of one of the roots
# and we haven't already been marked as an ancestor
ancestors.add(n) # Mark as ancestor
# Add non-nullid parents to list of nodes to tag.
nodestotag.update([p for p in self.parents(n) if
p != nullid])
elif n in heads: # We've seen it before, is it a fake head?
# So it is, real heads should not be the ancestors of
# any other heads.
heads.pop(n)
if not ancestors:
return nonodes
# Now that we have our set of ancestors, we want to remove any
# roots that are not ancestors.
# If one of the roots was nullid, everything is included anyway.
if lowestrev > nullrev:
# But, since we weren't, let's recompute the lowest rev to not
# include roots that aren't ancestors.
# Filter out roots that aren't ancestors of heads
roots = [root for root in roots if root in ancestors]
# Recompute the lowest revision
if roots:
lowestrev = min([self.rev(root) for root in roots])
else:
# No more roots? Return empty list
return nonodes
else:
# We are descending from nullid, and don't need to care about
# any other roots.
lowestrev = nullrev
roots = [nullid]
# Transform our roots list into a set.
descendants = set(roots)
# Also, keep the original roots so we can filter out roots that aren't
# 'real' roots (i.e. are descended from other roots).
roots = descendants.copy()
# Our topologically sorted list of output nodes.
orderedout = []
# Don't start at nullid since we don't want nullid in our output list,
# and if nullid shows up in descendants, empty parents will look like
# they're descendants.
for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
n = self.node(r)
isdescendant = False
if lowestrev == nullrev: # Everybody is a descendant of nullid
isdescendant = True
elif n in descendants:
# n is already a descendant
isdescendant = True
# This check only needs to be done here because all the roots
# will start being marked is descendants before the loop.
if n in roots:
# If n was a root, check if it's a 'real' root.
p = tuple(self.parents(n))
# If any of its parents are descendants, it's not a root.
if (p[0] in descendants) or (p[1] in descendants):
roots.remove(n)
else:
p = tuple(self.parents(n))
# A node is a descendant if either of its parents are
# descendants. (We seeded the dependents list with the roots
# up there, remember?)
if (p[0] in descendants) or (p[1] in descendants):
descendants.add(n)
isdescendant = True
if isdescendant and ((ancestors is None) or (n in ancestors)):
# Only include nodes that are both descendants and ancestors.
orderedout.append(n)
if (ancestors is not None) and (n in heads):
# We're trying to figure out which heads are reachable
# from roots.
# Mark this head as having been reached
heads[n] = True
elif ancestors is None:
# Otherwise, we're trying to discover the heads.
# Assume this is a head because if it isn't, the next step
# will eventually remove it.
heads[n] = True
# But, obviously its parents aren't.
for p in self.parents(n):
heads.pop(p, None)
heads = [head for head, flag in heads.iteritems() if flag]
roots = list(roots)
assert orderedout
assert roots
assert heads
return (orderedout, roots, heads)
def headrevs(self):
try:
return self.index.headrevs()
except AttributeError:
return self._headrevs()
def computephases(self, roots):
return self.index.computephasesmapsets(roots)
def _headrevs(self):
count = len(self)
if not count:
return [nullrev]
# we won't iter over filtered rev so nobody is a head at start
ishead = [0] * (count + 1)
index = self.index
for r in self:
ishead[r] = 1 # I may be an head
e = index[r]
ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
return [r for r, val in enumerate(ishead) if val]
def heads(self, start=None, stop=None):
"""return the list of all nodes that have no children
if start is specified, only heads that are descendants of
start will be returned
if stop is specified, it will consider all the revs from stop
as if they had no children
"""
if start is None and stop is None:
if not len(self):
return [nullid]
return [self.node(r) for r in self.headrevs()]
if start is None:
start = nullid
if stop is None:
stop = []
stoprevs = set([self.rev(n) for n in stop])
startrev = self.rev(start)
reachable = {startrev}
heads = {startrev}
parentrevs = self.parentrevs
for r in self.revs(start=startrev + 1):
for p in parentrevs(r):
if p in reachable:
if r not in stoprevs:
reachable.add(r)
heads.add(r)
if p in heads and p not in stoprevs:
heads.remove(p)
return [self.node(r) for r in heads]
def children(self, node):
"""find the children of a given node"""
c = []
p = self.rev(node)
for r in self.revs(start=p + 1):
prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
if prevs:
for pr in prevs:
if pr == p:
c.append(self.node(r))
elif p == nullrev:
c.append(self.node(r))
return c
def descendant(self, start, end):
if start == nullrev:
return True
for i in self.descendants([start]):
if i == end:
return True
elif i > end:
break
return False
def commonancestorsheads(self, a, b):
"""calculate all the heads of the common ancestors of nodes a and b"""
a, b = self.rev(a), self.rev(b)
try:
ancs = self.index.commonancestorsheads(a, b)
except (AttributeError, OverflowError): # C implementation failed
ancs = ancestor.commonancestorsheads(self.parentrevs, a, b)
return pycompat.maplist(self.node, ancs)
def isancestor(self, a, b):
"""return True if node a is an ancestor of node b
The implementation of this is trivial but the use of
commonancestorsheads is not."""
return a in self.commonancestorsheads(a, b)
def ancestor(self, a, b):
"""calculate the "best" common ancestor of nodes a and b"""
a, b = self.rev(a), self.rev(b)
try:
ancs = self.index.ancestors(a, b)
except (AttributeError, OverflowError):
ancs = ancestor.ancestors(self.parentrevs, a, b)
if ancs:
# choose a consistent winner when there's a tie
return min(map(self.node, ancs))
return nullid
def _match(self, id):
if isinstance(id, int):
# rev
return self.node(id)
if len(id) == 20:
# possibly a binary node
# odds of a binary node being all hex in ASCII are 1 in 10**25
try:
node = id
self.rev(node) # quick search the index
return node
except LookupError:
pass # may be partial hex id
try:
# str(rev)
rev = int(id)
if str(rev) != id:
raise ValueError
if rev < 0:
rev = len(self) + rev
if rev < 0 or rev >= len(self):
raise ValueError
return self.node(rev)
except (ValueError, OverflowError):
pass
if len(id) == 40:
try:
# a full hex nodeid?
node = bin(id)
self.rev(node)
return node
except (TypeError, LookupError):
pass
def _partialmatch(self, id):
maybewdir = wdirhex.startswith(id)
try:
partial = self.index.partialmatch(id)
if partial and self.hasnode(partial):
if maybewdir:
# single 'ff...' match in radix tree, ambiguous with wdir
raise RevlogError
return partial
if maybewdir:
# no 'ff...' match in radix tree, wdir identified
raise error.WdirUnsupported
return None
except RevlogError:
# parsers.c radix tree lookup gave multiple matches
# fast path: for unfiltered changelog, radix tree is accurate
if not getattr(self, 'filteredrevs', None):
raise LookupError(id, self.indexfile,
_('ambiguous identifier'))
# fall through to slow path that filters hidden revisions
except (AttributeError, ValueError):
# we are pure python, or key was too short to search radix tree
pass
if id in self._pcache:
return self._pcache[id]
if len(id) < 40:
try:
# hex(node)[:...]
l = len(id) // 2 # grab an even number of digits
prefix = bin(id[:l * 2])
nl = [e[7] for e in self.index if e[7].startswith(prefix)]
nl = [n for n in nl if hex(n).startswith(id) and
self.hasnode(n)]
if len(nl) > 0:
if len(nl) == 1 and not maybewdir:
self._pcache[id] = nl[0]
return nl[0]
raise LookupError(id, self.indexfile,
_('ambiguous identifier'))
if maybewdir:
raise error.WdirUnsupported
return None
except (TypeError, binascii.Error):
pass
def lookup(self, id):
"""locate a node based on:
- revision number or str(revision number)
- nodeid or subset of hex nodeid
"""
n = self._match(id)
if n is not None:
return n
n = self._partialmatch(id)
if n:
return n
raise LookupError(id, self.indexfile, _('no match found'))
def shortest(self, hexnode, minlength=1):
"""Find the shortest unambiguous prefix that matches hexnode."""
def isvalid(test):
try:
if self._partialmatch(test) is None:
return False
try:
i = int(test)
# if we are a pure int, then starting with zero will not be
# confused as a rev; or, obviously, if the int is larger
# than the value of the tip rev
if test[0] == '0' or i > len(self):
return True
return False
except ValueError:
return True
except error.RevlogError:
return False
except error.WdirUnsupported:
# single 'ff...' match
return True
shortest = hexnode
startlength = max(6, minlength)
length = startlength
while True:
test = hexnode[:length]
if isvalid(test):
shortest = test
if length == minlength or length > startlength:
return shortest
length -= 1
else:
length += 1
if len(shortest) <= length:
return shortest
def cmp(self, node, text):
"""compare text with a given file revision
returns True if text is different than what is stored.
"""
p1, p2 = self.parents(node)
return hash(text, p1, p2) != node
def _cachesegment(self, offset, data):
"""Add a segment to the revlog cache.
Accepts an absolute offset and the data that is at that location.
"""
o, d = self._chunkcache
# try to add to existing cache
if o + len(d) == offset and len(d) + len(data) < _chunksize:
self._chunkcache = o, d + data
else:
self._chunkcache = offset, data
def _readsegment(self, offset, length, df=None):
"""Load a segment of raw data from the revlog.
Accepts an absolute offset, length to read, and an optional existing
file handle to read from.
If an existing file handle is passed, it will be seeked and the
original seek position will NOT be restored.
Returns a str or buffer of raw byte data.
"""
if df is not None:
closehandle = False
else:
if self._inline:
df = self.opener(self.indexfile)
else:
df = self.opener(self.datafile)
closehandle = True
# Cache data both forward and backward around the requested
# data, in a fixed size window. This helps speed up operations
# involving reading the revlog backwards.
cachesize = self._chunkcachesize
realoffset = offset & ~(cachesize - 1)
reallength = (((offset + length + cachesize) & ~(cachesize - 1))
- realoffset)
df.seek(realoffset)
d = df.read(reallength)
if closehandle:
df.close()
self._cachesegment(realoffset, d)
if offset != realoffset or reallength != length:
return util.buffer(d, offset - realoffset, length)
return d
def _getsegment(self, offset, length, df=None):
"""Obtain a segment of raw data from the revlog.
Accepts an absolute offset, length of bytes to obtain, and an
optional file handle to the already-opened revlog. If the file
handle is used, it's original seek position will not be preserved.
Requests for data may be returned from a cache.
Returns a str or a buffer instance of raw byte data.
"""
o, d = self._chunkcache
l = len(d)
# is it in the cache?
cachestart = offset - o
cacheend = cachestart + length
if cachestart >= 0 and cacheend <= l:
if cachestart == 0 and cacheend == l:
return d # avoid a copy
return util.buffer(d, cachestart, cacheend - cachestart)
return self._readsegment(offset, length, df=df)
def _getsegmentforrevs(self, startrev, endrev, df=None):
"""Obtain a segment of raw data corresponding to a range of revisions.
Accepts the start and end revisions and an optional already-open
file handle to be used for reading. If the file handle is read, its
seek position will not be preserved.
Requests for data may be satisfied by a cache.
Returns a 2-tuple of (offset, data) for the requested range of
revisions. Offset is the integer offset from the beginning of the
revlog and data is a str or buffer of the raw byte data.
Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
to determine where each revision's data begins and ends.
"""
# Inlined self.start(startrev) & self.end(endrev) for perf reasons
# (functions are expensive).
index = self.index
istart = index[startrev]
start = int(istart[0] >> 16)
if startrev == endrev:
end = start + istart[1]
else:
iend = index[endrev]
end = int(iend[0] >> 16) + iend[1]
if self._inline:
start += (startrev + 1) * self._io.size
end += (endrev + 1) * self._io.size
length = end - start
return start, self._getsegment(start, length, df=df)
def _chunk(self, rev, df=None):
"""Obtain a single decompressed chunk for a revision.
Accepts an integer revision and an optional already-open file handle
to be used for reading. If used, the seek position of the file will not
be preserved.
Returns a str holding uncompressed data for the requested revision.
"""
return self.decompress(self._getsegmentforrevs(rev, rev, df=df)[1])
def _chunks(self, revs, df=None):
"""Obtain decompressed chunks for the specified revisions.
Accepts an iterable of numeric revisions that are assumed to be in
ascending order. Also accepts an optional already-open file handle
to be used for reading. If used, the seek position of the file will
not be preserved.
This function is similar to calling ``self._chunk()`` multiple times,
but is faster.
Returns a list with decompressed data for each requested revision.
"""
if not revs:
return []
start = self.start
length = self.length
inline = self._inline
iosize = self._io.size
buffer = util.buffer
l = []
ladd = l.append
if not self._withsparseread:
slicedchunks = (revs,)
else:
slicedchunks = _slicechunk(self, revs)
for revschunk in slicedchunks:
firstrev = revschunk[0]
# Skip trailing revisions with empty diff
for lastrev in revschunk[::-1]:
if length(lastrev) != 0:
break
try:
offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df)
except OverflowError:
# issue4215 - we can't cache a run of chunks greater than
# 2G on Windows
return [self._chunk(rev, df=df) for rev in revschunk]
decomp = self.decompress
for rev in revschunk:
chunkstart = start(rev)
if inline:
chunkstart += (rev + 1) * iosize
chunklength = length(rev)
ladd(decomp(buffer(data, chunkstart - offset, chunklength)))
return l
def _chunkclear(self):
"""Clear the raw chunk cache."""
self._chunkcache = (0, '')
def deltaparent(self, rev):
"""return deltaparent of the given revision"""
base = self.index[rev][3]
if base == rev:
return nullrev
elif self._generaldelta:
return base
else:
return rev - 1
def revdiff(self, rev1, rev2):
"""return or calculate a delta between two revisions
The delta calculated is in binary form and is intended to be written to
revlog data directly. So this function needs raw revision data.
"""
if rev1 != nullrev and self.deltaparent(rev2) == rev1:
return bytes(self._chunk(rev2))
return mdiff.textdiff(self.revision(rev1, raw=True),
self.revision(rev2, raw=True))
def revision(self, nodeorrev, _df=None, raw=False):
"""return an uncompressed revision of a given node or revision
number.
_df - an existing file handle to read from. (internal-only)
raw - an optional argument specifying if the revision data is to be
treated as raw data when applying flag transforms. 'raw' should be set
to True when generating changegroups or in debug commands.
"""
if isinstance(nodeorrev, int):
rev = nodeorrev
node = self.node(rev)
else:
node = nodeorrev
rev = None
cachedrev = None
flags = None
rawtext = None
if node == nullid:
return ""
if self._cache:
if self._cache[0] == node:
# _cache only stores rawtext
if raw:
return self._cache[2]
# duplicated, but good for perf
if rev is None:
rev = self.rev(node)
if flags is None:
flags = self.flags(rev)
# no extra flags set, no flag processor runs, text = rawtext
if flags == REVIDX_DEFAULT_FLAGS:
return self._cache[2]
# rawtext is reusable. need to run flag processor
rawtext = self._cache[2]
cachedrev = self._cache[1]
# look up what we need to read
if rawtext is None:
if rev is None:
rev = self.rev(node)
chain, stopped = self._deltachain(rev, stoprev=cachedrev)
if stopped:
rawtext = self._cache[2]
# drop cache to save memory
self._cache = None
bins = self._chunks(chain, df=_df)
if rawtext is None:
rawtext = bytes(bins[0])
bins = bins[1:]
rawtext = mdiff.patches(rawtext, bins)
self._cache = (node, rev, rawtext)
if flags is None:
if rev is None:
rev = self.rev(node)
flags = self.flags(rev)
text, validatehash = self._processflags(rawtext, flags, 'read', raw=raw)
if validatehash:
self.checkhash(text, node, rev=rev)
return text
def hash(self, text, p1, p2):
"""Compute a node hash.
Available as a function so that subclasses can replace the hash
as needed.
"""
return hash(text, p1, p2)
def _processflags(self, text, flags, operation, raw=False):
"""Inspect revision data flags and applies transforms defined by
registered flag processors.
``text`` - the revision data to process
``flags`` - the revision flags
``operation`` - the operation being performed (read or write)
``raw`` - an optional argument describing if the raw transform should be
applied.
This method processes the flags in the order (or reverse order if
``operation`` is 'write') defined by REVIDX_FLAGS_ORDER, applying the
flag processors registered for present flags. The order of flags defined
in REVIDX_FLAGS_ORDER needs to be stable to allow non-commutativity.
Returns a 2-tuple of ``(text, validatehash)`` where ``text`` is the
processed text and ``validatehash`` is a bool indicating whether the
returned text should be checked for hash integrity.
Note: If the ``raw`` argument is set, it has precedence over the
operation and will only update the value of ``validatehash``.
"""
# fast path: no flag processors will run
if flags == 0:
return text, True
if not operation in ('read', 'write'):
raise ProgrammingError(_("invalid '%s' operation ") % (operation))
# Check all flags are known.
if flags & ~REVIDX_KNOWN_FLAGS:
raise RevlogError(_("incompatible revision flag '%#x'") %
(flags & ~REVIDX_KNOWN_FLAGS))
validatehash = True
# Depending on the operation (read or write), the order might be
# reversed due to non-commutative transforms.
orderedflags = REVIDX_FLAGS_ORDER
if operation == 'write':
orderedflags = reversed(orderedflags)
for flag in orderedflags:
# If a flagprocessor has been registered for a known flag, apply the
# related operation transform and update result tuple.
if flag & flags:
vhash = True
if flag not in _flagprocessors:
message = _("missing processor for flag '%#x'") % (flag)
raise RevlogError(message)
processor = _flagprocessors[flag]
if processor is not None:
readtransform, writetransform, rawtransform = processor
if raw:
vhash = rawtransform(self, text)
elif operation == 'read':
text, vhash = readtransform(self, text)
else: # write operation
text, vhash = writetransform(self, text)
validatehash = validatehash and vhash
return text, validatehash
def checkhash(self, text, node, p1=None, p2=None, rev=None):
"""Check node hash integrity.
Available as a function so that subclasses can extend hash mismatch
behaviors as needed.
"""
if p1 is None and p2 is None:
p1, p2 = self.parents(node)
if node != self.hash(text, p1, p2):
revornode = rev
if revornode is None:
revornode = templatefilters.short(hex(node))
raise RevlogError(_("integrity check failed on %s:%s")
% (self.indexfile, pycompat.bytestr(revornode)))
def checkinlinesize(self, tr, fp=None):
"""Check if the revlog is too big for inline and convert if so.
This should be called after revisions are added to the revlog. If the
revlog has grown too large to be an inline revlog, it will convert it
to use multiple index and data files.
"""
if not self._inline or (self.start(-2) + self.length(-2)) < _maxinline:
return
trinfo = tr.find(self.indexfile)
if trinfo is None:
raise RevlogError(_("%s not found in the transaction")
% self.indexfile)
trindex = trinfo[2]
if trindex is not None:
dataoff = self.start(trindex)
else:
# revlog was stripped at start of transaction, use all leftover data
trindex = len(self) - 1
dataoff = self.end(-2)
tr.add(self.datafile, dataoff)
if fp:
fp.flush()
fp.close()
df = self.opener(self.datafile, 'w')
try:
for r in self:
df.write(self._getsegmentforrevs(r, r)[1])
finally:
df.close()
fp = self.opener(self.indexfile, 'w', atomictemp=True,
checkambig=self._checkambig)
self.version &= ~FLAG_INLINE_DATA
self._inline = False
for i in self:
e = self._io.packentry(self.index[i], self.node, self.version, i)
fp.write(e)
# if we don't call close, the temp file will never replace the
# real index
fp.close()
tr.replace(self.indexfile, trindex * self._io.size)
self._chunkclear()
def addrevision(self, text, transaction, link, p1, p2, cachedelta=None,
node=None, flags=REVIDX_DEFAULT_FLAGS, deltacomputer=None):
"""add a revision to the log
text - the revision data to add
transaction - the transaction object used for rollback
link - the linkrev data to add
p1, p2 - the parent nodeids of the revision
cachedelta - an optional precomputed delta
node - nodeid of revision; typically node is not specified, and it is
computed by default as hash(text, p1, p2), however subclasses might
use different hashing method (and override checkhash() in such case)
flags - the known flags to set on the revision
deltacomputer - an optional _deltacomputer instance shared between
multiple calls
"""
if link == nullrev:
raise RevlogError(_("attempted to add linkrev -1 to %s")
% self.indexfile)
if flags:
node = node or self.hash(text, p1, p2)
rawtext, validatehash = self._processflags(text, flags, 'write')
# If the flag processor modifies the revision data, ignore any provided
# cachedelta.
if rawtext != text:
cachedelta = None
if len(rawtext) > _maxentrysize:
raise RevlogError(
_("%s: size of %d bytes exceeds maximum revlog storage of 2GiB")
% (self.indexfile, len(rawtext)))
node = node or self.hash(rawtext, p1, p2)
if node in self.nodemap:
return node
if validatehash:
self.checkhash(rawtext, node, p1=p1, p2=p2)
return self.addrawrevision(rawtext, transaction, link, p1, p2, node,
flags, cachedelta=cachedelta,
deltacomputer=deltacomputer)
def addrawrevision(self, rawtext, transaction, link, p1, p2, node, flags,
cachedelta=None, deltacomputer=None):
"""add a raw revision with known flags, node and parents
useful when reusing a revision not stored in this revlog (ex: received
over wire, or read from an external bundle).
"""
dfh = None
if not self._inline:
dfh = self.opener(self.datafile, "a+")
ifh = self.opener(self.indexfile, "a+", checkambig=self._checkambig)
try:
return self._addrevision(node, rawtext, transaction, link, p1, p2,
flags, cachedelta, ifh, dfh,
deltacomputer=deltacomputer)
finally:
if dfh:
dfh.close()
ifh.close()
def compress(self, data):
"""Generate a possibly-compressed representation of data."""
if not data:
return '', data
compressed = self._compressor.compress(data)
if compressed:
# The revlog compressor added the header in the returned data.
return '', compressed
if data[0:1] == '\0':
return '', data
return 'u', data
def decompress(self, data):
"""Decompress a revlog chunk.
The chunk is expected to begin with a header identifying the
format type so it can be routed to an appropriate decompressor.
"""
if not data:
return data
# Revlogs are read much more frequently than they are written and many
# chunks only take microseconds to decompress, so performance is
# important here.
#
# We can make a few assumptions about revlogs:
#
# 1) the majority of chunks will be compressed (as opposed to inline
# raw data).
# 2) decompressing *any* data will likely by at least 10x slower than
# returning raw inline data.
# 3) we want to prioritize common and officially supported compression
# engines
#
# It follows that we want to optimize for "decompress compressed data
# when encoded with common and officially supported compression engines"
# case over "raw data" and "data encoded by less common or non-official
# compression engines." That is why we have the inline lookup first
# followed by the compengines lookup.
#
# According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib
# compressed chunks. And this matters for changelog and manifest reads.
t = data[0:1]
if t == 'x':
try:
return _zlibdecompress(data)
except zlib.error as e:
raise RevlogError(_('revlog decompress error: %s') % str(e))
# '\0' is more common than 'u' so it goes first.
elif t == '\0':
return data
elif t == 'u':
return util.buffer(data, 1)
try:
compressor = self._decompressors[t]
except KeyError:
try:
engine = util.compengines.forrevlogheader(t)
compressor = engine.revlogcompressor()
self._decompressors[t] = compressor
except KeyError:
raise RevlogError(_('unknown compression type %r') % t)
return compressor.decompress(data)
def _isgooddeltainfo(self, d, textlen):
"""Returns True if the given delta is good. Good means that it is within
the disk span, disk size, and chain length bounds that we know to be
performant."""
if d is None:
return False
# - 'd.distance' is the distance from the base revision -- bounding it
# limits the amount of I/O we need to do.
# - 'd.compresseddeltalen' is the sum of the total size of deltas we
# need to apply -- bounding it limits the amount of CPU we consume.
defaultmax = textlen * 4
maxdist = self._maxdeltachainspan
if not maxdist:
maxdist = d.distance # ensure the conditional pass
maxdist = max(maxdist, defaultmax)
if (d.distance > maxdist or d.deltalen > textlen or
d.compresseddeltalen > textlen * 2 or
(self._maxchainlen and d.chainlen > self._maxchainlen)):
return False
return True
def _addrevision(self, node, rawtext, transaction, link, p1, p2, flags,
cachedelta, ifh, dfh, alwayscache=False,
deltacomputer=None):
"""internal function to add revisions to the log
see addrevision for argument descriptions.
note: "addrevision" takes non-raw text, "_addrevision" takes raw text.
if "deltacomputer" is not provided or None, a defaultdeltacomputer will
be used.
invariants:
- rawtext is optional (can be None); if not set, cachedelta must be set.
if both are set, they must correspond to each other.
"""
if node == nullid:
raise RevlogError(_("%s: attempt to add null revision") %
(self.indexfile))
if node == wdirid:
raise RevlogError(_("%s: attempt to add wdir revision") %
(self.indexfile))
if self._inline:
fh = ifh
else:
fh = dfh
btext = [rawtext]
curr = len(self)
prev = curr - 1
offset = self.end(prev)
p1r, p2r = self.rev(p1), self.rev(p2)
# full versions are inserted when the needed deltas
# become comparable to the uncompressed text
if rawtext is None:
# need rawtext size, before changed by flag processors, which is
# the non-raw size. use revlog explicitly to avoid filelog's extra
# logic that might remove metadata size.
textlen = mdiff.patchedsize(revlog.size(self, cachedelta[0]),
cachedelta[1])
else:
textlen = len(rawtext)
if deltacomputer is None:
deltacomputer = _deltacomputer(self)
revinfo = _revisioninfo(node, p1, p2, btext, textlen, cachedelta, flags)
# no delta for flag processor revision (see "candelta" for why)
# not calling candelta since only one revision needs test, also to
# avoid overhead fetching flags again.
if flags & REVIDX_RAWTEXT_CHANGING_FLAGS:
deltainfo = None
else:
deltainfo = deltacomputer.finddeltainfo(revinfo, fh)
if deltainfo is not None:
base = deltainfo.base
chainbase = deltainfo.chainbase
data = deltainfo.data
l = deltainfo.deltalen
else:
rawtext = deltacomputer.buildtext(revinfo, fh)
data = self.compress(rawtext)
l = len(data[1]) + len(data[0])
base = chainbase = curr
e = (offset_type(offset, flags), l, textlen,
base, link, p1r, p2r, node)
self.index.insert(-1, e)
self.nodemap[node] = curr
entry = self._io.packentry(e, self.node, self.version, curr)
self._writeentry(transaction, ifh, dfh, entry, data, link, offset)
if alwayscache and rawtext is None:
rawtext = deltacomputer._buildtext(revinfo, fh)
if type(rawtext) == str: # only accept immutable objects
self._cache = (node, curr, rawtext)
self._chainbasecache[curr] = chainbase
return node
def _writeentry(self, transaction, ifh, dfh, entry, data, link, offset):
# Files opened in a+ mode have inconsistent behavior on various
# platforms. Windows requires that a file positioning call be made
# when the file handle transitions between reads and writes. See
# 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
# platforms, Python or the platform itself can be buggy. Some versions
# of Solaris have been observed to not append at the end of the file
# if the file was seeked to before the end. See issue4943 for more.
#
# We work around this issue by inserting a seek() before writing.
# Note: This is likely not necessary on Python 3.
ifh.seek(0, os.SEEK_END)
if dfh:
dfh.seek(0, os.SEEK_END)
curr = len(self) - 1
if not self._inline:
transaction.add(self.datafile, offset)
transaction.add(self.indexfile, curr * len(entry))
if data[0]:
dfh.write(data[0])
dfh.write(data[1])
ifh.write(entry)
else:
offset += curr * self._io.size
transaction.add(self.indexfile, offset, curr)
ifh.write(entry)
ifh.write(data[0])
ifh.write(data[1])
self.checkinlinesize(transaction, ifh)
def addgroup(self, deltas, linkmapper, transaction, addrevisioncb=None):
"""
add a delta group
given a set of deltas, add them to the revision log. the
first delta is against its parent, which should be in our
log, the rest are against the previous delta.
If ``addrevisioncb`` is defined, it will be called with arguments of
this revlog and the node that was added.
"""
nodes = []
r = len(self)
end = 0
if r:
end = self.end(r - 1)
ifh = self.opener(self.indexfile, "a+", checkambig=self._checkambig)
isize = r * self._io.size
if self._inline:
transaction.add(self.indexfile, end + isize, r)
dfh = None
else:
transaction.add(self.indexfile, isize, r)
transaction.add(self.datafile, end)
dfh = self.opener(self.datafile, "a+")
def flush():
if dfh:
dfh.flush()
ifh.flush()
try:
deltacomputer = _deltacomputer(self)
# loop through our set of deltas
for data in deltas:
node, p1, p2, linknode, deltabase, delta, flags = data
link = linkmapper(linknode)
flags = flags or REVIDX_DEFAULT_FLAGS
nodes.append(node)
if node in self.nodemap:
# this can happen if two branches make the same change
continue
for p in (p1, p2):
if p not in self.nodemap:
raise LookupError(p, self.indexfile,
_('unknown parent'))
if deltabase not in self.nodemap:
raise LookupError(deltabase, self.indexfile,
_('unknown delta base'))
baserev = self.rev(deltabase)
if baserev != nullrev and self.iscensored(baserev):
# if base is censored, delta must be full replacement in a
# single patch operation
hlen = struct.calcsize(">lll")
oldlen = self.rawsize(baserev)
newlen = len(delta) - hlen
if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen):
raise error.CensoredBaseError(self.indexfile,
self.node(baserev))
if not flags and self._peek_iscensored(baserev, delta, flush):
flags |= REVIDX_ISCENSORED
# We assume consumers of addrevisioncb will want to retrieve
# the added revision, which will require a call to
# revision(). revision() will fast path if there is a cache
# hit. So, we tell _addrevision() to always cache in this case.
# We're only using addgroup() in the context of changegroup
# generation so the revision data can always be handled as raw
# by the flagprocessor.
self._addrevision(node, None, transaction, link,
p1, p2, flags, (baserev, delta),
ifh, dfh,
alwayscache=bool(addrevisioncb),
deltacomputer=deltacomputer)
if addrevisioncb:
addrevisioncb(self, node)
if not dfh and not self._inline:
# addrevision switched from inline to conventional
# reopen the index
ifh.close()
dfh = self.opener(self.datafile, "a+")
ifh = self.opener(self.indexfile, "a+",
checkambig=self._checkambig)
finally:
if dfh:
dfh.close()
ifh.close()
return nodes
def iscensored(self, rev):
"""Check if a file revision is censored."""
return False
def _peek_iscensored(self, baserev, delta, flush):
"""Quickly check if a delta produces a censored revision."""
return False
def getstrippoint(self, minlink):
"""find the minimum rev that must be stripped to strip the linkrev
Returns a tuple containing the minimum rev and a set of all revs that
have linkrevs that will be broken by this strip.
"""
brokenrevs = set()
strippoint = len(self)
heads = {}
futurelargelinkrevs = set()
for head in self.headrevs():
headlinkrev = self.linkrev(head)
heads[head] = headlinkrev
if headlinkrev >= minlink:
futurelargelinkrevs.add(headlinkrev)
# This algorithm involves walking down the rev graph, starting at the
# heads. Since the revs are topologically sorted according to linkrev,
# once all head linkrevs are below the minlink, we know there are
# no more revs that could have a linkrev greater than minlink.
# So we can stop walking.
while futurelargelinkrevs:
strippoint -= 1
linkrev = heads.pop(strippoint)
if linkrev < minlink:
brokenrevs.add(strippoint)
else:
futurelargelinkrevs.remove(linkrev)
for p in self.parentrevs(strippoint):
if p != nullrev:
plinkrev = self.linkrev(p)
heads[p] = plinkrev
if plinkrev >= minlink:
futurelargelinkrevs.add(plinkrev)
return strippoint, brokenrevs
def strip(self, minlink, transaction):
"""truncate the revlog on the first revision with a linkrev >= minlink
This function is called when we're stripping revision minlink and
its descendants from the repository.
We have to remove all revisions with linkrev >= minlink, because
the equivalent changelog revisions will be renumbered after the
strip.
So we truncate the revlog on the first of these revisions, and
trust that the caller has saved the revisions that shouldn't be
removed and that it'll re-add them after this truncation.
"""
if len(self) == 0:
return
rev, _ = self.getstrippoint(minlink)
if rev == len(self):
return
# first truncate the files on disk
end = self.start(rev)
if not self._inline:
transaction.add(self.datafile, end)
end = rev * self._io.size
else:
end += rev * self._io.size
transaction.add(self.indexfile, end)
# then reset internal state in memory to forget those revisions
self._cache = None
self._chaininfocache = {}
self._chunkclear()
for x in xrange(rev, len(self)):
del self.nodemap[self.node(x)]
del self.index[rev:-1]
def checksize(self):
expected = 0
if len(self):
expected = max(0, self.end(len(self) - 1))
try:
f = self.opener(self.datafile)
f.seek(0, 2)
actual = f.tell()
f.close()
dd = actual - expected
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
dd = 0
try:
f = self.opener(self.indexfile)
f.seek(0, 2)
actual = f.tell()
f.close()
s = self._io.size
i = max(0, actual // s)
di = actual - (i * s)
if self._inline:
databytes = 0
for r in self:
databytes += max(0, self.length(r))
dd = 0
di = actual - len(self) * s - databytes
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
di = 0
return (dd, di)
def files(self):
res = [self.indexfile]
if not self._inline:
res.append(self.datafile)
return res
DELTAREUSEALWAYS = 'always'
DELTAREUSESAMEREVS = 'samerevs'
DELTAREUSENEVER = 'never'
DELTAREUSEFULLADD = 'fulladd'
DELTAREUSEALL = {'always', 'samerevs', 'never', 'fulladd'}
def clone(self, tr, destrevlog, addrevisioncb=None,
deltareuse=DELTAREUSESAMEREVS, aggressivemergedeltas=None):
"""Copy this revlog to another, possibly with format changes.
The destination revlog will contain the same revisions and nodes.
However, it may not be bit-for-bit identical due to e.g. delta encoding
differences.
The ``deltareuse`` argument control how deltas from the existing revlog
are preserved in the destination revlog. The argument can have the
following values:
DELTAREUSEALWAYS
Deltas will always be reused (if possible), even if the destination
revlog would not select the same revisions for the delta. This is the
fastest mode of operation.
DELTAREUSESAMEREVS
Deltas will be reused if the destination revlog would pick the same
revisions for the delta. This mode strikes a balance between speed
and optimization.
DELTAREUSENEVER
Deltas will never be reused. This is the slowest mode of execution.
This mode can be used to recompute deltas (e.g. if the diff/delta
algorithm changes).
Delta computation can be slow, so the choice of delta reuse policy can
significantly affect run time.
The default policy (``DELTAREUSESAMEREVS``) strikes a balance between
two extremes. Deltas will be reused if they are appropriate. But if the
delta could choose a better revision, it will do so. This means if you
are converting a non-generaldelta revlog to a generaldelta revlog,
deltas will be recomputed if the delta's parent isn't a parent of the
revision.
In addition to the delta policy, the ``aggressivemergedeltas`` argument
controls whether to compute deltas against both parents for merges.
By default, the current default is used.
"""
if deltareuse not in self.DELTAREUSEALL:
raise ValueError(_('value for deltareuse invalid: %s') % deltareuse)
if len(destrevlog):
raise ValueError(_('destination revlog is not empty'))
if getattr(self, 'filteredrevs', None):
raise ValueError(_('source revlog has filtered revisions'))
if getattr(destrevlog, 'filteredrevs', None):
raise ValueError(_('destination revlog has filtered revisions'))
# lazydeltabase controls whether to reuse a cached delta, if possible.
oldlazydeltabase = destrevlog._lazydeltabase
oldamd = destrevlog._aggressivemergedeltas
try:
if deltareuse == self.DELTAREUSEALWAYS:
destrevlog._lazydeltabase = True
elif deltareuse == self.DELTAREUSESAMEREVS:
destrevlog._lazydeltabase = False
destrevlog._aggressivemergedeltas = aggressivemergedeltas or oldamd
populatecachedelta = deltareuse in (self.DELTAREUSEALWAYS,
self.DELTAREUSESAMEREVS)
deltacomputer = _deltacomputer(destrevlog)
index = self.index
for rev in self:
entry = index[rev]
# Some classes override linkrev to take filtered revs into
# account. Use raw entry from index.
flags = entry[0] & 0xffff
linkrev = entry[4]
p1 = index[entry[5]][7]
p2 = index[entry[6]][7]
node = entry[7]
# (Possibly) reuse the delta from the revlog if allowed and
# the revlog chunk is a delta.
cachedelta = None
rawtext = None
if populatecachedelta:
dp = self.deltaparent(rev)
if dp != nullrev:
cachedelta = (dp, str(self._chunk(rev)))
if not cachedelta:
rawtext = self.revision(rev, raw=True)
if deltareuse == self.DELTAREUSEFULLADD:
destrevlog.addrevision(rawtext, tr, linkrev, p1, p2,
cachedelta=cachedelta,
node=node, flags=flags,
deltacomputer=deltacomputer)
else:
ifh = destrevlog.opener(destrevlog.indexfile, 'a+',
checkambig=False)
dfh = None
if not destrevlog._inline:
dfh = destrevlog.opener(destrevlog.datafile, 'a+')
try:
destrevlog._addrevision(node, rawtext, tr, linkrev, p1,
p2, flags, cachedelta, ifh, dfh,
deltacomputer=deltacomputer)
finally:
if dfh:
dfh.close()
ifh.close()
if addrevisioncb:
addrevisioncb(self, rev, node)
finally:
destrevlog._lazydeltabase = oldlazydeltabase
destrevlog._aggressivemergedeltas = oldamd
|