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 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
|
// Copyright 2020 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::convert::Infallible;
use std::fs::File;
use std::io;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt as _;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::SystemTime;
use assert_matches::assert_matches;
use bstr::BString;
use indoc::indoc;
use itertools::Itertools as _;
use jj_lib::backend::CopyId;
use jj_lib::backend::TreeId;
use jj_lib::backend::TreeValue;
use jj_lib::conflict_labels::ConflictLabels;
use jj_lib::conflicts::ConflictMaterializeOptions;
use jj_lib::file_util;
use jj_lib::file_util::check_symlink_support;
use jj_lib::file_util::symlink_dir;
use jj_lib::file_util::symlink_file;
use jj_lib::files::FileMergeHunkLevel;
use jj_lib::fsmonitor::FsmonitorSettings;
use jj_lib::gitignore::GitIgnoreFile;
use jj_lib::local_working_copy::LocalWorkingCopy;
use jj_lib::local_working_copy::TreeState;
use jj_lib::local_working_copy::TreeStateSettings;
use jj_lib::merge::Merge;
use jj_lib::merge::SameChange;
use jj_lib::merged_tree::MergedTree;
use jj_lib::merged_tree::MergedTreeBuilder;
use jj_lib::op_store::OperationId;
use jj_lib::ref_name::WorkspaceName;
use jj_lib::repo::ReadonlyRepo;
use jj_lib::repo::Repo as _;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use jj_lib::rewrite::merge_commit_trees;
use jj_lib::secret_backend::SecretBackend;
use jj_lib::tree_builder::TreeBuilder;
use jj_lib::tree_merge::MergeOptions;
use jj_lib::working_copy::CheckoutError;
use jj_lib::working_copy::CheckoutStats;
use jj_lib::working_copy::SnapshotOptions;
use jj_lib::working_copy::UntrackedReason;
use jj_lib::working_copy::WorkingCopy as _;
use jj_lib::workspace::Workspace;
use jj_lib::workspace::default_working_copy_factories;
use pollster::FutureExt as _;
use test_case::test_case;
use testutils::TestRepo;
use testutils::TestRepoBackend;
use testutils::TestWorkspace;
use testutils::assert_tree_eq;
use testutils::commit_with_tree;
use testutils::create_tree;
use testutils::create_tree_with;
use testutils::empty_snapshot_options;
use testutils::repo_path;
use testutils::repo_path_buf;
use testutils::repo_path_component;
use testutils::write_random_commit;
use tokio::io::AsyncReadExt as _;
fn check_icase_fs(dir: &Path) -> bool {
let test_file = tempfile::Builder::new()
.prefix("icase-")
.tempfile_in(dir)
.unwrap();
let orig_name = test_file.path().file_name().unwrap().to_str().unwrap();
let upper_name = orig_name.to_ascii_uppercase();
assert_ne!(orig_name, upper_name);
dir.join(upper_name).try_exists().unwrap()
}
/// Returns true if the directory appears to ignore some unicode zero-width
/// characters, as in HFS+.
fn check_hfs_plus(dir: &Path) -> bool {
let test_file = tempfile::Builder::new()
.prefix("hfs-plus-\u{200c}-")
.tempfile_in(dir)
.unwrap();
let orig_name = test_file.path().file_name().unwrap().to_str().unwrap();
let stripped_name = orig_name.replace('\u{200c}', "");
assert_ne!(orig_name, stripped_name);
dir.join(stripped_name).try_exists().unwrap()
}
/// Returns true if the directory appears to support Windows short file names.
fn check_vfat(dir: &Path) -> bool {
let _test_file = tempfile::Builder::new()
.prefix("vfattest-")
.tempfile_in(dir)
.unwrap();
let short_name = "VFATTE~1";
dir.join(short_name).try_exists().unwrap()
}
fn to_owned_path_vec(paths: &[&RepoPath]) -> Vec<RepoPathBuf> {
paths.iter().map(|&path| path.to_owned()).collect()
}
#[test]
fn test_root() {
// Test that the working copy is clean and empty after init.
let mut test_workspace = TestWorkspace::init();
let wc = test_workspace.workspace.working_copy();
assert_eq!(wc.sparse_patterns().unwrap(), vec![RepoPathBuf::root()]);
let new_tree = test_workspace.snapshot().unwrap();
let repo = &test_workspace.repo;
let wc_commit_id = repo
.view()
.get_wc_commit_id(WorkspaceName::DEFAULT)
.unwrap();
let wc_commit = repo.store().get_commit(wc_commit_id).unwrap();
assert_tree_eq!(new_tree, wc_commit.tree());
assert_tree_eq!(new_tree, repo.store().empty_merged_tree());
}
#[test_case(TestRepoBackend::Simple ; "simple backend")]
#[test_case(TestRepoBackend::Git ; "git backend")]
fn test_checkout_file_transitions(backend: TestRepoBackend) {
// Tests switching between commits where a certain path is of one type in one
// commit and another type in the other. Includes a "missing" type, so we cover
// additions and removals as well.
let mut test_workspace = TestWorkspace::init_with_backend(backend);
let repo = &test_workspace.repo;
let store = repo.store().clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Kind {
Missing,
Normal,
Executable,
// Executable, but same content as Normal, to test transition where only the bit changed
ExecutableNormalContent,
Conflict,
// Same content as Executable, to test that transition preserves the executable bit
ConflictedExecutableContent,
Symlink,
Tree,
GitSubmodule,
}
fn write_path(
repo: &Arc<ReadonlyRepo>,
tree_builder: &mut MergedTreeBuilder,
kind: Kind,
path: &RepoPath,
) {
let store = repo.store();
let copy_id = CopyId::placeholder();
let value = match kind {
Kind::Missing => Merge::absent(),
Kind::Normal => {
let id = testutils::write_file(store, path, "normal file contents");
Merge::normal(TreeValue::File {
id,
executable: false,
copy_id,
})
}
Kind::Executable => {
let id: jj_lib::backend::FileId =
testutils::write_file(store, path, "executable file contents");
Merge::normal(TreeValue::File {
id,
executable: true,
copy_id,
})
}
Kind::ExecutableNormalContent => {
let id = testutils::write_file(store, path, "normal file contents");
Merge::normal(TreeValue::File {
id,
executable: true,
copy_id,
})
}
Kind::Conflict => {
let base_file_id = testutils::write_file(store, path, "base file contents");
let left_file_id = testutils::write_file(store, path, "left file contents");
let right_file_id = testutils::write_file(store, path, "right file contents");
Merge::from_removes_adds(
vec![Some(TreeValue::File {
id: base_file_id,
executable: false,
copy_id: copy_id.clone(),
})],
vec![
Some(TreeValue::File {
id: left_file_id,
executable: false,
copy_id: copy_id.clone(),
}),
Some(TreeValue::File {
id: right_file_id,
executable: false,
copy_id: copy_id.clone(),
}),
],
)
}
Kind::ConflictedExecutableContent => {
let base_file_id = testutils::write_file(store, path, "executable file contents");
let left_file_id =
testutils::write_file(store, path, "left executable file contents");
let right_file_id =
testutils::write_file(store, path, "right executable file contents");
Merge::from_removes_adds(
vec![Some(TreeValue::File {
id: base_file_id,
executable: true,
copy_id: copy_id.clone(),
})],
vec![
Some(TreeValue::File {
id: left_file_id,
executable: true,
copy_id: copy_id.clone(),
}),
Some(TreeValue::File {
id: right_file_id,
executable: true,
copy_id: copy_id.clone(),
}),
],
)
}
Kind::Symlink => {
let id = store.write_symlink(path, "target").block_on().unwrap();
Merge::normal(TreeValue::Symlink(id))
}
Kind::Tree => {
let file_path = path.join(repo_path_component("file"));
let id = testutils::write_file(store, &file_path, "normal file contents");
let value = TreeValue::File {
id,
executable: false,
copy_id: copy_id.clone(),
};
tree_builder.set_or_remove(file_path, Merge::normal(value));
return;
}
Kind::GitSubmodule => {
let mut tx = repo.start_transaction();
let id = write_random_commit(tx.repo_mut()).id().clone();
tx.commit("test").unwrap();
Merge::normal(TreeValue::GitSubmodule(id))
}
};
tree_builder.set_or_remove(path.to_owned(), value);
}
let mut kinds = vec![
Kind::Missing,
Kind::Normal,
Kind::Executable,
Kind::ExecutableNormalContent,
Kind::Conflict,
Kind::ConflictedExecutableContent,
Kind::Tree,
];
kinds.push(Kind::Symlink);
if backend == TestRepoBackend::Git {
kinds.push(Kind::GitSubmodule);
}
let mut left_tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
let mut right_tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
let mut files = vec![];
for left_kind in &kinds {
for right_kind in &kinds {
let path = repo_path_buf(format!("{left_kind:?}_{right_kind:?}"));
write_path(repo, &mut left_tree_builder, *left_kind, &path);
write_path(repo, &mut right_tree_builder, *right_kind, &path);
files.push((*left_kind, *right_kind, path.clone()));
}
}
let left_tree = left_tree_builder.write_tree().unwrap();
let right_tree = right_tree_builder.write_tree().unwrap();
let left_commit = commit_with_tree(&store, left_tree);
let right_commit = commit_with_tree(&store, right_tree.clone());
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &left_commit)
.unwrap();
ws.check_out(repo.op_id().clone(), None, &right_commit)
.unwrap();
// Check that the working copy is clean.
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, right_tree);
for (_left_kind, right_kind, path) in &files {
let wc_path = workspace_root.join(path.as_internal_file_string());
let maybe_metadata = wc_path.symlink_metadata();
match right_kind {
Kind::Missing => {
assert!(maybe_metadata.is_err(), "{path:?} should not exist");
}
Kind::Normal => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
assert!(metadata.is_file(), "{path:?} should be a file");
#[cfg(unix)]
assert_eq!(
metadata.permissions().mode() & 0o111,
0,
"{path:?} should not be executable"
);
}
Kind::Executable | Kind::ExecutableNormalContent => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
assert!(metadata.is_file(), "{path:?} should be a file");
#[cfg(unix)]
assert_ne!(
metadata.permissions().mode() & 0o111,
0,
"{path:?} should be executable"
);
}
Kind::Conflict => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
assert!(metadata.is_file(), "{path:?} should be a file");
#[cfg(unix)]
assert_eq!(
metadata.permissions().mode() & 0o111,
0,
"{path:?} should not be executable"
);
}
Kind::ConflictedExecutableContent => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
assert!(metadata.is_file(), "{path:?} should be a file");
#[cfg(unix)]
assert_ne!(
metadata.permissions().mode() & 0o111,
0,
"{path:?} should be executable"
);
}
Kind::Symlink => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
if check_symlink_support().unwrap_or(false) {
assert!(
metadata.file_type().is_symlink(),
"{path:?} should be a symlink"
);
}
}
Kind::Tree => {
assert!(maybe_metadata.is_ok(), "{path:?} should exist");
let metadata = maybe_metadata.unwrap();
assert!(metadata.is_dir(), "{path:?} should be a directory");
}
Kind::GitSubmodule => {
// Not supported for now
assert!(maybe_metadata.is_err(), "{path:?} should not exist");
}
};
}
}
#[test]
fn test_checkout_no_op() {
// Check out another commit with the same tree that's already checked out. The
// recorded operation should be updated even though the tree is unchanged.
let mut test_workspace = TestWorkspace::init();
let repo = test_workspace.repo.clone();
let file_path = repo_path("file");
let tree = create_tree(&repo, &[(file_path, "contents")]);
let commit1 = commit_with_tree(repo.store(), tree.clone());
let commit2 = commit_with_tree(repo.store(), tree);
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
// Test the setup: the file should exist on in the tree state.
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(file_path));
// Update to commit2 (same tree as commit1)
let new_op_id = OperationId::from_bytes(b"whatever");
let stats = ws.check_out(new_op_id.clone(), None, &commit2).unwrap();
assert_eq!(stats, CheckoutStats::default());
// The tree state is unchanged but the recorded operation id is updated.
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(file_path));
assert_eq!(*wc.operation_id(), new_op_id);
}
// Test case for issue #2165
#[test]
fn test_conflict_subdirectory() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let path = repo_path("sub/file");
let empty_tree = create_tree(repo, &[]);
let tree1 = create_tree(repo, &[(path, "0")]);
let commit1 = commit_with_tree(repo.store(), tree1.clone());
let tree2 = create_tree(repo, &[(path, "1")]);
let merged_tree = MergedTree::merge(Merge::from_vec(vec![
(tree1, "tree 1".into()),
(empty_tree, "empty".into()),
(tree2, "tree 2".into()),
]))
.block_on()
.unwrap();
let merged_commit = commit_with_tree(repo.store(), merged_tree);
let repo = &test_workspace.repo;
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
ws.check_out(repo.op_id().clone(), None, &merged_commit)
.unwrap();
}
#[test]
fn test_acl() {
let settings = testutils::user_settings();
let test_workspace =
TestWorkspace::init_with_backend_and_settings(TestRepoBackend::Git, &settings);
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let secret_modified_path = repo_path("secret/modified");
let secret_added_path = repo_path("secret/added");
let secret_deleted_path = repo_path("secret/deleted");
let became_secret_path = repo_path("file1");
let became_public_path = repo_path("file2");
let tree1 = create_tree(
repo,
&[
(secret_modified_path, "0"),
(secret_deleted_path, "0"),
(became_secret_path, "public"),
(became_public_path, "secret"),
],
);
let tree2 = create_tree(
repo,
&[
(secret_modified_path, "1"),
(secret_added_path, "1"),
(became_secret_path, "secret"),
(became_public_path, "public"),
],
);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
SecretBackend::adopt_git_repo(&workspace_root);
let mut ws = Workspace::load(
&settings,
&workspace_root,
&test_workspace.env.default_store_factories(),
&default_working_copy_factories(),
)
.unwrap();
// Reload commits from the store associated with the workspace
let repo = ws.repo_loader().load_at(repo.operation()).unwrap();
let commit1 = repo.store().get_commit(commit1.id()).unwrap();
let commit2 = repo.store().get_commit(commit2.id()).unwrap();
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
assert!(
!secret_modified_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!secret_added_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!secret_deleted_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
became_secret_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!became_public_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
assert!(
!secret_modified_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!secret_added_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!secret_deleted_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
!became_secret_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
assert!(
became_public_path
.to_fs_path_unchecked(&workspace_root)
.is_file()
);
}
#[test]
fn test_tree_builder_file_directory_transition() {
let test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let store = repo.store();
let mut ws = test_workspace.workspace;
let workspace_root = ws.workspace_root().to_owned();
let mut check_out_tree = |tree_id: &TreeId| {
let tree = repo.store().get_tree(RepoPathBuf::root(), tree_id).unwrap();
let commit = commit_with_tree(
repo.store(),
MergedTree::resolved(repo.store().clone(), tree.id().clone()),
);
ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
};
let parent_path = repo_path("foo/bar");
let child_path = repo_path("foo/bar/baz");
// Add file at parent_path
let mut tree_builder = TreeBuilder::new(store.clone(), store.empty_tree_id().clone());
tree_builder.set(
parent_path.to_owned(),
TreeValue::File {
id: testutils::write_file(store, parent_path, ""),
executable: false,
copy_id: CopyId::placeholder(),
},
);
let tree_id = tree_builder.write_tree().unwrap();
check_out_tree(&tree_id);
assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_file());
assert!(!child_path.to_fs_path_unchecked(&workspace_root).exists());
// Turn parent_path into directory, add file at child_path
let mut tree_builder = TreeBuilder::new(store.clone(), tree_id);
tree_builder.remove(parent_path.to_owned());
tree_builder.set(
child_path.to_owned(),
TreeValue::File {
id: testutils::write_file(store, child_path, ""),
executable: false,
copy_id: CopyId::placeholder(),
},
);
let tree_id = tree_builder.write_tree().unwrap();
check_out_tree(&tree_id);
assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_dir());
assert!(child_path.to_fs_path_unchecked(&workspace_root).is_file());
// Turn parent_path back to file
let mut tree_builder = TreeBuilder::new(store.clone(), tree_id);
tree_builder.remove(child_path.to_owned());
tree_builder.set(
parent_path.to_owned(),
TreeValue::File {
id: testutils::write_file(store, parent_path, ""),
executable: false,
copy_id: CopyId::placeholder(),
},
);
let tree_id = tree_builder.write_tree().unwrap();
check_out_tree(&tree_id);
assert!(parent_path.to_fs_path_unchecked(&workspace_root).is_file());
assert!(!child_path.to_fs_path_unchecked(&workspace_root).exists());
}
#[test]
fn test_conflicting_changes_on_disk() {
let test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let mut ws = test_workspace.workspace;
let workspace_root = ws.workspace_root().to_owned();
// file on disk conflicts with file in target commit
let file_file_path = repo_path("file-file");
// file on disk conflicts with directory in target commit
let file_dir_path = repo_path("file-dir");
// directory on disk conflicts with file in target commit
let dir_file_path = repo_path("dir-file");
let tree = create_tree(
repo,
&[
(file_file_path, "committed contents"),
(
&file_dir_path.join(repo_path_component("file")),
"committed contents",
),
(dir_file_path, "committed contents"),
],
);
let commit = commit_with_tree(repo.store(), tree);
std::fs::write(
file_file_path.to_fs_path_unchecked(&workspace_root),
"contents on disk",
)
.unwrap();
std::fs::write(
file_dir_path.to_fs_path_unchecked(&workspace_root),
"contents on disk",
)
.unwrap();
std::fs::create_dir(dir_file_path.to_fs_path_unchecked(&workspace_root)).unwrap();
std::fs::write(
dir_file_path
.to_fs_path_unchecked(&workspace_root)
.join("file"),
"contents on disk",
)
.unwrap();
let stats = ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
assert_eq!(
stats,
CheckoutStats {
updated_files: 0,
added_files: 3,
removed_files: 0,
skipped_files: 3
}
);
assert_eq!(
std::fs::read_to_string(file_file_path.to_fs_path_unchecked(&workspace_root)).ok(),
Some("contents on disk".to_string())
);
assert_eq!(
std::fs::read_to_string(file_dir_path.to_fs_path_unchecked(&workspace_root)).ok(),
Some("contents on disk".to_string())
);
assert_eq!(
std::fs::read_to_string(
dir_file_path
.to_fs_path_unchecked(&workspace_root)
.join("file")
)
.ok(),
Some("contents on disk".to_string())
);
}
#[test]
fn test_reset() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let op_id = repo.op_id().clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let ignored_path = repo_path("ignored");
let gitignore_path = repo_path(".gitignore");
let tree_without_file = create_tree(repo, &[(gitignore_path, "ignored\n")]);
let commit_without_file = commit_with_tree(repo.store(), tree_without_file.clone());
let tree_with_file = create_tree(
repo,
&[(gitignore_path, "ignored\n"), (ignored_path, "code")],
);
let commit_with_file = commit_with_tree(repo.store(), tree_with_file.clone());
let ws = &mut test_workspace.workspace;
let commit = commit_with_tree(repo.store(), tree_with_file.clone());
ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
// Test the setup: the file should exist on disk and in the tree state.
assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(ignored_path));
// After we reset to the commit without the file, it should still exist on disk,
// but it should not be in the tree state, and it should not get added when we
// commit the working copy (because it's ignored).
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws
.locked_wc()
.reset(&commit_without_file)
.block_on()
.unwrap();
locked_ws.finish(op_id.clone()).unwrap();
assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(!wc.file_states().unwrap().contains_path(ignored_path));
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree_without_file);
// Now test the opposite direction: resetting to a commit where the file is
// tracked. The file should become tracked (even though it's ignored).
let ws = &mut test_workspace.workspace;
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws
.locked_wc()
.reset(&commit_with_file)
.block_on()
.unwrap();
locked_ws.finish(op_id.clone()).unwrap();
assert!(ignored_path.to_fs_path_unchecked(&workspace_root).is_file());
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(ignored_path));
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree_with_file);
}
#[test]
fn test_checkout_discard() {
// Start a mutation, do a checkout, and then discard the mutation. The working
// copy files should remain changed, but the state files should not be
// written.
let mut test_workspace = TestWorkspace::init();
let repo = test_workspace.repo.clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file1_path = repo_path("file1");
let file2_path = repo_path("file2");
let store = repo.store();
let tree1 = create_tree(&repo, &[(file1_path, "contents")]);
let tree2 = create_tree(&repo, &[(file2_path, "contents")]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
let state_path = wc.state_path().to_path_buf();
// Test the setup: the file should exist on disk and in the tree state.
assert!(file1_path.to_fs_path_unchecked(&workspace_root).is_file());
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(file1_path));
// Start a checkout
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws
.locked_wc()
.check_out(&commit2)
.block_on()
.unwrap();
// The change should be reflected in the working copy but not saved
assert!(!file1_path.to_fs_path_unchecked(&workspace_root).is_file());
assert!(file2_path.to_fs_path_unchecked(&workspace_root).is_file());
let reloaded_wc = LocalWorkingCopy::load(
store.clone(),
workspace_root.clone(),
state_path.clone(),
repo.settings(),
)
.unwrap();
assert!(reloaded_wc.file_states().unwrap().contains_path(file1_path));
assert!(!reloaded_wc.file_states().unwrap().contains_path(file2_path));
drop(locked_ws);
// The change should remain in the working copy, but not in memory and not saved
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert!(wc.file_states().unwrap().contains_path(file1_path));
assert!(!wc.file_states().unwrap().contains_path(file2_path));
assert!(!file1_path.to_fs_path_unchecked(&workspace_root).is_file());
assert!(file2_path.to_fs_path_unchecked(&workspace_root).is_file());
let reloaded_wc =
LocalWorkingCopy::load(store.clone(), workspace_root, state_path, repo.settings()).unwrap();
assert!(reloaded_wc.file_states().unwrap().contains_path(file1_path));
assert!(!reloaded_wc.file_states().unwrap().contains_path(file2_path));
}
#[test]
fn test_snapshot_file_directory_transition() {
let mut test_workspace = TestWorkspace::init();
let repo = test_workspace.repo.clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let to_ws_path = |path: &RepoPath| path.to_fs_path(&workspace_root).unwrap();
// file <-> directory transition at root and sub directories
let file1_path = repo_path("foo/bar");
let file2_path = repo_path("sub/bar/baz");
let file1p_path = file1_path.parent().unwrap();
let file2p_path = file2_path.parent().unwrap();
let tree1 = create_tree(&repo, &[(file1p_path, "1p"), (file2p_path, "2p")]);
let tree2 = create_tree(&repo, &[(file1_path, "1"), (file2_path, "2")]);
let commit1 = commit_with_tree(repo.store(), tree1.clone());
let commit2 = commit_with_tree(repo.store(), tree2.clone());
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
// file -> directory
std::fs::remove_file(to_ws_path(file1p_path)).unwrap();
std::fs::remove_file(to_ws_path(file2p_path)).unwrap();
std::fs::create_dir(to_ws_path(file1p_path)).unwrap();
std::fs::create_dir(to_ws_path(file2p_path)).unwrap();
std::fs::write(to_ws_path(file1_path), "1").unwrap();
std::fs::write(to_ws_path(file2_path), "2").unwrap();
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree2);
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
// directory -> file
std::fs::remove_file(to_ws_path(file1_path)).unwrap();
std::fs::remove_file(to_ws_path(file2_path)).unwrap();
std::fs::remove_dir(to_ws_path(file1p_path)).unwrap();
std::fs::remove_dir(to_ws_path(file2p_path)).unwrap();
std::fs::write(to_ws_path(file1p_path), "1p").unwrap();
std::fs::write(to_ws_path(file2p_path), "2p").unwrap();
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree1);
}
#[test]
fn test_materialize_snapshot_conflicted_files() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo.clone();
let ws = &mut test_workspace.workspace;
let workspace_root = ws.workspace_root().to_owned();
// Create tree with 3-sided conflict, with file1 and file2 having different
// conflicts:
// file1: A - A + A - B + C
// file2: A - B + C - D + D
let file1_path = repo_path("file1");
let file2_path = repo_path("file2");
let side1_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "1\n")]);
let base1_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "2\n")]);
let side2_tree = create_tree(repo, &[(file1_path, "a\n"), (file2_path, "4\n")]);
let base2_tree = create_tree(repo, &[(file1_path, "b\n"), (file2_path, "3\n")]);
let side3_tree = create_tree(repo, &[(file1_path, "c\n"), (file2_path, "3\n")]);
let merged_tree = MergedTree::merge(Merge::from_vec(vec![
(side1_tree, "side 1".into()),
(base1_tree, "base 1".into()),
(side2_tree, "side 2".into()),
(base2_tree, "base 2".into()),
(side3_tree, "side 3".into()),
]))
.block_on()
.unwrap();
let commit = commit_with_tree(repo.store(), merged_tree.clone());
let stats = ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
assert_eq!(
stats,
CheckoutStats {
updated_files: 0,
added_files: 2,
removed_files: 0,
skipped_files: 0
}
);
// Even though the tree-level conflict is a 3-sided conflict, each file is
// materialized as a 2-sided conflict.
let file1_value = merged_tree.path_value(file1_path).unwrap();
let file2_value = merged_tree.path_value(file2_path).unwrap();
assert_eq!(file1_value.num_sides(), 3);
assert_eq!(file2_value.num_sides(), 3);
insta::assert_snapshot!(
std::fs::read_to_string(file1_path.to_fs_path_unchecked(&workspace_root)).ok().unwrap(),
@r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: base 2
\\\\\\\ to: side 2
-b
+a
+++++++ side 3
c
>>>>>>> conflict 1 of 1 ends
");
insta::assert_snapshot!(
std::fs::read_to_string(file2_path.to_fs_path_unchecked(&workspace_root)).ok().unwrap(),
@r"
<<<<<<< conflict 1 of 1
%%%%%%% diff from: base 1
\\\\\\\ to: side 1
-2
+1
+++++++ side 2
4
>>>>>>> conflict 1 of 1 ends
");
// Editing a conflicted file should correctly propagate updates to each of
// the conflicting trees.
testutils::write_working_copy_file(
&workspace_root,
file1_path,
indoc! {"
<<<<<<< conflict 1 of 1
%%%%%%% diff from base to side #1
-b_edited
+a_edited
+++++++ side #2
c_edited
>>>>>>> conflict 1 of 1 ends
"},
);
let edited_tree = test_workspace.snapshot().unwrap();
let edited_file_value = edited_tree.path_value(file1_path).unwrap();
let edited_file_values = edited_file_value.iter().flatten().collect_vec();
assert_eq!(edited_file_values.len(), 5);
let get_file_id = |value: &TreeValue| match value {
TreeValue::File { id, .. } => id.clone(),
_ => panic!("unexpected value: {value:#?}"),
};
// The file IDs with indices 0 and 1 are the original unedited file values
// which were simplified.
let edited_file_file_id_0 = get_file_id(edited_file_values[0]);
assert_eq!(
testutils::read_file(repo.store(), file1_path, &edited_file_file_id_0),
b"a\n"
);
assert_eq!(edited_file_values[0], edited_file_values[1]);
let edited_file_file_id_2 = get_file_id(edited_file_values[2]);
assert_eq!(
testutils::read_file(repo.store(), file1_path, &edited_file_file_id_2),
b"a_edited\n"
);
let edited_file_file_id_3 = get_file_id(edited_file_values[3]);
assert_eq!(
testutils::read_file(repo.store(), file1_path, &edited_file_file_id_3),
b"b_edited\n"
);
let edited_file_file_id_4 = get_file_id(edited_file_values[4]);
assert_eq!(
testutils::read_file(repo.store(), file1_path, &edited_file_file_id_4),
b"c_edited\n"
);
}
#[test]
fn test_materialize_snapshot_unchanged_conflicts() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
// Both sides change "line 3" differently, right side deletes "line 5".
let base_content = indoc! {"
line 1
line 2
line 3
line 4
line 5
"};
let left_content = indoc! {"
line 1
line 2
left 3.1
left 3.2
left 3.3
line 4
line 5
"};
let right_content = indoc! {"
line 1
line 2
right 3.1
line 4
"};
let file_path = repo_path("file");
let base_tree = create_tree(repo, &[(file_path, base_content)]);
let left_tree = create_tree(repo, &[(file_path, left_content)]);
let right_tree = create_tree(repo, &[(file_path, right_content)]);
let merged_tree = MergedTree::merge(Merge::from_vec(vec![
(left_tree, "left".into()),
(base_tree, "base".into()),
(right_tree, "right".into()),
]))
.block_on()
.unwrap();
let commit = commit_with_tree(repo.store(), merged_tree.clone());
test_workspace
.workspace
.check_out(repo.op_id().clone(), None, &commit)
.unwrap();
// "line 5" should be deleted from the checked-out content.
let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
let materialized_content = std::fs::read_to_string(&disk_path).unwrap();
insta::assert_snapshot!(materialized_content, @r"
line 1
line 2
<<<<<<< conflict 1 of 1
+++++++ left
left 3.1
left 3.2
left 3.3
%%%%%%% diff from: base
\\\\\\\ to: right
-line 3
+right 3.1
>>>>>>> conflict 1 of 1 ends
line 4
");
let merged_tree_with_labels = MergedTree::new(
merged_tree.store().clone(),
merged_tree.tree_ids().clone(),
ConflictLabels::from_vec(vec![
"left label".into(),
"base label".into(),
"right label".into(),
]),
);
let commit_with_labels = commit_with_tree(repo.store(), merged_tree_with_labels.clone());
// When checking out a commit with the same conflicts but different labels, the
// file should still be updated.
let stats = test_workspace
.workspace
.check_out(repo.op_id().clone(), None, &commit_with_labels)
.unwrap();
assert_eq!(
stats,
CheckoutStats {
updated_files: 1,
..CheckoutStats::default()
}
);
let materialized_content = std::fs::read_to_string(&disk_path).unwrap();
insta::assert_snapshot!(materialized_content, @r"
line 1
line 2
<<<<<<< conflict 1 of 1
+++++++ left label
left 3.1
left 3.2
left 3.3
%%%%%%% diff from: base label
\\\\\\\ to: right label
-line 3
+right 3.1
>>>>>>> conflict 1 of 1 ends
line 4
");
// Update mtime to bypass file state comparison.
let file = File::options().write(true).open(&disk_path).unwrap();
file.set_modified(SystemTime::now() + Duration::from_secs(1))
.unwrap();
drop(file);
// Unchanged snapshot should be identical to the original even if "line 5"
// could be deleted from all sides.
let snapshotted_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(snapshotted_tree, merged_tree_with_labels);
}
struct SnapshotModifiedMaterializedConflictTestConfig {
base_contents: Option<&'static str>,
parent1_contents: Option<&'static str>,
parent2_contents: Option<&'static str>,
// Edit the conflict contents of the conflict file. The input is the parsed hunks of the
// conflict file. The contents of the conflict file will be replaced by the hunks returned.
get_new_merge_hunks: fn(Vec<Merge<BString>>) -> Vec<Merge<BString>>,
expected_file_contents: Merge<Option<&'static str>>,
}
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
for (i, side) in hunks[0].iter_mut().enumerate() {
if i == 0 {
side.extend(b"appended\n");
}
}
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\nappended\n"),
None,
Some("parent2\n"),
]),
}; "no base contents parent 1 appended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
for (i, side) in hunks[0].iter_mut().enumerate() {
if i == 2 {
side.extend(b"appended\n");
}
}
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\n"),
None,
Some("parent2\nappended\n"),
]),
}; "no base contents parent 2 appended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
for (i, side) in hunks[0].iter_mut().enumerate() {
if i == 0 || i == 2 {
side.extend(b"appended\n");
}
}
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\nappended\n"),
None,
Some("parent2\nappended\n"),
]),
}; "no base contents both parents appended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
hunks.push(Merge::resolved(BString::from("appended\n")));
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\nappended\n"),
// The file in the base change is also modified to preserve the materialized conflict.
Some("appended\n"),
Some("parent2\nappended\n"),
]),
}; "no base contents a new resolved hunk appended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
for side in &mut hunks[0] {
side.extend(b"appended\n");
}
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\nappended\n"),
// The file in the base change is also modified to preserve the materialized conflict.
Some("appended\n"),
Some("parent2\nappended\n"),
]),
}; "no base contents all sides of the existing hunk appended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
hunks[0].iter_mut().nth(1).unwrap().extend(b"new base\n");
hunks
},
// If the user adds contents to the absent side of a conflict hunk, we consider the conflict resolved.
expected_file_contents: Merge::from_vec(vec![
Some("parent1\n"),
// The file in the base change is modified to preserve the materialized conflict.
Some("new base\n"),
Some("parent2\n"),
]),
}; "no base contents base side appended only")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: None,
parent1_contents: Some("parent1\n"),
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
hunks.insert(0, Merge::resolved(BString::from("prepended\n")));
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("prepended\nparent1\n"),
// The file in the base change is also modified to preserve the materialized conflict.
Some("prepended\n"),
Some("prepended\nparent2\n"),
]),
}; "no base contents a new resolved hunk prepended")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: Some("base\n"),
parent1_contents: None,
parent2_contents: Some("parent2\n"),
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
hunks.push(Merge::resolved(BString::from("appended\n")));
hunks
},
expected_file_contents: Merge::from_vec(vec![
// The file in the parent1 change is also modified to preserve the materialized conflict.
Some("appended\n"),
Some("base\nappended\n"),
Some("parent2\nappended\n"),
]),
}; "file removed in parent1 a resolved hunk appended in merge")]
#[test_case(SnapshotModifiedMaterializedConflictTestConfig {
base_contents: Some("base\n"),
parent1_contents: Some("parent1\n"),
parent2_contents: None,
get_new_merge_hunks: |mut hunks: Vec<Merge<BString>>| {
hunks.push(Merge::resolved(BString::from("appended\n")));
hunks
},
expected_file_contents: Merge::from_vec(vec![
Some("parent1\nappended\n"),
Some("base\nappended\n"),
// The file in the parent2 change is also modified to preserve the materialized conflict.
Some("appended\n"),
]),
}; "file removed in parent2 a resolved hunk appended in merge")]
fn test_snapshot_modified_materialized_conflict(
SnapshotModifiedMaterializedConflictTestConfig {
base_contents,
parent1_contents,
parent2_contents,
get_new_merge_hunks,
expected_file_contents,
}: SnapshotModifiedMaterializedConflictTestConfig,
) {
// In this test, we create the following commits, checkout the merge commit,
// modify the merge contents, snapshot, and verify if the new merged tree is
// correct.
// D
// |\
// B C
// |/
// A
// We can't use the tokio runtime here because the test backend will create
// the tokio runtime in TestWorkspace::init, and tokio will panic if the
// tokio runtime is dropped in an async context. See
// https://docs.rs/tokio/1.47.1/tokio/runtime/struct.Handle.html#panics-2
// for details.
let mut test_workspace = TestWorkspace::init();
let file_repo_path = repo_path("test-file");
let file_disk_path = file_repo_path
.to_fs_path(test_workspace.workspace.workspace_root())
.unwrap();
// Create the commits with given contents.
let mut tx = test_workspace.repo.start_transaction();
let tree = create_tree(
&test_workspace.repo,
base_contents
.map(|contents| (file_repo_path, contents))
.as_slice(),
);
let base_commit = tx
.repo_mut()
.new_commit(
vec![test_workspace.repo.store().root_commit_id().clone()],
tree,
)
.write()
.unwrap();
let tree = create_tree(
&test_workspace.repo,
&parent1_contents
.map(|contents| (file_repo_path, contents))
.into_iter()
.collect::<Vec<_>>(),
);
let parent1_commit = tx
.repo_mut()
.new_commit(vec![base_commit.id().clone()], tree)
.write()
.unwrap();
let tree = create_tree(
&test_workspace.repo,
&parent2_contents
.map(|contents| (file_repo_path, contents))
.into_iter()
.collect::<Vec<_>>(),
);
let parent2_commit = tx
.repo_mut()
.new_commit(vec![base_commit.id().clone()], tree)
.write()
.unwrap();
// Update the repo to pick up the new commits.
test_workspace.repo = tx.commit("create parent commits").unwrap();
// Create the merge commit.
let tree = merge_commit_trees(&*test_workspace.repo, &[parent1_commit, parent2_commit])
.block_on()
.unwrap();
let merge_commit = commit_with_tree(test_workspace.repo.store(), tree);
// Checkout the merge commit.
test_workspace
.workspace
.check_out(test_workspace.repo.op_id().clone(), None, &merge_commit)
.unwrap();
let contents = std::fs::read(&file_disk_path).unwrap();
let hunks =
jj_lib::conflicts::parse_conflict(&contents, 2, jj_lib::conflicts::MIN_CONFLICT_MARKER_LEN)
.unwrap();
let hunks = get_new_merge_hunks(hunks);
let mut new_contents = vec![];
for hunk in hunks {
jj_lib::conflicts::materialize_merge_result(
&hunk,
&ConflictLabels::unlabeled(),
&mut new_contents,
&ConflictMaterializeOptions {
marker_style: jj_lib::conflicts::ConflictMarkerStyle::Diff,
marker_len: None,
merge: MergeOptions {
hunk_level: FileMergeHunkLevel::Line,
same_change: SameChange::Accept,
},
},
)
.unwrap();
}
std::fs::write(&file_disk_path, new_contents).unwrap();
// Snapshot.
let tree = test_workspace.snapshot().unwrap();
let actual_file_contents = tree
.path_value_async(file_repo_path)
.block_on()
.unwrap()
.try_map_async(async |tree_value| {
let Some(tree_value) = tree_value else {
return Ok::<_, Infallible>(None);
};
let TreeValue::File { id, .. } = tree_value else {
panic!("All sides of the conflict should be either a file or absent.");
};
let mut contents = vec![];
test_workspace
.repo
.store()
.read_file(file_repo_path, id)
.await
.unwrap()
.read_to_end(&mut contents)
.await
.unwrap();
Ok::<_, Infallible>(Some(String::from_utf8(contents).unwrap()))
})
.block_on()
.unwrap();
let expected_file_contents =
expected_file_contents.map(|contents| contents.as_deref().map(str::to_string));
assert_eq!(actual_file_contents, expected_file_contents);
}
#[test]
fn test_snapshot_racy_timestamps() {
// Tests that file modifications are detected even if they happen the same
// millisecond as the updated working copy state.
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = workspace_root.join("file");
let mut previous_tree = repo.store().empty_merged_tree();
for i in 0..100 {
std::fs::write(&file_path, format!("contents {i}").as_bytes()).unwrap();
let mut locked_ws = test_workspace
.workspace
.start_working_copy_mutation()
.unwrap();
let (new_tree, _stats) = locked_ws
.locked_wc()
.snapshot(&empty_snapshot_options())
.block_on()
.unwrap();
assert_ne!(new_tree.tree_ids(), previous_tree.tree_ids());
previous_tree = new_tree;
}
}
#[cfg(unix)]
#[test]
fn test_snapshot_special_file() {
// Tests that we ignore when special files (such as sockets and pipes) exist on
// disk.
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let ws = &mut test_workspace.workspace;
let file1_path = repo_path("file1");
let file1_disk_path = file1_path.to_fs_path_unchecked(&workspace_root);
std::fs::write(&file1_disk_path, "contents".as_bytes()).unwrap();
let file2_path = repo_path("file2");
let file2_disk_path = file2_path.to_fs_path_unchecked(&workspace_root);
std::fs::write(file2_disk_path, "contents".as_bytes()).unwrap();
let fifo_disk_path = workspace_root.join("fifo");
nix::unistd::mkfifo(&fifo_disk_path, nix::sys::stat::Mode::S_IRWXU).unwrap();
assert!(fifo_disk_path.exists());
assert!(!fifo_disk_path.is_file());
// Snapshot the working copy with the socket file
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
let (tree, _stats) = locked_ws
.locked_wc()
.snapshot(&empty_snapshot_options())
.block_on()
.unwrap();
locked_ws.finish(OperationId::from_hex("abc123")).unwrap();
// Only the regular files should be in the tree
assert_eq!(
tree.entries().map(|(path, _value)| path).collect_vec(),
to_owned_path_vec(&[file1_path, file2_path])
);
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert_eq!(
wc.file_states().unwrap().paths().collect_vec(),
vec![file1_path, file2_path]
);
// Replace a regular file by a socket and snapshot the working copy again
std::fs::remove_file(&file1_disk_path).unwrap();
nix::unistd::mkfifo(&file1_disk_path, nix::sys::stat::Mode::S_IRWXU).unwrap();
let tree = test_workspace.snapshot().unwrap();
// Only the regular file should be in the tree
assert_eq!(
tree.entries().map(|(path, _value)| path).collect_vec(),
to_owned_path_vec(&[file2_path])
);
let ws = &mut test_workspace.workspace;
let wc: &LocalWorkingCopy = ws.working_copy().downcast_ref().unwrap();
assert_eq!(
wc.file_states().unwrap().paths().collect_vec(),
vec![file2_path]
);
}
#[test]
fn test_gitignores() {
// Tests that .gitignore files are respected.
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let gitignore_path = repo_path(".gitignore");
let added_path = repo_path("added");
let modified_path = repo_path("modified");
let removed_path = repo_path("removed");
let ignored_path = repo_path("ignored");
let subdir_modified_path = repo_path("dir/modified");
let subdir_ignored_path = repo_path("dir/ignored");
testutils::write_working_copy_file(&workspace_root, gitignore_path, "ignored\n");
testutils::write_working_copy_file(&workspace_root, modified_path, "1");
testutils::write_working_copy_file(&workspace_root, removed_path, "1");
std::fs::create_dir(workspace_root.join("dir")).unwrap();
testutils::write_working_copy_file(&workspace_root, subdir_modified_path, "1");
let tree1 = test_workspace.snapshot().unwrap();
let files1 = tree1.entries().map(|(name, _value)| name).collect_vec();
assert_eq!(
files1,
to_owned_path_vec(&[
gitignore_path,
subdir_modified_path,
modified_path,
removed_path,
])
);
testutils::write_working_copy_file(
&workspace_root,
gitignore_path,
"ignored\nmodified\nremoved\n",
);
testutils::write_working_copy_file(&workspace_root, added_path, "2");
testutils::write_working_copy_file(&workspace_root, modified_path, "2");
std::fs::remove_file(removed_path.to_fs_path_unchecked(&workspace_root)).unwrap();
testutils::write_working_copy_file(&workspace_root, ignored_path, "2");
testutils::write_working_copy_file(&workspace_root, subdir_modified_path, "2");
testutils::write_working_copy_file(&workspace_root, subdir_ignored_path, "2");
let tree2 = test_workspace.snapshot().unwrap();
let files2 = tree2.entries().map(|(name, _value)| name).collect_vec();
assert_eq!(
files2,
to_owned_path_vec(&[
gitignore_path,
added_path,
subdir_modified_path,
modified_path,
])
);
}
#[test]
fn test_gitignores_in_ignored_dir() {
// Tests that .gitignore files in an ignored directory are ignored, i.e. that
// they cannot override the ignores from the parent
let mut test_workspace = TestWorkspace::init();
let op_id = test_workspace.repo.op_id().clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let gitignore_path = repo_path(".gitignore");
let nested_gitignore_path = repo_path("ignored/.gitignore");
let ignored_path = repo_path("ignored/file");
let tree1 = create_tree(&test_workspace.repo, &[(gitignore_path, "ignored\n")]);
let commit1 = commit_with_tree(test_workspace.repo.store(), tree1.clone());
let ws = &mut test_workspace.workspace;
ws.check_out(op_id.clone(), None, &commit1).unwrap();
testutils::write_working_copy_file(&workspace_root, nested_gitignore_path, "!file\n");
testutils::write_working_copy_file(&workspace_root, ignored_path, "contents");
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree1);
// The nested .gitignore is ignored even if it's tracked
let tree2 = create_tree(
&test_workspace.repo,
&[
(gitignore_path, "ignored\n"),
(nested_gitignore_path, "!file\n"),
],
);
let commit2 = commit_with_tree(test_workspace.repo.store(), tree2.clone());
let mut locked_ws = test_workspace
.workspace
.start_working_copy_mutation()
.unwrap();
locked_ws.locked_wc().reset(&commit2).block_on().unwrap();
locked_ws.finish(OperationId::from_hex("abc123")).unwrap();
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, tree2);
}
#[test]
fn test_gitignores_checkout_never_overwrites_ignored() {
// Tests that a .gitignore'd file doesn't get overwritten if check out a commit
// where the file is tracked.
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
// Write an ignored file called "modified" to disk
let gitignore_path = repo_path(".gitignore");
testutils::write_working_copy_file(&workspace_root, gitignore_path, "modified\n");
let modified_path = repo_path("modified");
testutils::write_working_copy_file(&workspace_root, modified_path, "garbage");
// Create a tree that adds the same file but with different contents
let tree = create_tree(repo, &[(modified_path, "contents")]);
let commit = commit_with_tree(repo.store(), tree);
// Now check out the tree that adds the file "modified" with contents
// "contents". The exiting contents ("garbage") shouldn't be replaced in the
// working copy.
let ws = &mut test_workspace.workspace;
assert!(ws.check_out(repo.op_id().clone(), None, &commit,).is_ok());
// Check that the old contents are in the working copy
let path = workspace_root.join("modified");
assert!(path.is_file());
assert_eq!(std::fs::read(&path).unwrap(), b"garbage");
}
#[test]
fn test_gitignores_ignored_directory_already_tracked() {
// Tests that a .gitignore'd directory that already has a tracked file in it
// does not get removed when snapshotting the working directory.
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let repo = test_workspace.repo.clone();
let gitignore_path = repo_path(".gitignore");
let unchanged_normal_path = repo_path("ignored/unchanged_normal");
let modified_normal_path = repo_path("ignored/modified_normal");
let deleted_normal_path = repo_path("ignored/deleted_normal");
let unchanged_executable_path = repo_path("ignored/unchanged_executable");
let modified_executable_path = repo_path("ignored/modified_executable");
let deleted_executable_path = repo_path("ignored/deleted_executable");
let unchanged_symlink_path = repo_path("ignored/unchanged_symlink");
let modified_symlink_path = repo_path("ignored/modified_symlink");
let deleted_symlink_path = repo_path("ignored/deleted_symlink");
let tree = create_tree_with(&repo, |builder| {
builder.file(gitignore_path, "/ignored/\n");
builder.file(unchanged_normal_path, "contents");
builder.file(modified_normal_path, "contents");
builder.file(deleted_normal_path, "contents");
builder
.file(unchanged_executable_path, "contents")
.executable(true);
builder
.file(modified_executable_path, "contents")
.executable(true);
builder
.file(deleted_executable_path, "contents")
.executable(true);
builder.symlink(unchanged_symlink_path, "contents");
builder.symlink(modified_symlink_path, "contents");
builder.symlink(deleted_symlink_path, "contents");
});
let commit = commit_with_tree(repo.store(), tree);
// Check out the tree with the files in `ignored/`
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
// Make some changes inside the ignored directory and check that they are
// detected when we snapshot. The files that are still there should not be
// deleted from the resulting tree.
std::fs::write(
modified_normal_path.to_fs_path_unchecked(&workspace_root),
"modified",
)
.unwrap();
std::fs::remove_file(deleted_normal_path.to_fs_path_unchecked(&workspace_root)).unwrap();
std::fs::write(
modified_executable_path.to_fs_path_unchecked(&workspace_root),
"modified",
)
.unwrap();
std::fs::remove_file(deleted_executable_path.to_fs_path_unchecked(&workspace_root)).unwrap();
let fs_path = modified_symlink_path.to_fs_path_unchecked(&workspace_root);
std::fs::remove_file(&fs_path).unwrap();
if check_symlink_support().unwrap_or(false) {
symlink_file("modified", &fs_path).unwrap();
} else {
std::fs::write(fs_path, "modified").unwrap();
}
std::fs::remove_file(deleted_symlink_path.to_fs_path_unchecked(&workspace_root)).unwrap();
let new_tree = test_workspace.snapshot().unwrap();
let expected_tree = create_tree_with(&repo, |builder| {
builder.file(gitignore_path, "/ignored/\n");
builder.file(unchanged_normal_path, "contents");
builder.file(modified_normal_path, "modified");
builder
.file(unchanged_executable_path, "contents")
.executable(true);
builder
.file(modified_executable_path, "modified")
.executable(true);
builder.symlink(unchanged_symlink_path, "contents");
builder.symlink(modified_symlink_path, "modified");
});
assert_tree_eq!(new_tree, expected_tree);
}
#[test]
fn test_dotgit_ignored() {
// Tests that .git directories and files are always ignored (we could accept
// them if the backend is not git).
let mut test_workspace = TestWorkspace::init();
let store = test_workspace.repo.store().clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
// Test with a .git/ directory (with a file in, since we don't write empty
// trees)
let dotgit_path = workspace_root.join(".git");
std::fs::create_dir(&dotgit_path).unwrap();
testutils::write_working_copy_file(&workspace_root, repo_path(".git/file"), "contents");
let new_tree = test_workspace.snapshot().unwrap();
let empty_tree = store.empty_merged_tree();
assert_tree_eq!(new_tree, empty_tree);
std::fs::remove_dir_all(&dotgit_path).unwrap();
// Test with a .git file
testutils::write_working_copy_file(&workspace_root, repo_path(".git"), "contents");
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, empty_tree);
std::fs::remove_file(workspace_root.join(".git")).unwrap();
// Test a nested repository foo/ containing .git and f.
let foo_path = workspace_root.join("foo");
std::fs::create_dir(&foo_path).unwrap();
testutils::write_working_copy_file(&workspace_root, repo_path("foo/.git"), "");
testutils::write_working_copy_file(&workspace_root, repo_path("foo/f"), "contents");
let new_tree = test_workspace.snapshot().unwrap();
assert_tree_eq!(new_tree, empty_tree);
std::fs::remove_dir_all(&foo_path).unwrap();
}
#[test_case(""; "ignore nothing")]
#[test_case("/*\n"; "ignore all")]
fn test_git_submodule(gitignore_content: &str) {
// Tests that git submodules are ignored.
let mut test_workspace = TestWorkspace::init_with_backend(TestRepoBackend::Git);
let repo = test_workspace.repo.clone();
let store = repo.store().clone();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let base_ignores = GitIgnoreFile::empty()
.chain("", Path::new(""), gitignore_content.as_bytes())
.unwrap();
let snapshot_options = SnapshotOptions {
base_ignores,
..empty_snapshot_options()
};
let mut tx = repo.start_transaction();
// Add files in sub directory. Sub directories are traversed differently
// depending on .gitignore. #5246
let added_path = repo_path("sub/added");
let submodule_path = repo_path("sub/module");
let added_submodule_path = repo_path("sub/module/added");
let mut tree_builder = MergedTreeBuilder::new(store.empty_merged_tree());
tree_builder.set_or_remove(
added_path.to_owned(),
Merge::normal(TreeValue::File {
id: testutils::write_file(repo.store(), added_path, "added\n"),
executable: false,
copy_id: CopyId::new(vec![]),
}),
);
let submodule_id1 = write_random_commit(tx.repo_mut()).id().clone();
tree_builder.set_or_remove(
submodule_path.to_owned(),
Merge::normal(TreeValue::GitSubmodule(submodule_id1)),
);
let tree_id1 = tree_builder.write_tree().unwrap();
let commit1 = commit_with_tree(repo.store(), tree_id1.clone());
let mut tree_builder = MergedTreeBuilder::new(tree_id1.clone());
let submodule_id2 = write_random_commit(tx.repo_mut()).id().clone();
tree_builder.set_or_remove(
submodule_path.to_owned(),
Merge::normal(TreeValue::GitSubmodule(submodule_id2)),
);
let tree_id2 = tree_builder.write_tree().unwrap();
let commit2 = commit_with_tree(repo.store(), tree_id2.clone());
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
std::fs::create_dir(submodule_path.to_fs_path_unchecked(&workspace_root)).unwrap();
testutils::write_working_copy_file(
&workspace_root,
added_submodule_path,
"i am a file in a submodule\n",
);
// Check that the files present in the submodule are not tracked
// when we snapshot
let (new_tree, _stats) = test_workspace
.snapshot_with_options(&snapshot_options)
.unwrap();
assert_tree_eq!(new_tree, tree_id1);
// Check that the files in the submodule are not deleted
let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
assert!(
file_in_submodule_path.metadata().is_ok(),
"{file_in_submodule_path:?} should exist"
);
// Check out new commit updating the submodule, which shouldn't fail because
// of existing submodule files
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
// Check that the files in the submodule are not deleted
let file_in_submodule_path = added_submodule_path.to_fs_path_unchecked(&workspace_root);
assert!(
file_in_submodule_path.metadata().is_ok(),
"{file_in_submodule_path:?} should exist"
);
// Check that the files present in the submodule are not tracked
// when we snapshot
let (new_tree, _stats) = test_workspace
.snapshot_with_options(&snapshot_options)
.unwrap();
assert_tree_eq!(new_tree, tree_id2);
// Check out the empty tree, which shouldn't fail
let ws = &mut test_workspace.workspace;
let stats = ws
.check_out(repo.op_id().clone(), None, &store.root_commit())
.unwrap();
assert_eq!(stats.skipped_files, 1);
}
#[test]
fn test_check_out_existing_file_cannot_be_removed() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = repo_path("file");
let tree1 = create_tree(repo, &[(file_path, "0")]);
let tree2 = create_tree(repo, &[(file_path, "1")]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
// Make the parent directory readonly.
let writable_dir_perm = workspace_root.symlink_metadata().unwrap().permissions();
let mut readonly_dir_perm = writable_dir_perm.clone();
readonly_dir_perm.set_readonly(true);
std::fs::set_permissions(&workspace_root, readonly_dir_perm).unwrap();
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
std::fs::set_permissions(&workspace_root, writable_dir_perm).unwrap();
// TODO: find a way to trigger the error on Windows
if !cfg!(windows) {
assert_matches!(
result,
Err(CheckoutError::Other { message, .. }) if message.contains("Failed to remove")
);
}
}
#[test]
fn test_check_out_existing_file_replaced_with_directory() {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = repo_path("file");
let tree1 = create_tree(repo, &[(file_path, "0")]);
let tree2 = create_tree(repo, &[(file_path, "1")]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
std::fs::remove_file(file_path.to_fs_path_unchecked(&workspace_root)).unwrap();
std::fs::create_dir(file_path.to_fs_path_unchecked(&workspace_root)).unwrap();
// Checkout doesn't fail, but the file should be skipped.
let stats = ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
assert_eq!(stats.skipped_files, 1);
assert!(file_path.to_fs_path_unchecked(&workspace_root).is_dir());
}
#[test]
fn test_check_out_existing_directory_symlink() {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
// Creates a symlink in working directory, and a tree that will add a file
// under the symlinked directory.
symlink_dir("..", workspace_root.join("parent")).unwrap();
// Test two file paths writing to the same directory to ensure that
// any directory creation optimizations which depend on how
// `parent/escaped1` behaved don't allow `parent/escaped2` to be
// created
let file_path1 = repo_path("parent/escaped1");
let file_path2 = repo_path("parent/escaped2");
let tree = create_tree(repo, &[(file_path1, "contents"), (file_path2, "contents")]);
let commit = commit_with_tree(repo.store(), tree);
// Checkout doesn't fail, but the file should be skipped.
let ws = &mut test_workspace.workspace;
let stats = ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
assert_eq!(stats.skipped_files, 2);
// Therefore, "../escaped*" paths shouldn't be created.
assert!(!workspace_root.parent().unwrap().join("escaped1").exists());
assert!(!workspace_root.parent().unwrap().join("escaped2").exists());
}
#[test]
fn test_check_out_existing_directory_symlink_icase_fs() {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let is_icase_fs = check_icase_fs(&workspace_root);
// Creates a symlink in working directory, and a tree that will add a file
// under the symlinked directory.
symlink_dir("..", workspace_root.join("parent")).unwrap();
let file_path1 = repo_path("PARENT/escaped1");
let file_path2 = repo_path("PARENT/escaped2");
let tree = create_tree(repo, &[(file_path1, "contents"), (file_path2, "contents")]);
let commit = commit_with_tree(repo.store(), tree);
// Checkout doesn't fail, but the file should be skipped on icase fs.
let ws = &mut test_workspace.workspace;
let stats = ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
if is_icase_fs {
assert_eq!(stats.skipped_files, 2);
} else {
assert_eq!(stats.skipped_files, 0);
}
// Therefore, "../escaped*" paths shouldn't be created.
assert!(!workspace_root.parent().unwrap().join("escaped1").exists());
assert!(!workspace_root.parent().unwrap().join("escaped2").exists());
}
#[test_case(false; "symlink target does not exist")]
#[test_case(true; "symlink target exists")]
fn test_check_out_existing_file_symlink_icase_fs(victim_exists: bool) {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let is_icase_fs = check_icase_fs(&workspace_root);
// Creates a symlink in working directory, and a tree that will overwrite
// the symlink content.
symlink_file(
PathBuf::from_iter(["..", "pwned"]),
workspace_root.join("parent"),
)
.unwrap();
let victim_file_path = workspace_root.parent().unwrap().join("pwned");
if victim_exists {
std::fs::write(&victim_file_path, "old").unwrap();
}
assert_eq!(workspace_root.join("parent").exists(), victim_exists);
let file_path = repo_path("PARENT");
let tree = create_tree(repo, &[(file_path, "bad")]);
let commit = commit_with_tree(repo.store(), tree);
// Checkout doesn't fail, but the file should be skipped on icase fs.
let ws = &mut test_workspace.workspace;
let stats = ws.check_out(repo.op_id().clone(), None, &commit).unwrap();
if is_icase_fs {
assert_eq!(stats.skipped_files, 1);
} else {
assert_eq!(stats.skipped_files, 0);
}
// Therefore, "../pwned" shouldn't be updated.
if victim_exists {
assert_eq!(std::fs::read(&victim_file_path).unwrap(), b"old");
} else {
assert!(!victim_file_path.exists());
}
}
#[test]
fn test_check_out_file_removal_over_existing_directory_symlink() {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = repo_path("parent/escaped");
let tree1 = create_tree(repo, &[(file_path, "contents")]);
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Check out "parent/escaped".
let ws = &mut test_workspace.workspace;
ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
// Pretend that "parent" was a symlink, which might be created by
// e.g. checking out "PARENT" on case-insensitive fs. The file
// "parent/escaped" would be skipped in that case.
std::fs::remove_file(file_path.to_fs_path_unchecked(&workspace_root)).unwrap();
std::fs::remove_dir(workspace_root.join("parent")).unwrap();
symlink_dir("..", workspace_root.join("parent")).unwrap();
let victim_file_path = workspace_root.parent().unwrap().join("escaped");
std::fs::write(&victim_file_path, "").unwrap();
assert!(file_path.to_fs_path_unchecked(&workspace_root).exists());
// Check out empty tree, which tries to remove "parent/escaped".
let stats = ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
assert_eq!(stats.skipped_files, 1);
// "../escaped" shouldn't be removed.
assert!(victim_file_path.exists());
}
#[test_case(".git"; "reserved .git dir")]
#[test_case(".jj"; "reserved .jj dir")]
#[test_case("symlink"; "looped")]
#[test_case("unknown"; "dead")]
#[cfg_attr(windows, ignore = "Windows impl follows symlink")] // FIXME
fn test_check_out_symlink_unusual_target(link_target: &str) {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
std::fs::create_dir(workspace_root.join(".git")).unwrap();
let symlink_path = repo_path("symlink");
let symlink_disk_path = symlink_path.to_fs_path_unchecked(&workspace_root);
let tree1 = create_tree_with(repo, |builder| {
builder.symlink(symlink_path, link_target);
});
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Check out tree containing symlink
let ws = &mut test_workspace.workspace;
let stats = ws.check_out(repo.op_id().clone(), None, &commit1).unwrap();
assert_eq!(stats.added_files, 1);
// Symlink should be created
assert_eq!(
symlink_disk_path.read_link().unwrap().as_os_str(),
link_target
);
// Check out empty tree
let stats = ws.check_out(repo.op_id().clone(), None, &commit2).unwrap();
assert_eq!(stats.removed_files, 1);
// Symlink should be deleted
assert_matches!(
symlink_disk_path.symlink_metadata().map_err(|e| e.kind()),
Err(io::ErrorKind::NotFound)
);
}
#[test_case("../pwned"; "escape from root")]
#[test_case("sub/../../pwned"; "escape from sub dir")]
fn test_check_out_malformed_file_path(file_path_str: &str) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = repo_path(file_path_str);
let tree = create_tree(repo, &[(file_path, "contents")]);
let commit = commit_with_tree(repo.store(), tree);
// Checkout should fail
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit);
assert_matches!(result, Err(CheckoutError::InvalidRepoPath(_)));
// Therefore, "pwned" file shouldn't be created.
assert!(!workspace_root.join(file_path_str).exists());
assert!(!workspace_root.parent().unwrap().join("pwned").exists());
}
#[test_case(r"sub\..\../pwned"; "path separator")]
#[test_case("d:/pwned"; "drive letter")]
fn test_check_out_malformed_file_path_windows(file_path_str: &str) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let file_path = repo_path(file_path_str);
let tree = create_tree(repo, &[(file_path, "contents")]);
let commit = commit_with_tree(repo.store(), tree);
// Checkout should fail on Windows
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit);
if cfg!(windows) {
assert_matches!(result, Err(CheckoutError::InvalidRepoPath(_)));
} else {
assert_matches!(result, Ok(_));
}
// Therefore, "pwned" file shouldn't be created.
if cfg!(windows) {
assert!(!workspace_root.join(file_path_str).exists());
}
assert!(!workspace_root.parent().unwrap().join("pwned").exists());
}
#[test_case(".git"; "root .git file")]
#[test_case(".jj"; "root .jj file")]
#[test_case(".git/pwned"; "root .git dir")]
#[test_case(".jj/pwned"; "root .jj dir")]
#[test_case("sub/.git"; "sub .git file")]
#[test_case("sub/.jj"; "sub .jj file")]
#[test_case("sub/.git/pwned"; "sub .git dir")]
#[test_case("sub/.jj/pwned"; "sub .jj dir")]
fn test_check_out_reserved_file_path(file_path_str: &str) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
std::fs::create_dir(workspace_root.join(".git")).unwrap();
let file_path = repo_path(file_path_str);
let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
let tree1 = create_tree(repo, &[(file_path, "contents")]);
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Checkout should fail.
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit1);
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
// Therefore, "pwned" file shouldn't be created.
if ![".git", ".jj"].contains(&file_path_str) {
assert!(!disk_path.exists());
}
assert!(!workspace_root.join(".git").join("pwned").exists());
assert!(!workspace_root.join(".jj").join("pwned").exists());
assert!(!workspace_root.join("sub").join(".git").exists());
assert!(!workspace_root.join("sub").join(".jj").exists());
// Pretend that the checkout somehow succeeded.
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws.locked_wc().reset(&commit1).block_on().unwrap();
locked_ws.finish(repo.op_id().clone()).unwrap();
if ![".git", ".jj"].contains(&file_path_str) {
std::fs::create_dir_all(disk_path.parent().unwrap()).unwrap();
std::fs::write(&disk_path, "").unwrap();
}
// Check out empty tree, which tries to remove the file.
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
// The existing file shouldn't be removed.
assert!(disk_path.exists());
}
#[test_case(".Git/pwned"; "root .git dir")]
#[test_case(".jJ/pwned"; "root .jj dir")]
#[test_case("sub/.GIt"; "sub .git file")]
#[test_case("sub/.JJ"; "sub .jj file")]
#[test_case("sub/.gIT/pwned"; "sub .git dir")]
#[test_case("sub/.Jj/pwned"; "sub .jj dir")]
fn test_check_out_reserved_file_path_icase_fs(file_path_str: &str) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
std::fs::create_dir(workspace_root.join(".git")).unwrap();
let is_icase_fs = check_icase_fs(&workspace_root);
let file_path = repo_path(file_path_str);
let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
let tree1 = create_tree(repo, &[(file_path, "contents")]);
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Checkout should fail on icase fs.
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit1);
if is_icase_fs {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// Therefore, "pwned" file shouldn't be created.
if is_icase_fs {
assert!(!disk_path.exists());
}
assert!(!workspace_root.join(".git").join("pwned").exists());
assert!(!workspace_root.join(".jj").join("pwned").exists());
assert!(!workspace_root.join("sub").join(".git").exists());
assert!(!workspace_root.join("sub").join(".jj").exists());
// Pretend that the checkout somehow succeeded.
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws.locked_wc().reset(&commit1).block_on().unwrap();
locked_ws.finish(repo.op_id().clone()).unwrap();
std::fs::create_dir_all(disk_path.parent().unwrap()).unwrap();
std::fs::write(&disk_path, "").unwrap();
// Check out empty tree, which tries to remove the file.
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
if is_icase_fs {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// The existing file shouldn't be removed on icase fs.
if is_icase_fs {
assert!(disk_path.exists());
}
}
// Here we don't test ignored characters exhaustively because our implementation
// isn't using deny list.
#[test_case("\u{200c}.git/pwned"; "root .git dir")]
#[test_case(".\u{200d}jj/pwned"; "root .jj dir")]
#[test_case("sub/.g\u{200c}it"; "sub .git file")]
#[test_case("sub/.jj\u{200d}"; "sub .jj file")]
#[test_case("sub/.gi\u{200e}t/pwned"; "sub .git dir")]
#[test_case("sub/.jj\u{200f}/pwned"; "sub .jj dir")]
fn test_check_out_reserved_file_path_hfs_plus(file_path_str: &str) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
std::fs::create_dir(workspace_root.join(".git")).unwrap();
let is_hfs_plus = check_hfs_plus(&workspace_root);
let file_path = repo_path(file_path_str);
let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
let tree1 = create_tree(repo, &[(file_path, "contents")]);
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Checkout should fail on HFS+-like fs.
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit1);
if is_hfs_plus {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// Therefore, "pwned" file shouldn't be created.
if is_hfs_plus {
assert!(!disk_path.exists());
}
assert!(!workspace_root.join(".git").join("pwned").exists());
assert!(!workspace_root.join(".jj").join("pwned").exists());
assert!(!workspace_root.join("sub").join(".git").exists());
assert!(!workspace_root.join("sub").join(".jj").exists());
// Pretend that the checkout somehow succeeded.
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws.locked_wc().reset(&commit1).block_on().unwrap();
locked_ws.finish(repo.op_id().clone()).unwrap();
std::fs::create_dir_all(disk_path.parent().unwrap()).unwrap();
std::fs::write(&disk_path, "").unwrap();
// Check out empty tree, which tries to remove the file.
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
if is_hfs_plus {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// The existing file shouldn't be removed on HFS+-like fs.
if is_hfs_plus {
assert!(disk_path.exists());
}
}
#[test_case(".git/pwned", &["GIT~1/pwned", "GI2837~1/pwned"]; "root .git dir short name")]
#[test_case(".jj/pwned", &["JJ~1/pwned", "JJ2E09~1/pwned"]; "root .jj dir short name")]
#[test_case(".git/pwned", &[".GIT./pwned"]; "root .git dir trailing dots")]
#[test_case(".jj/pwned", &[".JJ../pwned"]; "root .jj dir trailing dots")]
#[test_case("sub/.git", &["sub/.GIT.."]; "sub .git file trailing dots")]
#[test_case("sub/.jj", &["sub/.JJ."]; "sub .jj file trailing dots")]
// TODO: Add more weird patterns?
// - https://en.wikipedia.org/wiki/8.3_filename
// - See is_ntfs_dotgit() of Git and pathauditor of Mercurial
fn test_check_out_reserved_file_path_vfat(vfat_path_str: &str, file_path_strs: &[&str]) {
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
std::fs::create_dir(workspace_root.join(".git")).unwrap();
let is_vfat = check_vfat(&workspace_root);
let vfat_disk_path = workspace_root.join(vfat_path_str);
let file_paths = file_path_strs.iter().map(|&s| repo_path(s)).collect_vec();
let tree1 = create_tree_with(repo, |builder| {
for path in file_paths {
builder.file(path, "contents");
}
});
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Checkout should fail on VFAT-like fs.
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit1);
if is_vfat {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// Therefore, "pwned" file shouldn't be created.
if is_vfat {
assert!(!vfat_disk_path.exists());
}
assert!(!workspace_root.join(".git").join("pwned").exists());
assert!(!workspace_root.join(".jj").join("pwned").exists());
assert!(!workspace_root.join("sub").join(".git").exists());
assert!(!workspace_root.join("sub").join(".jj").exists());
// Pretend that the checkout somehow succeeded.
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws.locked_wc().reset(&commit1).block_on().unwrap();
locked_ws.finish(repo.op_id().clone()).unwrap();
if is_vfat {
std::fs::create_dir_all(vfat_disk_path.parent().unwrap()).unwrap();
std::fs::write(&vfat_disk_path, "").unwrap();
}
// Check out empty tree, which tries to remove the file.
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
if is_vfat {
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
} else {
assert_matches!(result, Ok(_));
}
// The existing file shouldn't be removed on VFAT-like fs.
if is_vfat {
assert!(vfat_disk_path.exists());
}
}
#[test_case(".git"; "root .git file")]
#[test_case(".git/pwned"; "root .git dir")]
fn test_check_out_reserved_file_path_dot_git_symlink(file_path_str: &str) {
if !check_symlink_support().unwrap() {
eprintln!("Skipping test because symlink isn't supported");
return;
}
let mut test_workspace = TestWorkspace::init();
let repo = &test_workspace.repo;
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
// Create symlink .git -> ../git-repo
let git_repo_dir = test_workspace.env.root().join("git-repo");
let dot_git_path = workspace_root.join(".git");
std::fs::create_dir(&git_repo_dir).unwrap();
symlink_dir(&git_repo_dir, &dot_git_path).unwrap();
assert!(dot_git_path.exists());
let file_path = repo_path(file_path_str);
let disk_path = file_path.to_fs_path_unchecked(&workspace_root);
let tree1 = create_tree(repo, &[(file_path, "contents")]);
let tree2 = create_tree(repo, &[]);
let commit1 = commit_with_tree(repo.store(), tree1);
let commit2 = commit_with_tree(repo.store(), tree2);
// Checkout should fail.
let ws = &mut test_workspace.workspace;
let result = ws.check_out(repo.op_id().clone(), None, &commit1);
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
// Therefore, "pwned" file shouldn't be created.
assert!(!git_repo_dir.join("pwned").exists());
assert!(!dot_git_path.join("pwned").exists());
// Pretend that the checkout somehow succeeded.
let mut locked_ws = ws.start_working_copy_mutation().unwrap();
locked_ws.locked_wc().reset(&commit1).block_on().unwrap();
locked_ws.finish(repo.op_id().clone()).unwrap();
if file_path_str != ".git" {
std::fs::write(&disk_path, "").unwrap();
}
// Check out empty tree, which tries to remove the file.
let result = ws.check_out(repo.op_id().clone(), None, &commit2);
assert_matches!(result, Err(CheckoutError::ReservedPathComponent { .. }));
// The existing file shouldn't be removed.
assert!(disk_path.exists());
}
#[test]
fn test_fsmonitor() {
let test_repo = TestRepo::init();
let repo = &test_repo.repo;
let workspace_root = test_repo.env.root().join("workspace");
let state_path = test_repo.env.root().join("state");
std::fs::create_dir(&workspace_root).unwrap();
std::fs::create_dir(&state_path).unwrap();
let tree_state_settings = TreeStateSettings::try_from_user_settings(repo.settings()).unwrap();
TreeState::init(
repo.store().clone(),
workspace_root.clone(),
state_path.clone(),
&tree_state_settings,
)
.unwrap();
let foo_path = repo_path("foo");
let bar_path = repo_path("bar");
let nested_path = repo_path("path/to/nested");
testutils::write_working_copy_file(&workspace_root, foo_path, "foo\n");
testutils::write_working_copy_file(&workspace_root, bar_path, "bar\n");
testutils::write_working_copy_file(&workspace_root, nested_path, "nested\n");
let ignored_path = repo_path("path/to/ignored");
let gitignore_path = repo_path("path/.gitignore");
testutils::write_working_copy_file(&workspace_root, ignored_path, "ignored\n");
testutils::write_working_copy_file(&workspace_root, gitignore_path, "to/ignored\n");
let snapshot = |paths: &[&RepoPath]| {
let changed_files = paths
.iter()
.map(|p| p.to_fs_path_unchecked(Path::new("")))
.collect();
let settings = TreeStateSettings {
fsmonitor_settings: FsmonitorSettings::Test { changed_files },
..tree_state_settings.clone()
};
let mut tree_state = TreeState::load(
repo.store().clone(),
workspace_root.clone(),
state_path.clone(),
&settings,
)
.unwrap();
tree_state
.snapshot(&empty_snapshot_options())
.block_on()
.unwrap();
tree_state
};
let tree_state = snapshot(&[]);
assert_tree_eq!(*tree_state.current_tree(), repo.store().empty_merged_tree());
let tree_state = snapshot(&[foo_path]);
insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
merged tree (sides: 1)
tree 2a5341b103917cfdb48a
file "foo" (e99c2057c15160add351): "foo\n"
"#);
let mut tree_state = snapshot(&[foo_path, bar_path, nested_path, ignored_path]);
insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
merged tree (sides: 1)
tree 1c5c336421714b1df7bb
file "bar" (94cc973e7e1aefb7eff6): "bar\n"
file "foo" (e99c2057c15160add351): "foo\n"
file "path/to/nested" (6209060941cd770c8d46): "nested\n"
"#);
tree_state.save().unwrap();
testutils::write_working_copy_file(&workspace_root, foo_path, "updated foo\n");
testutils::write_working_copy_file(&workspace_root, bar_path, "updated bar\n");
let tree_state = snapshot(&[foo_path]);
insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
merged tree (sides: 1)
tree f653dfa18d0b025bdb9e
file "bar" (94cc973e7e1aefb7eff6): "bar\n"
file "foo" (e0fbd106147cc04ccd05): "updated foo\n"
file "path/to/nested" (6209060941cd770c8d46): "nested\n"
"#);
std::fs::remove_file(foo_path.to_fs_path_unchecked(&workspace_root)).unwrap();
let mut tree_state = snapshot(&[foo_path]);
insta::assert_snapshot!(testutils::dump_tree(tree_state.current_tree()), @r#"
merged tree (sides: 1)
tree b7416fc248a038b920c3
file "bar" (94cc973e7e1aefb7eff6): "bar\n"
file "path/to/nested" (6209060941cd770c8d46): "nested\n"
"#);
tree_state.save().unwrap();
}
#[test]
fn test_snapshot_max_new_file_size() {
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let small_path = repo_path("small");
let large_path = repo_path("large");
let limit: usize = 1024;
std::fs::write(
small_path.to_fs_path_unchecked(&workspace_root),
vec![0; limit],
)
.unwrap();
let options = SnapshotOptions {
max_new_file_size: limit as u64,
..empty_snapshot_options()
};
test_workspace
.snapshot_with_options(&options)
.expect("files exactly matching the size limit should succeed");
std::fs::write(
small_path.to_fs_path_unchecked(&workspace_root),
vec![0; limit + 1],
)
.unwrap();
let (old_tree, _stats) = test_workspace
.snapshot_with_options(&options)
.expect("existing files may grow beyond the size limit");
// A new file of 1KiB + 1 bytes should be left untracked
std::fs::write(
large_path.to_fs_path_unchecked(&workspace_root),
vec![0; limit + 1],
)
.unwrap();
let (new_tree, stats) = test_workspace
.snapshot_with_options(&options)
.expect("snapshot should not fail because of new files beyond the size limit");
assert_tree_eq!(new_tree, old_tree);
assert_eq!(
stats
.untracked_paths
.keys()
.map(AsRef::as_ref)
.collect_vec(),
[large_path]
);
assert_matches!(
stats.untracked_paths.values().next().unwrap(),
UntrackedReason::FileTooLarge { size, .. } if *size == (limit as u64) + 1
);
// A file in sub directory should also be caught
let sub_large_path = repo_path("sub/large");
std::fs::create_dir(
sub_large_path
.parent()
.unwrap()
.to_fs_path_unchecked(&workspace_root),
)
.unwrap();
std::fs::rename(
large_path.to_fs_path_unchecked(&workspace_root),
sub_large_path.to_fs_path_unchecked(&workspace_root),
)
.unwrap();
let (new_tree, stats) = test_workspace
.snapshot_with_options(&options)
.expect("snapshot should not fail because of new files beyond the size limit");
assert_tree_eq!(new_tree, old_tree);
assert_eq!(
stats
.untracked_paths
.keys()
.map(AsRef::as_ref)
.collect_vec(),
[sub_large_path]
);
assert_matches!(
stats.untracked_paths.values().next().unwrap(),
UntrackedReason::FileTooLarge { .. }
);
}
#[test]
fn test_snapshot_symlink_use_forward_slash() {
if !file_util::check_symlink_support().unwrap() {
eprintln!("Symlink not supported. Skip the test.");
}
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let target = repo_path("target/link/target.txt");
let target_path = target.to_fs_path(&workspace_root).unwrap();
std::fs::create_dir_all(target_path.parent().unwrap()).unwrap();
std::fs::write(&target_path, "a\n").unwrap();
let link = repo_path("link/link.txt");
let link_path = link.to_fs_path(&workspace_root).unwrap();
let link_contents = "../target/link/target.txt";
std::fs::create_dir_all(link_path.parent().unwrap()).unwrap();
symlink_file(link_contents, link_path).unwrap();
let tree = test_workspace
.snapshot()
.expect("Snapshot with symlink should succeed.");
let tree_value = tree
.path_value(link)
.expect("Failed to retrieve the MergedTreeValue from the path.")
.into_resolved()
.expect("Shouldn't have conflicts.")
.expect("The link path should exist.");
let TreeValue::Symlink(symlink_id) = tree_value.clone() else {
panic!(
"Expect {} to be a symlink, but got {:?}",
link.as_internal_file_string(),
tree_value
);
};
let actual_link_contents = test_workspace
.repo
.store()
.read_symlink(link, &symlink_id)
.block_on()
.unwrap();
assert!(
!actual_link_contents.contains("\\"),
"Expect the symlink in the Store to use \"/\" as the separator, but got \
{actual_link_contents}."
);
}
fn is_verbatim_path(path: &Path) -> bool {
let Some(Component::Prefix(prefix)) = path.components().next() else {
return false;
};
prefix.kind().is_verbatim()
}
#[cfg(windows)]
fn absolute_path_to_verbatim_path(input: &Path) -> PathBuf {
use std::ffi::OsString;
use std::path::Prefix;
use bstr::ByteSlice as _;
assert!(input.is_absolute());
let input = input.canonicalize().unwrap();
let mut components = input.components();
let Component::Prefix(prefix_component) = components.next().unwrap() else {
panic!("target should be an absolute path after being canonicalized");
};
let mut verbatim_path = match prefix_component.kind() {
// C: -> \\?\Global\C:
// \\?\C: -> \\?\Global\C:
//
// Prefix the path with Global, so that when we read back the symlink, it's still a verbatim
// path. The symlink to a \\?\C: prefixed path(e.g., \\?\C:\file.txt) will be converted to a
// not verbatim path(e.g., C:\file.txt) when calling read_link.
Prefix::Disk(disk) | Prefix::VerbatimDisk(disk) => {
let mut verbatim_prefix = OsString::from(r"\\?\Global\");
verbatim_prefix.push([disk].to_os_str().unwrap());
verbatim_prefix.push(":");
verbatim_prefix
}
_ => panic!("Unsupported path: {}", input.display()),
};
verbatim_path.push(components.as_path().as_os_str());
let verbatim_path = PathBuf::from(verbatim_path);
assert!(is_verbatim_path(&verbatim_path));
verbatim_path
}
#[test_case(|link, target| file_util::relative_path(link.parent().unwrap(), target); "relative")]
#[test_case(|_, target| {
assert!(target.is_absolute());
target.to_owned()
}; "absolute")]
#[cfg_attr(
windows,
test_case(|_, target: &Path| absolute_path_to_verbatim_path(target); "verbatim absolute")
)]
fn test_snapshot_and_update_valid_symlink(get_link_target: impl FnOnce(&Path, &Path) -> PathBuf) {
if !file_util::check_symlink_support().unwrap() {
eprintln!("Symlink not supported. Skip the test.");
}
let mut test_workspace = TestWorkspace::init();
let workspace_root = test_workspace.workspace.workspace_root().to_owned();
let target = repo_path("target/link/target.txt");
let target_path = target.to_fs_path(&workspace_root).unwrap();
std::fs::create_dir_all(target_path.parent().unwrap()).unwrap();
// Unique contents that it's unlikely that we match accidentally.
let file_contents = b"18bHZD165T@C\n";
std::fs::write(&target_path, file_contents).unwrap();
let link = repo_path("link/link.txt");
let link_path = link.to_fs_path(&workspace_root).unwrap();
let link_contents = get_link_target(&link_path, &target_path);
std::fs::create_dir_all(link_path.parent().unwrap()).unwrap();
symlink_file(&link_contents, &link_path).unwrap();
std::fs::read_link(&link_path).expect("The symlink itself should exist.");
assert_eq!(std::fs::read(&link_path).unwrap(), file_contents);
assert_eq!(
is_verbatim_path(&std::fs::read_link(&link_path).unwrap()),
is_verbatim_path(&link_contents),
"Make sure that when we test with a verbatim path, it's still a verbatim path in the \
Store when snapshotting."
);
let tree = test_workspace
.snapshot()
.expect("Snapshot with symlink should succeed.");
let commit = commit_with_tree(test_workspace.repo.store(), tree);
// Checkout the root commit to clear the workspace.
let mut locked_ws = test_workspace
.workspace
.start_working_copy_mutation()
.unwrap();
let root_commit = test_workspace.repo.store().root_commit();
locked_ws
.locked_wc()
.check_out(&root_commit)
.block_on()
.unwrap();
locked_ws
.finish(test_workspace.repo.op_id().clone())
.unwrap();
assert!(!std::fs::exists(&link_path).unwrap());
assert!(std::fs::read_link(&link_path).is_err());
// Checkout the original commit back.
let mut locked_ws = test_workspace
.workspace
.start_working_copy_mutation()
.unwrap();
locked_ws.locked_wc().check_out(&commit).block_on().unwrap();
locked_ws
.finish(test_workspace.repo.op_id().clone())
.unwrap();
let actual_target = std::fs::read_link(&link_path).expect("The symlink itself should exist.");
let actual_contents = std::fs::read(&link_path).unwrap_or_else(|e| {
panic!(
"Failed to read from the symlink at {}, which points to {}: {e:?}",
link_path.display(),
actual_target.display()
)
});
assert_eq!(actual_contents, file_contents);
assert_eq!(
is_verbatim_path(&std::fs::read_link(&link_path).unwrap()),
is_verbatim_path(&link_contents),
"When we checkout a symlink to a verbatim path, it should still point to a verbatim path."
);
}
|