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 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
@testable import CoreCommands
@testable import Commands
import Foundation
import PackageGraph
import PackageLoading
import PackageModel
import SourceControl
import SPMTestSupport
import Workspace
import XCTest
import struct TSCBasic.ByteString
import class TSCBasic.BufferedOutputByteStream
import class TSCBasic.InMemoryFileSystem
import enum TSCBasic.JSON
import class Basics.AsyncProcess
final class PackageCommandTests: CommandsTestCase {
@discardableResult
private func execute(
_ args: [String] = [],
packagePath: AbsolutePath? = nil,
env: Environment? = nil
) async throws -> (stdout: String, stderr: String) {
var environment = env ?? [:]
// don't ignore local packages when caching
environment["SWIFTPM_TESTS_PACKAGECACHE"] = "1"
return try await SwiftPM.Package.execute(args, packagePath: packagePath, env: environment)
}
func testNoParameters() async throws {
let stdout = try await execute().stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package"))
}
func testUsage() async throws {
do {
_ = try await execute(["-help"])
XCTFail("expecting `execute` to fail")
} catch SwiftPMError.executionFailure(_, _, let stderr) {
XCTAssertMatch(stderr, .contains("Usage: swift package"))
} catch {
throw error
}
}
func testSeeAlso() async throws {
let stdout = try await execute(["--help"]).stdout
XCTAssertMatch(stdout, .contains("SEE ALSO: swift build, swift run, swift test"))
}
func testVersion() async throws {
let stdout = try await execute(["--version"]).stdout
XCTAssertMatch(stdout, .contains("Swift Package Manager"))
}
func testCompletionTool() async throws {
let stdout = try await execute(["completion-tool", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OVERVIEW: Completion command (for shell completions)"))
}
func testInitOverview() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OVERVIEW: Initialize a new package"))
}
func testInitUsage() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("USAGE: swift package init [--type <type>] "))
XCTAssertMatch(stdout, .contains(" [--name <name>]"))
}
func testInitOptionsHelp() async throws {
let stdout = try await execute(["init", "--help"]).stdout
XCTAssertMatch(stdout, .contains("OPTIONS:"))
}
func testPlugin() async throws {
await XCTAssertThrowsCommandExecutionError(try await execute(["plugin"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Missing expected plugin command"))
}
}
func testUnknownOption() async throws {
await XCTAssertThrowsCommandExecutionError(try await execute(["--foo"])) { error in
XCTAssertMatch(error.stderr, .contains("error: Unknown option '--foo'"))
}
}
func testUnknownSubommand() async throws {
try await fixture(name: "Miscellaneous/ExeTest") { fixturePath in
await XCTAssertThrowsCommandExecutionError(try await execute(["foo"], packagePath: fixturePath)) { error in
XCTAssertMatch(error.stderr, .contains("Unknown subcommand or plugin name ‘foo’"))
}
}
}
func testNetrc() async throws {
try await fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
// --enable-netrc flag
try await self.execute(["resolve", "--enable-netrc"], packagePath: fixturePath)
// --disable-netrc flag
try await self.execute(["resolve", "--disable-netrc"], packagePath: fixturePath)
// --enable-netrc and --disable-netrc flags
await XCTAssertAsyncThrowsError(
try await self.execute(["resolve", "--enable-netrc", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Value to be set with flag '--disable-netrc' had already been set with flag '--enable-netrc'"))
}
}
}
func testNetrcFile() async throws {
try await fixture(name: "DependencyResolution/External/XCFramework") { fixturePath in
let fs = localFileSystem
let netrcPath = fixturePath.appending(".netrc")
try fs.writeFileContents(
netrcPath,
string: "machine mymachine.labkey.org login user@labkey.org password mypassword"
)
// valid .netrc file path
try await execute(["resolve", "--netrc-file", netrcPath.pathString], packagePath: fixturePath)
// valid .netrc file path with --disable-netrc option
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", netrcPath.pathString, "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
// invalid .netrc file path
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", "/foo"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("Did not find netrc file at /foo."))
}
// invalid .netrc file path with --disable-netrc option
await XCTAssertAsyncThrowsError(
try await execute(["resolve", "--netrc-file", "/foo", "--disable-netrc"], packagePath: fixturePath)
) { error in
XCTAssertMatch(String(describing: error), .contains("'--disable-netrc' and '--netrc-file' are mutually exclusive"))
}
}
}
func testEnableDisableCache() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending("cache")
let repositoriesCachePath = cachePath.appending("repositories")
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try await self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
try await self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try await self.execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--enable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
do {
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
let (_, _) = try await self.execute(["resolve", "--disable-dependency-cache", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssertFalse(localFileSystem.exists(repositoriesCachePath))
}
}
}
func testResolve() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Check that `resolve` works.
_ = try await execute(["resolve"], packagePath: packageRoot)
let path = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
XCTAssertEqual(try GitRepository(path: path).getTags(), ["1.2.3"])
}
}
func testUpdate() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Perform an initial fetch.
_ = try await execute(["resolve"], packagePath: packageRoot)
do {
let checkoutPath = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
let checkoutRepo = GitRepository(path: checkoutPath)
XCTAssertEqual(try checkoutRepo.getTags(), ["1.2.3"])
_ = try checkoutRepo.revision(forTag: "1.2.3")
}
// update and retag the dependency, and update.
let repoPath = fixturePath.appending("Foo")
let repo = GitRepository(path: repoPath)
try localFileSystem.writeFileContents(repoPath.appending("test"), string: "test")
try repo.stageEverything()
try repo.commit()
try repo.tag(name: "1.2.4")
// we will validate it is there
let revision = try repo.revision(forTag: "1.2.4")
_ = try await execute(["update"], packagePath: packageRoot)
do {
// We shouldn't assume package path will be same after an update so ask again for it.
let checkoutPath = try SwiftPM.packagePath(for: "Foo", packageRoot: packageRoot)
let checkoutRepo = GitRepository(path: checkoutPath)
// tag may not be there, but revision should be after update
XCTAssertTrue(checkoutRepo.exists(revision: .init(identifier: revision)))
}
}
}
func testCache() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
let repositoriesPath = packageRoot.appending(components: ".build", "repositories")
let cachePath = fixturePath.appending("cache")
let repositoriesCachePath = cachePath.appending("repositories")
// Perform an initial fetch and populate the cache
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
// we have to check for the prefix here since the hash value changes because spm sees the `prefix`
// directory `/var/...` as `/private/var/...`.
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
// Remove .build folder
_ = try await execute(["reset"], packagePath: packageRoot)
// Perform another cache this time from the cache
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
// Remove .build and cache folder
_ = try await execute(["reset"], packagePath: packageRoot)
try localFileSystem.removeFileTree(cachePath)
// Perform another fetch
_ = try await execute(["resolve", "--cache-path", cachePath.pathString], packagePath: packageRoot)
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesPath).contains { $0.hasPrefix("Foo-") })
XCTAssert(try localFileSystem.getDirectoryContents(repositoriesCachePath).contains { $0.hasPrefix("Foo-") })
}
}
func testDescribe() async throws {
try await fixture(name: "Miscellaneous/ExeTest") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that tests don't appear in the product memberships.
XCTAssertEqual(json["name"]?.string, "ExeTest")
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertNil(jsonTarget0["product_memberships"])
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "Exe")
}
try await fixture(name: "CFamilyTargets/SwiftCMixed") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that the JSON description contains what we expect it to.
XCTAssertEqual(json["name"]?.string, "SwiftCMixed")
XCTAssertMatch(json["path"]?.string, .prefix("/"))
XCTAssertMatch(json["path"]?.string, .suffix("/" + fixturePath.basename))
XCTAssertEqual(json["targets"]?.array?.count, 3)
let jsonTarget0 = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget0["name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["c99name"]?.stringValue, "SeaLib")
XCTAssertEqual(jsonTarget0["type"]?.stringValue, "library")
XCTAssertEqual(jsonTarget0["module_type"]?.stringValue, "ClangTarget")
let jsonTarget1 = try XCTUnwrap(json["targets"]?.array?[1])
XCTAssertEqual(jsonTarget1["name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["c99name"]?.stringValue, "SeaExec")
XCTAssertEqual(jsonTarget1["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget1["module_type"]?.stringValue, "SwiftTarget")
XCTAssertEqual(jsonTarget1["product_memberships"]?.array?[0].stringValue, "SeaExec")
let jsonTarget2 = try XCTUnwrap(json["targets"]?.array?[2])
XCTAssertEqual(jsonTarget2["name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["c99name"]?.stringValue, "CExec")
XCTAssertEqual(jsonTarget2["type"]?.stringValue, "executable")
XCTAssertEqual(jsonTarget2["module_type"]?.stringValue, "ClangTarget")
XCTAssertEqual(jsonTarget2["product_memberships"]?.array?[0].stringValue, "CExec")
// Generate the text description.
let (textOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=text"], packagePath: fixturePath)
let textChunks = textOutput.components(separatedBy: "\n").reduce(into: [""]) { chunks, line in
// Split the text into chunks based on presence or absence of leading whitespace.
if line.hasPrefix(" ") == chunks[chunks.count-1].hasPrefix(" ") {
chunks[chunks.count-1].append(line + "\n")
}
else {
chunks.append(line + "\n")
}
}.filter{ !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
// Check that the text description contains what we expect it to.
// FIXME: This is a bit inelegant, but any errors are easy to reason about.
let textChunk0 = try XCTUnwrap(textChunks[0])
XCTAssertMatch(textChunk0, .contains("Name: SwiftCMixed"))
XCTAssertMatch(textChunk0, .contains("Path: /"))
XCTAssertMatch(textChunk0, .contains("/" + fixturePath.basename + "\n"))
XCTAssertMatch(textChunk0, .contains("Tools version: 4.2"))
XCTAssertMatch(textChunk0, .contains("Products:"))
let textChunk1 = try XCTUnwrap(textChunks[1])
XCTAssertMatch(textChunk1, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk1, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk1, .contains("Targets:\n SeaExec"))
let textChunk2 = try XCTUnwrap(textChunks[2])
XCTAssertMatch(textChunk2, .contains("Name: CExec"))
XCTAssertMatch(textChunk2, .contains("Type:\n Executable"))
XCTAssertMatch(textChunk2, .contains("Targets:\n CExec"))
let textChunk3 = try XCTUnwrap(textChunks[3])
XCTAssertMatch(textChunk3, .contains("Targets:"))
let textChunk4 = try XCTUnwrap(textChunks[4])
XCTAssertMatch(textChunk4, .contains("Name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("C99name: SeaLib"))
XCTAssertMatch(textChunk4, .contains("Type: library"))
XCTAssertMatch(textChunk4, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk4, .contains("Path: Sources/SeaLib"))
XCTAssertMatch(textChunk4, .contains("Sources:\n Foo.c"))
let textChunk5 = try XCTUnwrap(textChunks[5])
XCTAssertMatch(textChunk5, .contains("Name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("C99name: SeaExec"))
XCTAssertMatch(textChunk5, .contains("Type: executable"))
XCTAssertMatch(textChunk5, .contains("Module type: SwiftTarget"))
XCTAssertMatch(textChunk5, .contains("Path: Sources/SeaExec"))
XCTAssertMatch(textChunk5, .contains("Sources:\n main.swift"))
let textChunk6 = try XCTUnwrap(textChunks[6])
XCTAssertMatch(textChunk6, .contains("Name: CExec"))
XCTAssertMatch(textChunk6, .contains("C99name: CExec"))
XCTAssertMatch(textChunk6, .contains("Type: executable"))
XCTAssertMatch(textChunk6, .contains("Module type: ClangTarget"))
XCTAssertMatch(textChunk6, .contains("Path: Sources/CExec"))
XCTAssertMatch(textChunk6, .contains("Sources:\n main.c"))
}
try await fixture(name: "DependencyResolution/External/Simple/Bar") { fixturePath in
// Generate the JSON description.
let (jsonOutput, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
// Check that product dependencies and memberships are as expected.
XCTAssertEqual(json["name"]?.string, "Bar")
let jsonTarget = try XCTUnwrap(json["targets"]?.array?[0])
XCTAssertEqual(jsonTarget["product_memberships"]?.array?[0].stringValue, "Bar")
XCTAssertEqual(jsonTarget["product_dependencies"]?.array?[0].stringValue, "Foo")
XCTAssertNil(jsonTarget["target_dependencies"])
}
}
func testDescribePackageUsingPlugins() async throws {
try await fixture(name: "Miscellaneous/Plugins/MySourceGenPlugin") { fixturePath in
// Generate the JSON description.
let (stdout, _) = try await SwiftPM.Package.execute(["describe", "--type=json"], packagePath: fixturePath)
let json = try JSON(bytes: ByteString(encodingAsUTF8: stdout))
// Check the contents of the JSON.
XCTAssertEqual(try XCTUnwrap(json["name"]).string, "MySourceGenPlugin")
let targetsArray = try XCTUnwrap(json["targets"]?.array)
let buildToolPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenBuildToolPlugin" }?.dictionary)
XCTAssertEqual(buildToolPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(buildToolPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
let prebuildPluginTarget = try XCTUnwrap(targetsArray.first{ $0["name"]?.string == "MySourceGenPrebuildPlugin" }?.dictionary)
XCTAssertEqual(prebuildPluginTarget["module_type"]?.string, "PluginTarget")
XCTAssertEqual(prebuildPluginTarget["plugin_capability"]?.dictionary?["type"]?.string, "buildTool")
}
}
func testDumpPackage() async throws {
try await fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending("app")
let (dumpOutput, _) = try await execute(["dump-package"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: dumpOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
guard case let .array(platforms)? = contents["platforms"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
XCTAssertEqual(platforms, [
.dictionary([
"platformName": .string("macos"),
"version": .string("10.12"),
"options": .array([])
]),
.dictionary([
"platformName": .string("ios"),
"version": .string("10.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("tvos"),
"version": .string("11.0"),
"options": .array([])
]),
.dictionary([
"platformName": .string("watchos"),
"version": .string("5.0"),
"options": .array([])
]),
])
}
}
// Returns symbol graph with or without pretty printing.
private func symbolGraph(atPath path: AbsolutePath, withPrettyPrinting: Bool, file: StaticString = #file, line: UInt = #line) async throws -> Data? {
let tool = try SwiftCommandState.makeMockState(options: GlobalOptions.parse(["--package-path", path.pathString]))
let symbolGraphExtractorPath = try tool.getTargetToolchain().getSymbolGraphExtract()
let arguments = withPrettyPrinting ? ["dump-symbol-graph", "--pretty-print"] : ["dump-symbol-graph"]
let result = try await SwiftPM.Package.execute(arguments, packagePath: path, env: ["SWIFT_SYMBOLGRAPH_EXTRACT": symbolGraphExtractorPath.pathString])
let enumerator = try XCTUnwrap(FileManager.default.enumerator(at: URL(fileURLWithPath: path.pathString), includingPropertiesForKeys: nil), file: file, line: line)
var symbolGraphURL: URL?
for case let url as URL in enumerator where url.lastPathComponent == "Bar.symbols.json" {
symbolGraphURL = url
break
}
let symbolGraphData: Data
if let symbolGraphURL {
symbolGraphData = try Data(contentsOf: symbolGraphURL)
} else {
XCTFail("Failed to extract symbol graph: \(result.stdout)\n\(result.stderr)")
return nil
}
// Double check that it's a valid JSON
XCTAssertNoThrow(try JSONSerialization.jsonObject(with: symbolGraphData), file: file, line: line)
return symbolGraphData
}
func testDumpSymbolGraphCompactFormatting() async throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try await fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let compactGraphData = try await XCTAsyncUnwrap(await symbolGraph(atPath: fixturePath, withPrettyPrinting: false))
let compactJSONText = String(decoding: compactGraphData, as: UTF8.self)
XCTAssertEqual(compactJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testDumpSymbolGraphPrettyFormatting() async throws {
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try await fixture(name: "DependencyResolution/Internal/Simple") { fixturePath in
let prettyGraphData = try await XCTAsyncUnwrap(await symbolGraph(atPath: fixturePath, withPrettyPrinting: true))
let prettyJSONText = String(decoding: prettyGraphData, as: UTF8.self)
XCTAssertGreaterThan(prettyJSONText.components(separatedBy: .newlines).count, 1)
}
}
func testShowDependencies() async throws {
try await fixture(name: "DependencyResolution/External/Complex") { fixturePath in
let packageRoot = fixturePath.appending("app")
let (textOutput, _) = try await SwiftPM.Package.execute(["show-dependencies", "--format=text"], packagePath: packageRoot)
XCTAssert(textOutput.contains("FisherYates@1.2.3"))
let (jsonOutput, _) = try await SwiftPM.Package.execute(["show-dependencies", "--format=json"], packagePath: packageRoot)
let json = try JSON(bytes: ByteString(encodingAsUTF8: jsonOutput))
guard case let .dictionary(contents) = json else { XCTFail("unexpected result"); return }
guard case let .string(name)? = contents["name"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(name, "Dealer")
guard case let .string(path)? = contents["path"] else { XCTFail("unexpected result"); return }
XCTAssertEqual(try resolveSymlinks(try AbsolutePath(validating: path)), try resolveSymlinks(packageRoot))
}
}
func testShowDependencies_dotFormat_sr12016() throws {
// Confirm that SR-12016 is resolved.
// See https://bugs.swift.org/browse/SR-12016
let fileSystem = InMemoryFileSystem(emptyFiles: [
"/PackageA/Sources/TargetA/main.swift",
"/PackageB/Sources/TargetB/B.swift",
"/PackageC/Sources/TargetC/C.swift",
"/PackageD/Sources/TargetD/D.swift",
])
let manifestA = Manifest.createRootManifest(
displayName: "PackageA",
path: "/PackageA",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageB"),
.fileSystem(path: "/PackageC"),
],
products: [
try .init(name: "exe", type: .executable, targets: ["TargetA"])
],
targets: [
try .init(name: "TargetA", dependencies: ["PackageB", "PackageC"])
]
)
let manifestB = Manifest.createFileSystemManifest(
displayName: "PackageB",
path: "/PackageB",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageC"),
.fileSystem(path: "/PackageD"),
],
products: [
try .init(name: "PackageB", type: .library(.dynamic), targets: ["TargetB"])
],
targets: [
try .init(name: "TargetB", dependencies: ["PackageC", "PackageD"])
]
)
let manifestC = Manifest.createFileSystemManifest(
displayName: "PackageC",
path: "/PackageC",
toolsVersion: .v5_3,
dependencies: [
.fileSystem(path: "/PackageD"),
],
products: [
try .init(name: "PackageC", type: .library(.dynamic), targets: ["TargetC"])
],
targets: [
try .init(name: "TargetC", dependencies: ["PackageD"])
]
)
let manifestD = Manifest.createFileSystemManifest(
displayName: "PackageD",
path: "/PackageD",
toolsVersion: .v5_3,
products: [
try .init(name: "PackageD", type: .library(.dynamic), targets: ["TargetD"])
],
targets: [
try .init(name: "TargetD")
]
)
let observability = ObservabilitySystem.makeForTesting()
let graph = try loadModulesGraph(
fileSystem: fileSystem,
manifests: [manifestA, manifestB, manifestC, manifestD],
observabilityScope: observability.topScope
)
XCTAssertNoDiagnostics(observability.diagnostics)
let output = BufferedOutputByteStream()
SwiftPackageCommand.ShowDependencies.dumpDependenciesOf(
graph: graph,
rootPackage: graph.rootPackages[graph.rootPackages.startIndex],
mode: .dot,
on: output
)
let dotFormat = output.bytes.description
var alreadyPutOut: Set<Substring> = []
for line in dotFormat.split(whereSeparator: { $0.isNewline }) {
if alreadyPutOut.contains(line) {
XCTFail("Same line was already put out: \(line)")
}
alreadyPutOut.insert(line)
}
let expectedLines: [Substring] = [
#""/PackageA" [label="packagea\n/PackageA\nunspecified"]"#,
#""/PackageB" [label="packageb\n/PackageB\nunspecified"]"#,
#""/PackageC" [label="packagec\n/PackageC\nunspecified"]"#,
#""/PackageD" [label="packaged\n/PackageD\nunspecified"]"#,
#""/PackageA" -> "/PackageB""#,
#""/PackageA" -> "/PackageC""#,
#""/PackageB" -> "/PackageC""#,
#""/PackageB" -> "/PackageD""#,
#""/PackageC" -> "/PackageD""#,
]
for expectedLine in expectedLines {
XCTAssertTrue(alreadyPutOut.contains(expectedLine),
"Expected line is not found: \(expectedLine)")
}
}
func testShowDependencies_redirectJsonOutput() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let root = tmpPath.appending(components: "root")
let dep = tmpPath.appending(components: "dep")
// Create root package.
let mainFilePath = root.appending(components: "Sources", "root", "main.swift")
try fs.writeFileContents(mainFilePath, string: "")
try fs.writeFileContents(root.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "root",
dependencies: [.package(url: "../dep", from: "1.0.0")],
targets: [.target(name: "root", dependencies: ["dep"])]
)
"""
)
// Create dependency.
try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift"), string: "")
try fs.writeFileContents(dep.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "dep",
products: [.library(name: "dep", targets: ["dep"])],
targets: [.target(name: "dep")]
)
"""
)
do {
let depGit = GitRepository(path: dep)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
}
let resultPath = root.appending("result.json")
_ = try await execute(["show-dependencies", "--format", "json", "--output-path", resultPath.pathString ], packagePath: root)
XCTAssertFileExists(resultPath)
let jsonOutput: Data = try fs.readFileContents(resultPath)
let json = try JSON(data: jsonOutput)
XCTAssertEqual(json["name"]?.string, "root")
XCTAssertEqual(json["dependencies"]?[0]?["name"]?.string, "dep")
}
}
func testInitEmpty() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--type", "empty"], packagePath: path)
XCTAssertFileExists(path.appending("Package.swift"))
}
}
func testInitExecutable() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--type", "executable"], packagePath: path)
let manifest = path.appending("Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources")), ["main.swift"])
}
}
func testInitLibrary() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init"], packagePath: path)
XCTAssertFileExists(path.appending("Package.swift"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources").appending("Foo")), ["Foo.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Tests")).sorted(), ["FooTests"])
}
}
func testInitCustomNameExecutable() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("Foo")
try fs.createDirectory(path)
_ = try await execute(["init", "--name", "CustomName", "--type", "executable"], packagePath: path)
let manifest = path.appending("Package.swift")
let contents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(contents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertFileExists(manifest)
XCTAssertEqual(try fs.getDirectoryContents(path.appending("Sources")), ["main.swift"])
}
}
func testPackageAddDependency() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client",
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
)
_ = try await execute(["add-dependency", "--branch", "main", "https://github.com/swiftlang/swift-syntax.git"], packagePath: path)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#".package(url: "https://github.com/swiftlang/swift-syntax.git", branch: "main"),"#))
}
}
func testPackageAddTarget() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client"
)
"""
)
_ = try await execute(["add-target", "client", "--dependencies", "MyLib", "OtherLib", "--type", "executable"], packagePath: path)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#"targets:"#))
XCTAssertMatch(contents, .contains(#".executableTarget"#))
XCTAssertMatch(contents, .contains(#"name: "client""#))
XCTAssertMatch(contents, .contains(#"dependencies:"#))
XCTAssertMatch(contents, .contains(#""MyLib""#))
XCTAssertMatch(contents, .contains(#""OtherLib""#))
}
}
func testPackageAddTargetDependency() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client",
targets: [ .target(name: "library") ]
)
"""
)
try localFileSystem.writeFileContents(path.appending(components: "Sources", "library", "library.swift"), string:
"""
public func Foo() { }
"""
)
_ = try await execute(["add-target-dependency", "--package", "other-package", "other-product", "library"], packagePath: path)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#".product(name: "other-product", package: "other-package"#))
}
}
func testPackageAddProduct() async throws {
try await testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending("PackageB")
try fs.createDirectory(path)
try fs.writeFileContents(path.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "client"
)
"""
)
_ = try await execute(["add-product", "MyLib", "--targets", "MyLib", "--type", "static-library"], packagePath: path)
let manifest = path.appending("Package.swift")
XCTAssertFileExists(manifest)
let contents: String = try fs.readFileContents(manifest)
XCTAssertMatch(contents, .contains(#"products:"#))
XCTAssertMatch(contents, .contains(#".library"#))
XCTAssertMatch(contents, .contains(#"name: "MyLib""#))
XCTAssertMatch(contents, .contains(#"type: .static"#))
XCTAssertMatch(contents, .contains(#"targets:"#))
XCTAssertMatch(contents, .contains(#""MyLib""#))
}
}
func testPackageEditAndUnedit() async throws {
try await fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending("foo")
func build() async throws -> (stdout: String, stderr: String) {
return try await SwiftPM.Build.execute(packagePath: fooPath)
}
// Put bar and baz in edit mode.
_ = try await SwiftPM.Package.execute(["edit", "bar", "--branch", "bugfix"], packagePath: fooPath)
_ = try await SwiftPM.Package.execute(["edit", "baz", "--branch", "bugfix"], packagePath: fooPath)
// Path to the executable.
let exec = [fooPath.appending(components: ".build", try UserToolchain.default.targetTriple.platformBuildPathComponent, "debug", "foo").pathString]
// We should see it now in packages directory.
let editsPath = fooPath.appending(components: "Packages", "bar")
XCTAssertDirectoryExists(editsPath)
let bazEditsPath = fooPath.appending(components: "Packages", "baz")
XCTAssertDirectoryExists(bazEditsPath)
// Removing baz externally should just emit an warning and not a build failure.
try localFileSystem.removeFileTree(bazEditsPath)
// Do a modification in bar and build.
try localFileSystem.writeFileContents(editsPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 88888\n")
let (_, stderr) = try await build()
XCTAssertMatch(stderr, .contains("dependency 'baz' was being edited but is missing; falling back to original checkout"))
// We should be able to see that modification now.
try await XCTAssertAsyncEqual(try await AsyncProcess.checkNonZeroExit(arguments: exec), "88888\n")
// The branch of edited package should be the one we provided when putting it in edit mode.
let editsRepo = GitRepository(path: editsPath)
XCTAssertEqual(try editsRepo.currentBranch(), "bugfix")
// It shouldn't be possible to unedit right now because of uncommitted changes.
do {
_ = try await SwiftPM.Package.execute(["unedit", "bar"], packagePath: fooPath)
XCTFail("Unexpected unedit success")
} catch {}
try editsRepo.stageEverything()
try editsRepo.commit()
// It shouldn't be possible to unedit right now because of unpushed changes.
do {
_ = try await SwiftPM.Package.execute(["unedit", "bar"], packagePath: fooPath)
XCTFail("Unexpected unedit success")
} catch {}
// Push the changes.
try editsRepo.push(remote: "origin", branch: "bugfix")
// We should be able to unedit now.
_ = try await SwiftPM.Package.execute(["unedit", "bar"], packagePath: fooPath)
// Test editing with a path i.e. ToT development.
let bazTot = fixturePath.appending("tot")
try await SwiftPM.Package.execute(["edit", "baz", "--path", bazTot.pathString], packagePath: fooPath)
XCTAssertTrue(localFileSystem.exists(bazTot))
XCTAssertTrue(localFileSystem.isSymlink(bazEditsPath))
// Edit a file in baz ToT checkout.
let bazTotPackageFile = bazTot.appending("Package.swift")
var content: String = try localFileSystem.readFileContents(bazTotPackageFile)
content += "\n// Edited."
try localFileSystem.writeFileContents(bazTotPackageFile, string: content)
// Unediting baz will remove the symlink but not the checked out package.
try await SwiftPM.Package.execute(["unedit", "baz"], packagePath: fooPath)
XCTAssertTrue(localFileSystem.exists(bazTot))
XCTAssertFalse(localFileSystem.isSymlink(bazEditsPath))
// Check that on re-editing with path, we don't make a new clone.
try await SwiftPM.Package.execute(["edit", "baz", "--path", bazTot.pathString], packagePath: fooPath)
XCTAssertTrue(localFileSystem.isSymlink(bazEditsPath))
XCTAssertEqual(try localFileSystem.readFileContents(bazTotPackageFile), content)
}
}
func testPackageClean() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Build it.
await XCTAssertBuilds(packageRoot)
let buildPath = packageRoot.appending(".build")
let binFile = buildPath.appending(components: try UserToolchain.default.targetTriple.platformBuildPathComponent, "debug", "Bar")
XCTAssertFileExists(binFile)
XCTAssert(localFileSystem.isDirectory(buildPath))
// Clean, and check for removal of the build directory but not Packages.
_ = try await execute(["clean"], packagePath: packageRoot)
XCTAssertNoSuchPath(binFile)
// Clean again to ensure we get no error.
_ = try await execute(["clean"], packagePath: packageRoot)
}
}
func testPackageReset() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Build it.
await XCTAssertBuilds(packageRoot)
let buildPath = packageRoot.appending(".build")
let binFile = buildPath.appending(components: try UserToolchain.default.targetTriple.platformBuildPathComponent, "debug", "Bar")
XCTAssertFileExists(binFile)
XCTAssert(localFileSystem.isDirectory(buildPath))
// Clean, and check for removal of the build directory but not Packages.
_ = try await execute(["clean"], packagePath: packageRoot)
XCTAssertNoSuchPath(binFile)
XCTAssertFalse(try localFileSystem.getDirectoryContents(buildPath.appending("repositories")).isEmpty)
// Fully clean.
_ = try await execute(["reset"], packagePath: packageRoot)
XCTAssertFalse(localFileSystem.isDirectory(buildPath))
// Test that we can successfully run reset again.
_ = try await execute(["reset"], packagePath: packageRoot)
}
}
func testPinningBranchAndRevision() async throws {
try await fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending("foo")
@discardableResult
func execute(_ args: String..., printError: Bool = true) async throws -> String {
return try await SwiftPM.Package.execute([] + args, packagePath: fooPath).stdout
}
try await execute("update")
let pinsFile = fooPath.appending("Package.resolved")
XCTAssertFileExists(pinsFile)
// Update bar repo.
let barPath = fixturePath.appending("bar")
let barRepo = GitRepository(path: barPath)
try barRepo.checkout(newBranch: "YOLO")
let yoloRevision = try barRepo.getCurrentRevision()
// Try to pin bar at a branch.
do {
try await execute("resolve", "bar", "--branch", "YOLO")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let state = PinsStore.PinState.branch(name: "YOLO", revision: yoloRevision.identifier)
let identity = PackageIdentity(path: barPath)
XCTAssertEqual(pinsStore.pins[identity]?.state, state)
}
// Try to pin bar at a revision.
do {
try await execute("resolve", "bar", "--revision", yoloRevision.identifier)
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let state = PinsStore.PinState.revision(yoloRevision.identifier)
let identity = PackageIdentity(path: barPath)
XCTAssertEqual(pinsStore.pins[identity]?.state, state)
}
// Try to pin bar at a bad revision.
do {
try await execute("resolve", "bar", "--revision", "xxxxx")
XCTFail()
} catch {}
}
}
func testPinning() async throws {
try await fixture(name: "Miscellaneous/PackageEdit") { fixturePath in
let fooPath = fixturePath.appending("foo")
let exec = [fooPath.appending(components: ".build", try UserToolchain.default.targetTriple.platformBuildPathComponent, "debug", "foo").pathString]
// Build and check.
_ = try await SwiftPM.Build.execute(packagePath: fooPath)
try await XCTAssertAsyncEqual(try await AsyncProcess.checkNonZeroExit(arguments: exec).spm_chomp(), "\(5)")
// Get path to bar checkout.
let barPath = try SwiftPM.packagePath(for: "bar", packageRoot: fooPath)
// Checks the content of checked out bar.swift.
func checkBar(_ value: Int, file: StaticString = #file, line: UInt = #line) throws {
let contents: String = try localFileSystem.readFileContents(barPath.appending(components:"Sources", "bar.swift"))
XCTAssertTrue(contents.spm_chomp().hasSuffix("\(value)"), "got \(contents)", file: file, line: line)
}
// We should see a pin file now.
let pinsFile = fooPath.appending("Package.resolved")
XCTAssertFileExists(pinsFile)
// Test pins file.
do {
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
XCTAssertEqual(pinsStore.pins.count, 2)
for pkg in ["bar", "baz"] {
let path = try SwiftPM.packagePath(for: pkg, packageRoot: fooPath)
let pin = pinsStore.pins[PackageIdentity(path: path)]!
XCTAssertEqual(pin.packageRef.identity, PackageIdentity(path: path))
guard case .localSourceControl(let path) = pin.packageRef.kind, path.pathString.hasSuffix(pkg) else {
return XCTFail("invalid pin location \(path)")
}
switch pin.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
}
}
@discardableResult
func execute(_ args: String...) async throws -> String {
return try await SwiftPM.Package.execute([] + args, packagePath: fooPath).stdout
}
// Try to pin bar.
do {
try await execute("resolve", "bar")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let identity = PackageIdentity(path: barPath)
switch pinsStore.pins[identity]?.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
}
// Update bar repo.
do {
let barPath = fixturePath.appending("bar")
let barRepo = GitRepository(path: barPath)
try localFileSystem.writeFileContents(barPath.appending(components: "Sources", "bar.swift"), bytes: "public let theValue = 6\n")
try barRepo.stageEverything()
try barRepo.commit()
try barRepo.tag(name: "1.2.4")
}
// Running package update with --repin should update the package.
do {
try await execute("update")
try checkBar(6)
}
// We should be able to revert to a older version.
do {
try await execute("resolve", "bar", "--version", "1.2.3")
let pinsStore = try PinsStore(pinsFile: pinsFile, workingDirectory: fixturePath, fileSystem: localFileSystem, mirrors: .init())
let identity = PackageIdentity(path: barPath)
switch pinsStore.pins[identity]?.state {
case .version(let version, revision: _):
XCTAssertEqual(version, "1.2.3")
default:
XCTFail("invalid pin state")
}
try checkBar(5)
}
// Try pinning a dependency which is in edit mode.
do {
try await execute("edit", "bar", "--branch", "bugfix")
await XCTAssertThrowsCommandExecutionError(try await execute("resolve", "bar")) { error in
XCTAssertMatch(error.stderr, .contains("error: edited dependency 'bar' can't be resolved"))
}
try await execute("unedit", "bar")
}
}
}
func testOnlyUseVersionsFromResolvedFileFetchesWithExistingState() async throws {
func writeResolvedFile(packageDir: AbsolutePath, repositoryURL: String, revision: String, version: String) throws {
try localFileSystem.writeFileContents(packageDir.appending("Package.resolved"), string:
"""
{
"object": {
"pins": [
{
"package": "library",
"repositoryURL": "\(repositoryURL)",
"state": {
"branch": null,
"revision": "\(revision)",
"version": "\(version)"
}
}
]
},
"version": 1
}
"""
)
}
try await testWithTemporaryDirectory { tmpPath in
let packageDir = tmpPath.appending(components: "library")
try localFileSystem.writeFileContents(packageDir.appending("Package.swift"), string:
"""
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "library",
products: [ .library(name: "library", targets: ["library"]) ],
targets: [ .target(name: "library") ]
)
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "library", "library.swift"), string:
"""
public func Foo() { }
"""
)
let depGit = GitRepository(path: packageDir)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
let initialRevision = try depGit.revision(forTag: "1.0.0")
let repositoryURL = "file://\(packageDir.pathString)"
let clientDir = tmpPath.appending(components: "client")
try localFileSystem.writeFileContents(clientDir.appending("Package.swift"), string:
"""
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "client",
dependencies: [ .package(url: "\(repositoryURL)", from: "1.0.0") ],
targets: [ .target(name: "client", dependencies: [ "library" ]) ]
)
"""
)
try localFileSystem.writeFileContents(clientDir.appending(components: "Sources", "client", "main.swift"), string:
"""
print("hello")
"""
)
// Initial resolution with clean state.
do {
try writeResolvedFile(packageDir: clientDir, repositoryURL: repositoryURL, revision: initialRevision, version: "1.0.0")
let (_, err) = try await execute(["resolve", "--only-use-versions-from-resolved-file"], packagePath: clientDir)
XCTAssertMatch(err, .contains("Fetching \(repositoryURL)"))
}
// Make a change to the dependency and tag a new version.
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "library", "library.swift"), string:
"""
public func Best() { }
"""
)
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.1")
let updatedRevision = try depGit.revision(forTag: "1.0.1")
// Require new version but re-use existing state that hasn't fetched the latest revision, yet.
do {
try writeResolvedFile(packageDir: clientDir, repositoryURL: repositoryURL, revision: updatedRevision, version: "1.0.1")
let (_, err) = try await execute(["resolve", "--only-use-versions-from-resolved-file"], packagePath: clientDir)
XCTAssertNoMatch(err, .contains("Fetching \(repositoryURL)"))
XCTAssertMatch(err, .contains("Updating \(repositoryURL)"))
}
// And again
do {
let (_, err) = try await execute(["resolve", "--only-use-versions-from-resolved-file"], packagePath: clientDir)
XCTAssertNoMatch(err, .contains("Updating \(repositoryURL)"))
XCTAssertNoMatch(err, .contains("Fetching \(repositoryURL)"))
}
}
}
func testSymlinkedDependency() async throws {
try await testWithTemporaryDirectory { path in
let fs = localFileSystem
let root = path.appending(components: "root")
let dep = path.appending(components: "dep")
let depSym = path.appending(components: "depSym")
// Create root package.
try fs.writeFileContents(root.appending(components: "Sources", "root", "main.swift"), string: "")
try fs.writeFileContents(root.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "root",
dependencies: [.package(url: "../depSym", from: "1.0.0")],
targets: [.target(name: "root", dependencies: ["dep"])]
)
"""
)
// Create dependency.
try fs.writeFileContents(dep.appending(components: "Sources", "dep", "lib.swift"), string: "")
try fs.writeFileContents(dep.appending("Package.swift"), string:
"""
// swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "dep",
products: [.library(name: "dep", targets: ["dep"])],
targets: [.target(name: "dep")]
)
"""
)
do {
let depGit = GitRepository(path: dep)
try depGit.create()
try depGit.stageEverything()
try depGit.commit()
try depGit.tag(name: "1.0.0")
}
// Create symlink to the dependency.
try fs.createSymbolicLink(depSym, pointingAt: dep, relative: false)
_ = try await execute(["resolve"], packagePath: root)
}
}
func testMirrorConfigDeprecation() async throws {
try await testWithTemporaryDirectory { fixturePath in
localFileSystem.createEmptyFiles(at: fixturePath, files:
"/Sources/Foo/Foo.swift",
"/Package.swift"
)
let (_, stderr) = try await execute(["config", "set-mirror", "--package-url", "https://github.com/foo/bar", "--mirror-url", "https://mygithub.com/foo/bar"], packagePath: fixturePath)
XCTAssertMatch(stderr, .contains("warning: '--package-url' option is deprecated; use '--original' instead"))
XCTAssertMatch(stderr, .contains("warning: '--mirror-url' option is deprecated; use '--mirror' instead"))
}
}
func testMirrorConfig() async throws {
try await testWithTemporaryDirectory { fixturePath in
let fs = localFileSystem
let packageRoot = fixturePath.appending("Foo")
let configOverride = fixturePath.appending("configoverride")
let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: packageRoot)
fs.createEmptyFiles(at: packageRoot, files:
"/Sources/Foo/Foo.swift",
"/Tests/FooTests/FooTests.swift",
"/Package.swift",
"anchor"
)
// Test writing.
try await execute(["config", "set-mirror", "--original", "https://github.com/foo/bar", "--mirror", "https://mygithub.com/foo/bar"], packagePath: packageRoot)
try await execute(["config", "set-mirror", "--original", "git@github.com:swiftlang/swift-package-manager.git", "--mirror", "git@mygithub.com:foo/swift-package-manager.git"], packagePath: packageRoot)
XCTAssertTrue(fs.isFile(configFile))
// Test env override.
try await execute(["config", "set-mirror", "--original", "https://github.com/foo/bar", "--mirror", "https://mygithub.com/foo/bar"], packagePath: packageRoot, env: ["SWIFTPM_MIRROR_CONFIG": configOverride.pathString])
XCTAssertTrue(fs.isFile(configOverride))
let content: String = try fs.readFileContents(configOverride)
XCTAssertMatch(content, .contains("mygithub"))
// Test reading.
var (stdout, _) = try await execute(["config", "get-mirror", "--original", "https://github.com/foo/bar"], packagePath: packageRoot)
XCTAssertEqual(stdout.spm_chomp(), "https://mygithub.com/foo/bar")
(stdout, _) = try await execute(["config", "get-mirror", "--original", "git@github.com:swiftlang/swift-package-manager.git"], packagePath: packageRoot)
XCTAssertEqual(stdout.spm_chomp(), "git@mygithub.com:foo/swift-package-manager.git")
func check(stderr: String, _ block: () async throws -> ()) async {
await XCTAssertThrowsCommandExecutionError(try await block()) { error in
XCTAssertMatch(stderr, .contains(stderr))
}
}
await check(stderr: "not found\n") {
try await execute(["config", "get-mirror", "--original", "foo"], packagePath: packageRoot)
}
// Test deletion.
try await execute(["config", "unset-mirror", "--original", "https://github.com/foo/bar"], packagePath: packageRoot)
try await execute(["config", "unset-mirror", "--original", "git@mygithub.com:foo/swift-package-manager.git"], packagePath: packageRoot)
await check(stderr: "not found\n") {
try await execute(["config", "get-mirror", "--original", "https://github.com/foo/bar"], packagePath: packageRoot)
}
await check(stderr: "not found\n") {
try await execute(["config", "get-mirror", "--original", "git@github.com:swiftlang/swift-package-manager.git"], packagePath: packageRoot)
}
await check(stderr: "error: Mirror not found for 'foo'\n") {
try await execute(["config", "unset-mirror", "--original", "foo"], packagePath: packageRoot)
}
}
}
func testMirrorSimple() async throws {
try await testWithTemporaryDirectory { fixturePath in
let fs = localFileSystem
let packageRoot = fixturePath.appending("MyPackage")
let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: packageRoot)
fs.createEmptyFiles(
at: packageRoot,
files:
"/Sources/Foo/Foo.swift",
"/Tests/FooTests/FooTests.swift",
"/Package.swift"
)
try fs.writeFileContents(packageRoot.appending("Package.swift"), string:
"""
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(url: "https://scm.com/org/foo", from: "1.0.0")
],
targets: [
.executableTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "foo")
])
]
)
"""
)
try await execute(["config", "set-mirror", "--original", "https://scm.com/org/foo", "--mirror", "https://scm.com/org/bar"], packagePath: packageRoot)
XCTAssertTrue(fs.isFile(configFile))
let (stdout, _) = try await SwiftPM.Package.execute(["dump-package"], packagePath: packageRoot)
XCTAssertMatch(stdout, .contains("https://scm.com/org/bar"))
XCTAssertNoMatch(stdout, .contains("https://scm.com/org/foo"))
}
}
func testMirrorURLToRegistry() async throws {
try await testWithTemporaryDirectory { fixturePath in
let fs = localFileSystem
let packageRoot = fixturePath.appending("MyPackage")
let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: packageRoot)
fs.createEmptyFiles(
at: packageRoot,
files:
"/Sources/Foo/Foo.swift",
"/Tests/FooTests/FooTests.swift",
"/Package.swift"
)
try fs.writeFileContents(packageRoot.appending("Package.swift"), string:
"""
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(url: "https://scm.com/org/foo", from: "1.0.0")
],
targets: [
.executableTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "foo")
])
]
)
"""
)
try await execute(["config", "set-mirror", "--original", "https://scm.com/org/foo", "--mirror", "org.bar"], packagePath: packageRoot)
XCTAssertTrue(fs.isFile(configFile))
let (stdout, _) = try await SwiftPM.Package.execute(["dump-package"], packagePath: packageRoot)
XCTAssertMatch(stdout, .contains("org.bar"))
XCTAssertNoMatch(stdout, .contains("https://scm.com/org/foo"))
}
}
func testMirrorRegistryToURL() async throws {
try await testWithTemporaryDirectory { fixturePath in
let fs = localFileSystem
let packageRoot = fixturePath.appending("MyPackage")
let configFile = Workspace.DefaultLocations.mirrorsConfigurationFile(forRootPackage: packageRoot)
fs.createEmptyFiles(
at: packageRoot,
files:
"/Sources/Foo/Foo.swift",
"/Tests/FooTests/FooTests.swift",
"/Package.swift"
)
try fs.writeFileContents(packageRoot.appending("Package.swift"), string:
"""
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(id: "org.foo", from: "1.0.0")
],
targets: [
.executableTarget(
name: "MyTarget",
dependencies: [
.product(name: "Foo", package: "org.foo")
])
]
)
"""
)
try await execute(["config", "set-mirror", "--original", "org.foo", "--mirror", "https://scm.com/org/bar"], packagePath: packageRoot)
XCTAssertTrue(fs.isFile(configFile))
let (stdout, _) = try await SwiftPM.Package.execute(["dump-package"], packagePath: packageRoot)
XCTAssertMatch(stdout, .contains("https://scm.com/org/bar"))
XCTAssertNoMatch(stdout, .contains("org.foo"))
}
}
func testPackageLoadingCommandPathResilience() async throws {
#if !os(macOS)
try XCTSkipIf(true, "skipping on non-macOS")
#endif
try await fixture(name: "ValidLayouts/SingleModule") { fixturePath in
try await testWithTemporaryDirectory { tmpdir in
// Create fake `xcrun` and `sandbox-exec` commands.
let fakeBinDir = tmpdir
for fakeCmdName in ["xcrun", "sandbox-exec"] {
let fakeCmdPath = fakeBinDir.appending(component: fakeCmdName)
try localFileSystem.writeFileContents(fakeCmdPath, string:
"""
#!/bin/sh
echo "wrong \(fakeCmdName) invoked"
exit 1
"""
)
try localFileSystem.chmod(.executable, path: fakeCmdPath)
}
// Invoke `swift-package`, passing in the overriding `PATH` environment variable.
let packageRoot = fixturePath.appending("Library")
let patchedPATH = fakeBinDir.pathString + ":" + ProcessInfo.processInfo.environment["PATH"]!
let (stdout, _) = try await SwiftPM.Package.execute(["dump-package"], packagePath: packageRoot, env: ["PATH": patchedPATH])
// Check that the wrong tools weren't invoked. We can't just check the exit code because of fallbacks.
XCTAssertNoMatch(stdout, .contains("wrong xcrun invoked"))
XCTAssertNoMatch(stdout, .contains("wrong sandbox-exec invoked"))
}
}
}
func testBuildToolPlugin() async throws {
try await testBuildToolPlugin(staticStdlib: false)
}
func testBuildToolPluginWithStaticStdlib() async throws {
// Skip if the toolchain cannot compile a simple program with static stdlib.
do {
let args = try [
UserToolchain.default.swiftCompilerPath.pathString,
"-static-stdlib", "-emit-executable", "-o", "/dev/null", "-"
]
let process = AsyncProcess(arguments: args)
let stdin = try process.launch()
stdin.write(sequence: "".utf8)
try stdin.close()
let result = try await process.waitUntilExit()
try XCTSkipIf(
result.exitStatus != .terminated(code: 0),
"skipping because static stdlib is not supported by the toolchain"
)
}
try await testBuildToolPlugin(staticStdlib: true)
}
func testBuildToolPlugin(staticStdlib: Bool) async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending("Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary",
plugins: [
"MyPlugin",
]
),
.plugin(
name: "MyPlugin",
capability: .buildTool()
),
]
)
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift"), string:
"""
public func Foo() { }
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.foo"), string:
"""
a file with a filename suffix handled by the plugin
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.bar"), string:
"""
a file with a filename suffix not handled by the plugin
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift"), string:
"""
import PackagePlugin
import Foundation
@main
struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
// Expect the initial working directory for build tool plugins is the package directory.
guard FileManager.default.currentDirectoryPath == context.package.directory.string else {
throw "expected initial working directory ‘\\(FileManager.default.currentDirectoryPath)’"
}
// Check that the package display name is what we expect.
guard context.package.displayName == "MyPackage" else {
throw "expected display name to be ‘MyPackage’ but found ‘\\(context.package.displayName)’"
}
// Create and return a build command that uses all the `.foo` files in the target as inputs, so they get counted as having been handled.
let fooFiles = target.sourceModule?.sourceFiles.compactMap{ $0.path.extension == "foo" ? $0.path : nil } ?? []
return [ .buildCommand(displayName: "A command", executable: Path("/bin/echo"), arguments: fooFiles, inputFiles: fooFiles) ]
}
}
extension String : Error {}
"""
)
// Invoke it, and check the results.
let args = staticStdlib ? ["--static-swift-stdlib"] : []
let (stdout, stderr) = try await SwiftPM.Build.execute(args, packagePath: packageDir)
XCTAssert(stdout.contains("Build complete!"))
// We expect a warning about `library.bar` but not about `library.foo`.
XCTAssertMatch(stderr, .contains("found 1 file(s) which are unhandled"))
XCTAssertNoMatch(stderr, .contains("Sources/MyLibrary/library.foo"))
XCTAssertMatch(stderr, .contains("Sources/MyLibrary/library.bar"))
}
}
func testBuildToolPluginFailure() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending("Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary",
plugins: [
"MyPlugin",
]
),
.plugin(
name: "MyPlugin",
capability: .buildTool()
),
]
)
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending("library.swift"), string: """
public func Foo() { }
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
import Foundation
@main
struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
print("This is text from the plugin")
throw "This is an error from the plugin"
return []
}
}
extension String : Error {}
"""
)
// Invoke it, and check the results.
await XCTAssertAsyncThrowsError(try await SwiftPM.Build.execute(["-v"], packagePath: packageDir)) { error in
guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertMatch(stderr, .contains("This is text from the plugin"))
XCTAssertMatch(stderr, .contains("error: This is an error from the plugin"))
XCTAssertMatch(stderr, .contains("build stopped due to build-tool plugin failures"))
}
}
}
func testArchiveSource() async throws {
try await fixture(name: "DependencyResolution/External/Simple") { fixturePath in
let packageRoot = fixturePath.appending("Bar")
// Running without arguments or options
do {
let (stdout, _) = try await SwiftPM.Package.execute(["archive-source"], packagePath: packageRoot)
XCTAssert(stdout.contains("Created Bar.zip"), #"actual: "\#(stdout)""#)
}
// Running without arguments or options again, overwriting existing archive
do {
let (stdout, _) = try await SwiftPM.Package.execute(["archive-source"], packagePath: packageRoot)
XCTAssert(stdout.contains("Created Bar.zip"), #"actual: "\#(stdout)""#)
}
// Running with output as absolute path within package root
do {
let destination = packageRoot.appending("Bar-1.2.3.zip")
let (stdout, _) = try await SwiftPM.Package.execute(["archive-source", "--output", destination.pathString], packagePath: packageRoot)
XCTAssert(stdout.contains("Created Bar-1.2.3.zip"), #"actual: "\#(stdout)""#)
}
// Running with output is outside the package root
try await withTemporaryDirectory { tempDirectory in
let destination = tempDirectory.appending("Bar-1.2.3.zip")
let (stdout, _) = try await SwiftPM.Package.execute(["archive-source", "--output", destination.pathString], packagePath: packageRoot)
XCTAssert(stdout.hasPrefix("Created /"), #"actual: "\#(stdout)""#)
XCTAssert(stdout.contains("Bar-1.2.3.zip"), #"actual: "\#(stdout)""#)
}
// Running without arguments or options in non-package directory
do {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["archive-source"], packagePath: fixturePath)) { error in
guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssert(stderr.contains("error: Could not find Package.swift in this directory or any of its parent directories."), #"actual: "\#(stderr)""#)
}
}
// Running with output as absolute path to existing directory
do {
let destination = AbsolutePath.root
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["archive-source", "--output", destination.pathString], packagePath: packageRoot)) { error in
guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssert(
stderr.contains("error: Couldn’t create an archive:"),
#"actual: "\#(stderr)""#
)
}
}
}
}
func testCommandPlugin() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target, a plugin, and a local tool. It depends on a sample package which also has a tool.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage")
],
targets: [
.target(
name: "MyLibrary",
dependencies: [
.product(name: "HelperLibrary", package: "HelperPackage")
]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "mycmd", description: "What is mycmd anyway?")
),
dependencies: [
.target(name: "LocalBuiltTool"),
.target(name: "LocalBinaryTool"),
.product(name: "RemoteBuiltTool", package: "HelperPackage")
]
),
.binaryTarget(
name: "LocalBinaryTool",
path: "Binaries/LocalBinaryTool.artifactbundle"
),
.executableTarget(
name: "LocalBuiltTool"
)
]
)
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift"), string:
"""
public func Foo() { }
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "test.docc"), string:
"""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>sample</string>
</dict>
"""
)
let environment = Environment.current
let hostTriple = try UserToolchain(
swiftSDK: .hostSwiftSDK(environment: environment),
environment: environment
).targetTriple
let hostTripleString = if hostTriple.isDarwin() {
hostTriple.tripleString(forPlatformVersion: "")
} else {
hostTriple.tripleString
}
try localFileSystem.writeFileContents(
packageDir.appending(components: "Binaries", "LocalBinaryTool.artifactbundle", "info.json"),
string: """
{ "schemaVersion": "1.0",
"artifacts": {
"LocalBinaryTool": {
"type": "executable",
"version": "1.2.3",
"variants": [
{ "path": "LocalBinaryTool.sh",
"supportedTriples": ["\(hostTripleString)"]
},
]
}
}
}
"""
)
try localFileSystem.writeFileContents(
packageDir.appending(components: "Sources", "LocalBuiltTool", "main.swift"),
string: #"print("Hello")"#
)
try localFileSystem.writeFileContents(
packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift"),
string: """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
print("This is MyCommandPlugin.")
// Print out the initial working directory so we can check it in the test.
print("Initial working directory: \\(FileManager.default.currentDirectoryPath)")
// Check that we can find a binary-provided tool in the same package.
print("Looking for LocalBinaryTool...")
let localBinaryTool = try context.tool(named: "LocalBinaryTool")
print("... found it at \\(localBinaryTool.path)")
// Check that we can find a source-built tool in the same package.
print("Looking for LocalBuiltTool...")
let localBuiltTool = try context.tool(named: "LocalBuiltTool")
print("... found it at \\(localBuiltTool.path)")
// Check that we can find a source-built tool in another package.
print("Looking for RemoteBuiltTool...")
let remoteBuiltTool = try context.tool(named: "RemoteBuiltTool")
print("... found it at \\(remoteBuiltTool.path)")
// Check that we can find a tool in the toolchain.
print("Looking for swiftc...")
let swiftc = try context.tool(named: "swiftc")
print("... found it at \\(swiftc.path)")
// Check that we can find a standard tool.
print("Looking for sed...")
let sed = try context.tool(named: "sed")
print("... found it at \\(sed.path)")
// Extract the `--target` arguments.
var argExtractor = ArgumentExtractor(arguments)
let targetNames = argExtractor.extractOption(named: "target")
let targets = try context.package.targets(named: targetNames)
// Print out the source files so that we can check them.
if let sourceFiles = targets.first(where: { $0.name == "MyLibrary" })?.sourceModule?.sourceFiles {
for file in sourceFiles {
print(" \\(file.path): \\(file.type)")
}
}
// Print out the dependencies so that we can check them.
for dependency in context.package.dependencies {
print(" dependency \\(dependency.package.displayName): \\(dependency.package.origin)")
}
}
}
"""
)
// Create the sample vendored dependency package.
try localFileSystem.writeFileContents(
packageDir.appending(components: "VendoredDependencies", "HelperPackage", "Package.swift"),
string: """
// swift-tools-version: 5.5
import PackageDescription
let package = Package(
name: "HelperPackage",
products: [
.library(
name: "HelperLibrary",
targets: ["HelperLibrary"]
),
.executable(
name: "RemoteBuiltTool",
targets: ["RemoteBuiltTool"]
),
],
targets: [
.target(
name: "HelperLibrary"
),
.executableTarget(
name: "RemoteBuiltTool"
),
]
)
"""
)
try localFileSystem.writeFileContents(
packageDir.appending(
components: "VendoredDependencies",
"HelperPackage",
"Sources",
"HelperLibrary",
"library.swift"
),
string: "public func Bar() { }"
)
try localFileSystem.writeFileContents(
packageDir.appending(
components: "VendoredDependencies",
"HelperPackage",
"Sources",
"RemoteBuiltTool",
"main.swift"
),
string: #"print("Hello")"#
)
// Check that we can invoke the plugin with the "plugin" subcommand.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["plugin", "mycmd"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("This is MyCommandPlugin."))
}
// Check that we can also invoke it without the "plugin" subcommand.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["mycmd"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("This is MyCommandPlugin."))
}
// Testing listing the available command plugins.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["plugin", "--list"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("‘mycmd’ (plugin ‘MyPlugin’ in package ‘MyPackage’)"))
}
// Check that we get the expected error if trying to invoke a plugin with the wrong name.
do {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["my-nonexistent-cmd"], packagePath: packageDir)) { error in
guard case SwiftPMError.executionFailure(_, _, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertMatch(stderr, .contains("Unknown subcommand or plugin name ‘my-nonexistent-cmd’"))
}
}
// Check that the .docc file was properly vended to the plugin.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["mycmd", "--target", "MyLibrary"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Sources/MyLibrary/library.swift: source"))
XCTAssertMatch(stdout, .contains("Sources/MyLibrary/test.docc: unknown"))
}
// Check that the initial working directory is what we expected.
do {
let workingDirectory = FileManager.default.currentDirectoryPath
let (stdout, _) = try await SwiftPM.Package.execute(["mycmd"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Initial working directory: \(workingDirectory)"))
}
// Check that information about the dependencies was properly sent to the plugin.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["mycmd", "--target", "MyLibrary"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("dependency HelperPackage: local"))
}
}
}
func testAmbiguousCommandPlugin() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await fixture(name: "Miscellaneous/Plugins/AmbiguousCommands") { fixturePath in
let (stdout, _) = try await SwiftPM.Package.execute(["plugin", "--package", "A", "A"], packagePath: fixturePath)
XCTAssertMatch(stdout, .contains("Hello A!"))
}
}
// Test reporting of plugin diagnostic messages at different verbosity levels
func testCommandPluginDiagnostics() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Match patterns for expected messages
let isEmpty = StringPattern.equal("")
let isOnlyPrint = StringPattern.equal("command plugin: print\n")
let containsProgress = StringPattern.contains("[diagnostics-stub] command plugin: Diagnostics.progress")
let containsRemark = StringPattern.contains("command plugin: Diagnostics.remark")
let containsWarning = StringPattern.contains("command plugin: Diagnostics.warning")
let containsError = StringPattern.contains("command plugin: Diagnostics.error")
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
func runPlugin(flags: [String], diagnostics: [String], completion: (String, String) -> Void) async throws {
let (stdout, stderr) = try await SwiftPM.Package.execute(flags + ["print-diagnostics"] + diagnostics, packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
completion(stdout, stderr)
}
// Diagnostics.error causes SwiftPM to return a non-zero exit code, but we still need to check stdout and stderr
func runPluginWithError(flags: [String], diagnostics: [String], completion: (String, String) -> Void) async throws {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(flags + ["print-diagnostics"] + diagnostics, packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])) { error in
guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
completion(stdout, stderr)
}
}
// Default verbosity
// - stdout is always printed
// - Diagnostics below 'warning' are suppressed
try await runPlugin(flags: [], diagnostics: ["print"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, isEmpty)
}
try await runPlugin(flags: [], diagnostics: ["print", "progress"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPlugin(flags: [], diagnostics: ["print", "progress", "remark"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPlugin(flags: [], diagnostics: ["print", "progress", "remark", "warning"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertMatch(stderr, containsWarning)
}
try await runPluginWithError(flags: [], diagnostics: ["print", "progress", "remark", "warning", "error"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertMatch(stderr, containsWarning)
XCTAssertMatch(stderr, containsError)
}
// Quiet Mode
// - stdout is always printed
// - Diagnostics below 'error' are suppressed
try await runPlugin(flags: ["-q"], diagnostics: ["print"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, isEmpty)
}
try await runPlugin(flags: ["-q"], diagnostics: ["print", "progress"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPlugin(flags: ["-q"], diagnostics: ["print", "progress", "remark"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPlugin(flags: ["-q"], diagnostics: ["print", "progress", "remark", "warning"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPluginWithError(flags: ["-q"], diagnostics: ["print", "progress", "remark", "warning", "error"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertNoMatch(stderr, containsRemark)
XCTAssertNoMatch(stderr, containsWarning)
XCTAssertMatch(stderr, containsError)
}
// Verbose Mode
// - stdout is always printed
// - All diagnostics are printed
// - Substantial amounts of additional compiler output are also printed
try await runPlugin(flags: ["-v"], diagnostics: ["print"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
// At this level stderr contains extra compiler output even if the plugin does not print diagnostics
}
try await runPlugin(flags: ["-v"], diagnostics: ["print", "progress"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
}
try await runPlugin(flags: ["-v"], diagnostics: ["print", "progress", "remark"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertMatch(stderr, containsRemark)
}
try await runPlugin(flags: ["-v"], diagnostics: ["print", "progress", "remark", "warning"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertMatch(stderr, containsRemark)
XCTAssertMatch(stderr, containsWarning)
}
try await runPluginWithError(flags: ["-v"], diagnostics: ["print", "progress", "remark", "warning", "error"]) { stdout, stderr in
XCTAssertMatch(stdout, isOnlyPrint)
XCTAssertMatch(stderr, containsProgress)
XCTAssertMatch(stderr, containsRemark)
XCTAssertMatch(stderr, containsWarning)
XCTAssertMatch(stderr, containsError)
}
}
}
// Test target builds requested by a command plugin
func testCommandPluginTargetBuilds() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
let debugTarget = [".build", "debug", "placeholder"]
let releaseTarget = [".build", "release", "placeholder"]
func AssertIsExecutableFile(_ fixturePath: AbsolutePath, file: StaticString = #filePath, line: UInt = #line) {
XCTAssert(
localFileSystem.isExecutableFile(fixturePath),
"\(fixturePath) does not exist",
file: file,
line: line
)
}
func AssertNotExists(_ fixturePath: AbsolutePath, file: StaticString = #filePath, line: UInt = #line) {
XCTAssertFalse(
localFileSystem.exists(fixturePath),
"\(fixturePath) should not exist",
file: file,
line: line
)
}
// By default, a plugin-requested build produces a debug binary
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let _ = try await SwiftPM.Package.execute(["-c", "release", "build-target"], packagePath: fixturePath)
AssertIsExecutableFile(fixturePath.appending(components: debugTarget))
AssertNotExists(fixturePath.appending(components: releaseTarget))
}
// If the plugin specifies a debug binary, that is what will be built, regardless of overall configuration
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let _ = try await SwiftPM.Package.execute(["-c", "release", "build-target", "build-debug"], packagePath: fixturePath)
AssertIsExecutableFile(fixturePath.appending(components: debugTarget))
AssertNotExists(fixturePath.appending(components: releaseTarget))
}
// If the plugin requests a release binary, that is what will be built, regardless of overall configuration
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let _ = try await SwiftPM.Package.execute(["-c", "debug", "build-target", "build-release"], packagePath: fixturePath)
AssertNotExists(fixturePath.appending(components: debugTarget))
AssertIsExecutableFile(fixturePath.appending(components: releaseTarget))
}
// If the plugin inherits the overall build configuration, that is what will be built
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let _ = try await SwiftPM.Package.execute(["-c", "debug", "build-target", "build-inherit"], packagePath: fixturePath)
AssertIsExecutableFile(fixturePath.appending(components: debugTarget))
AssertNotExists(fixturePath.appending(components: releaseTarget))
}
// If the plugin inherits the overall build configuration, that is what will be built
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let _ = try await SwiftPM.Package.execute(["-c", "release", "build-target", "build-inherit"], packagePath: fixturePath)
AssertNotExists(fixturePath.appending(components: debugTarget))
AssertIsExecutableFile(fixturePath.appending(components: releaseTarget))
}
}
// Test logging of builds initiated by a command plugin
func testCommandPluginBuildLogs() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Match patterns for expected messages
let isEmpty = StringPattern.equal("")
// result.logText printed by the plugin has a prefix
let containsLogtext = StringPattern.contains("command plugin: packageManager.build logtext: Building for debugging...")
// Echoed logs have no prefix
let containsLogecho = StringPattern.regex("^Building for debugging...\n")
// These tests involve building a target, so each test must run with a fresh copy of the fixture
// otherwise the logs may be different in subsequent tests.
// Check than nothing is echoed when echoLogs is false
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let (stdout, stderr) = try await SwiftPM.Package.execute(["print-diagnostics", "build"], packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, isEmpty)
XCTAssertMatch(stderr, isEmpty)
}
// Check that logs are returned to the plugin when echoLogs is false
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let (stdout, stderr) = try await SwiftPM.Package.execute(["print-diagnostics", "build", "printlogs"], packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, containsLogtext)
XCTAssertMatch(stderr, isEmpty)
}
// Check that logs echoed to the console (on stderr) when echoLogs is true
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let (stdout, stderr) = try await SwiftPM.Package.execute(["print-diagnostics", "build", "echologs"], packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, isEmpty)
XCTAssertMatch(stderr, containsLogecho)
}
// Check that logs are returned to the plugin and echoed to the console (on stderr) when echoLogs is true
try await fixture(name: "Miscellaneous/Plugins/CommandPluginTestStub") { fixturePath in
let (stdout, stderr) = try await SwiftPM.Package.execute(["print-diagnostics", "build", "printlogs", "echologs"], packagePath: fixturePath, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, containsLogtext)
XCTAssertMatch(stderr, containsLogecho)
}
}
func testCommandPluginNetworkingPermissions(permissionsManifestFragment: String, permissionError: String, reason: String, remedy: [String]) async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string:
"""
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(name: "MyLibrary"),
.plugin(name: "MyPlugin", capability: .command(intent: .custom(verb: "Network", description: "Help description"), permissions: \(permissionsManifestFragment))),
]
)
"""
)
try localFileSystem.writeFileContents(packageDir.appending(components: "Sources", "MyLibrary", "library.swift"), string: "public func Foo() { }")
try localFileSystem.writeFileContents(packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift"), string:
"""
import PackagePlugin
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(context: PluginContext, arguments: [String]) throws {
print("hello world")
}
}
"""
)
#if os(macOS)
do {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["plugin", "Network"], packagePath: packageDir)) { error in
guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertNoMatch(stdout, .contains("hello world"))
XCTAssertMatch(stderr, .contains("error: Plugin ‘MyPlugin’ wants permission to allow \(permissionError)."))
XCTAssertMatch(stderr, .contains("Stated reason: “\(reason)”."))
XCTAssertMatch(stderr, .contains("Use `\(remedy.joined(separator: " "))` to allow this."))
}
}
#endif
// Check that we don't get an error (and also are allowed to write to the package directory) if we pass `--allow-writing-to-package-directory`.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["plugin"] + remedy + ["Network"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("hello world"))
}
}
}
func testCommandPluginNetworkingPermissions() async throws {
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .all(), reason: \"internet good\")]",
permissionError: "all network connections on all ports",
reason: "internet good",
remedy: ["--allow-network-connections", "all"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .all(ports: [23, 42, 443, 8080]), reason: \"internet good\")]",
permissionError: "all network connections on ports: 23, 42, 443, 8080",
reason: "internet good",
remedy: ["--allow-network-connections", "all:23,42,443,8080"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .all(ports: 1..<4), reason: \"internet good\")]",
permissionError: "all network connections on ports: 1, 2, 3",
reason: "internet good",
remedy: ["--allow-network-connections", "all:1,2,3"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .local(), reason: \"localhost good\")]",
permissionError: "local network connections on all ports",
reason: "localhost good",
remedy: ["--allow-network-connections", "local"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .local(ports: [23, 42, 443, 8080]), reason: \"localhost good\")]",
permissionError: "local network connections on ports: 23, 42, 443, 8080",
reason: "localhost good",
remedy: ["--allow-network-connections", "local:23,42,443,8080"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .local(ports: 1..<4), reason: \"localhost good\")]",
permissionError: "local network connections on ports: 1, 2, 3",
reason: "localhost good",
remedy: ["--allow-network-connections", "local:1,2,3"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .docker, reason: \"docker good\")]",
permissionError: "docker unix domain socket connections",
reason: "docker good",
remedy: ["--allow-network-connections", "docker"])
try await testCommandPluginNetworkingPermissions(
permissionsManifestFragment: "[.allowNetworkConnections(scope: .unixDomainSocket, reason: \"unix sockets good\")]",
permissionError: "unix domain socket connections",
reason: "unix sockets good",
remedy: ["--allow-network-connections", "unixDomainSocket"])
}
func testCommandPluginPermissions() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string:
"""
// swift-tools-version: 5.6
import PackageDescription
import Foundation
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "PackageScribbler", description: "Help description"),
// We use an environment here so we can control whether we declare the permission.
permissions: ProcessInfo.processInfo.environment["DECLARE_PACKAGE_WRITING_PERMISSION"] == "1"
? [.writeToPackageDirectory(reason: "For testing purposes")]
: []
)
),
]
)
"""
)
let libPath = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(libPath, recursive: true)
try localFileSystem.writeFileContents(libPath.appending("library.swift"), string:
"public func Foo() { }"
)
let pluginPath = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(pluginPath, recursive: true)
try localFileSystem.writeFileContents(pluginPath.appending("plugin.swift"), string:
"""
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Check that we can write to the package directory.
print("Trying to write to the package directory...")
guard FileManager.default.createFile(atPath: context.package.directory.appending("Foo").string, contents: Data("Hello".utf8)) else {
throw "Couldn’t create file at path \\(context.package.directory.appending("Foo"))"
}
print("... successfully created it")
}
}
extension String: Error {}
"""
)
// Check that we get an error if the plugin needs permission but if we don't give it to them. Note that sandboxing is only currently supported on macOS.
#if os(macOS)
do {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["plugin", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])) { error in
guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertNoMatch(stdout, .contains("successfully created it"))
XCTAssertMatch(stderr, .contains("error: Plugin ‘MyPlugin’ wants permission to write to the package directory."))
XCTAssertMatch(stderr, .contains("Stated reason: “For testing purposes”."))
XCTAssertMatch(stderr, .contains("Use `--allow-writing-to-package-directory` to allow this."))
}
}
#endif
// Check that we don't get an error (and also are allowed to write to the package directory) if we pass `--allow-writing-to-package-directory`.
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["plugin", "--allow-writing-to-package-directory", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertMatch(stdout, .contains("successfully created it"))
XCTAssertNoMatch(stderr, .contains("error: Couldn’t create file at path"))
}
// Check that we get an error if the plugin doesn't declare permission but tries to write anyway. Note that sandboxing is only currently supported on macOS.
#if os(macOS)
do {
await XCTAssertAsyncThrowsError(try await SwiftPM.Package.execute(["plugin", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "0"])) { error in
guard case SwiftPMError.executionFailure(_, let stdout, let stderr) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertNoMatch(stdout, .contains("successfully created it"))
XCTAssertMatch(stderr, .contains("error: Couldn’t create file at path"))
}
}
#endif
// Check default command with arguments
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["--allow-writing-to-package-directory", "PackageScribbler"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertMatch(stdout, .contains("successfully created it"))
XCTAssertNoMatch(stderr, .contains("error: Couldn’t create file at path"))
}
// Check plugin arguments after plugin name
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["plugin", "PackageScribbler", "--allow-writing-to-package-directory"], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertMatch(stdout, .contains("successfully created it"))
XCTAssertNoMatch(stderr, .contains("error: Couldn’t create file at path"))
}
// Check default command with arguments after plugin name
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["PackageScribbler", "--allow-writing-to-package-directory", ], packagePath: packageDir, env: ["DECLARE_PACKAGE_WRITING_PERMISSION": "1"])
XCTAssertMatch(stdout, .contains("successfully created it"))
XCTAssertNoMatch(stderr, .contains("error: Couldn’t create file at path"))
}
}
}
func testCommandPluginArgumentsNotSwallowed() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir)
try localFileSystem.writeFileContents(
packageDir.appending(components: "Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
import Foundation
let package = Package(
name: "MyPackage",
targets: [
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "MyPlugin", description: "Help description")
)
),
]
)
"""
)
let pluginDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(pluginDir, recursive: true)
try localFileSystem.writeFileContents(
pluginDir.appending("plugin.swift"),
string: """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
print (arguments)
guard arguments.contains("--foo") else {
throw "expecting argument foo"
}
guard arguments.contains("--help") else {
throw "expecting argument help"
}
guard arguments.contains("--version") else {
throw "expecting argument version"
}
guard arguments.contains("--verbose") else {
throw "expecting argument verbose"
}
print("success")
}
}
extension String: Error {}
"""
)
// Check arguments
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["plugin", "MyPlugin", "--foo", "--help", "--version", "--verbose"], packagePath: packageDir, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, .contains("success"))
XCTAssertEqual(stderr, "")
}
// Check default command arguments
do {
let (stdout, stderr) = try await SwiftPM.Package.execute(["MyPlugin", "--foo", "--help", "--version", "--verbose"], packagePath: packageDir, env: ["SWIFT_DRIVER_SWIFTSCAN_LIB" : "/this/is/a/bad/path"])
XCTAssertMatch(stdout, .contains("success"))
XCTAssertEqual(stderr, "")
}
}
}
func testCommandPluginSymbolGraphCallbacks() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Depending on how the test is running, the `swift-symbolgraph-extract` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getSymbolGraphExtract()) == nil, "skipping test because the `swift-symbolgraph-extract` tools isn't available")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, and executable, and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir)
try localFileSystem.writeFileContents(
packageDir.appending(components: "Package.swift"),
string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyCommand",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .documentationGeneration()
)
),
]
)
"""
)
let libraryPath = packageDir.appending(components: "Sources", "MyLibrary", "library.swift")
try localFileSystem.createDirectory(libraryPath.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
libraryPath,
string: #"public func GetGreeting() -> String { return "Hello" }"#
)
let commandPath = packageDir.appending(components: "Sources", "MyCommand", "main.swift")
try localFileSystem.createDirectory(commandPath.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
commandPath,
string: """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
)
let pluginPath = packageDir.appending(components: "Plugins", "MyPlugin", "plugin.swift")
try localFileSystem.createDirectory(pluginPath.parentDirectory, recursive: true)
try localFileSystem.writeFileContents(
pluginPath,
string: """
import PackagePlugin
import Foundation
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Ask for and print out the symbol graph directory for each target.
var argExtractor = ArgumentExtractor(arguments)
let targetNames = argExtractor.extractOption(named: "target")
let targets = targetNames.isEmpty
? context.package.targets
: try context.package.targets(named: targetNames)
for target in targets {
let symbolGraph = try packageManager.getSymbolGraph(for: target,
options: .init(minimumAccessLevel: .public))
print("\\(target.name): \\(symbolGraph.directoryPath)")
}
}
}
"""
)
// Check that if we don't pass any target, we successfully get symbol graph information for all targets in the package, and at different paths.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["generate-documentation"], packagePath: packageDir)
XCTAssertMatch(stdout, .and(.contains("MyLibrary:"), .contains("mypackage/MyLibrary")))
XCTAssertMatch(stdout, .and(.contains("MyCommand:"), .contains("mypackage/MyCommand")))
}
// Check that if we pass a target, we successfully get symbol graph information for just the target we asked for.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["generate-documentation", "--target", "MyLibrary"], packagePath: packageDir)
XCTAssertMatch(stdout, .and(.contains("MyLibrary:"), .contains("mypackage/MyLibrary")))
XCTAssertNoMatch(stdout, .and(.contains("MyCommand:"), .contains("mypackage/MyCommand")))
}
}
}
func testCommandPluginBuildingCallbacks() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, an executable, and a command plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyAutomaticLibrary",
targets: ["MyLibrary"]
),
.library(
name: "MyStaticLibrary",
type: .static,
targets: ["MyLibrary"]
),
.library(
name: "MyDynamicLibrary",
type: .dynamic,
targets: ["MyLibrary"]
),
.executable(
name: "MyExecutable",
targets: ["MyExecutable"]
),
],
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyExecutable",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "my-build-tester", description: "Help description")
)
),
]
)
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Extract the plugin arguments.
var argExtractor = ArgumentExtractor(arguments)
let productNames = argExtractor.extractOption(named: "product")
if productNames.count != 1 {
throw "Expected exactly one product name, but had: \\(productNames.joined(separator: ", "))"
}
let products = try context.package.products(named: productNames)
let printCommands = (argExtractor.extractFlag(named: "print-commands") > 0)
let release = (argExtractor.extractFlag(named: "release") > 0)
if let unextractedArgs = argExtractor.unextractedOptionsOrFlags.first {
throw "Unknown option: \\(unextractedArgs)"
}
let positionalArgs = argExtractor.remainingArguments
if !positionalArgs.isEmpty {
throw "Unexpected extra arguments: \\(positionalArgs)"
}
do {
var parameters = PackageManager.BuildParameters()
parameters.configuration = release ? .release : .debug
parameters.logging = printCommands ? .verbose : .concise
parameters.otherSwiftcFlags = ["-DEXTRA_SWIFT_FLAG"]
let result = try packageManager.build(.product(products[0].name), parameters: parameters)
print("succeeded: \\(result.succeeded)")
for artifact in result.builtArtifacts {
print("artifact-path: \\(artifact.path.string)")
print("artifact-kind: \\(artifact.kind)")
}
print("log:\\n\\(result.logText)")
}
catch {
print("error from the plugin host: \\(error)")
}
}
}
extension String: Error {}
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending("library.swift"), string: """
public func GetGreeting() -> String { return "Hello" }
"""
)
let myExecutableTargetDir = packageDir.appending(components: "Sources", "MyExecutable")
try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExecutableTargetDir.appending("main.swift"), string: """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
)
// Invoke the plugin with parameters choosing a verbose build of MyExecutable for debugging.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["my-build-tester", "--product", "MyExecutable", "--print-commands"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Building for debugging..."))
XCTAssertNoMatch(stdout, .contains("Building for production..."))
XCTAssertMatch(stdout, .contains("-module-name MyExecutable"))
XCTAssertMatch(stdout, .contains("-DEXTRA_SWIFT_FLAG"))
XCTAssertMatch(stdout, .contains("Build of product 'MyExecutable' complete!"))
XCTAssertMatch(stdout, .contains("succeeded: true"))
XCTAssertMatch(stdout, .and(.contains("artifact-path:"), .contains("debug/MyExecutable")))
XCTAssertMatch(stdout, .and(.contains("artifact-kind:"), .contains("executable")))
}
// Invoke the plugin with parameters choosing a concise build of MyExecutable for release.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["my-build-tester", "--product", "MyExecutable", "--release"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Building for production..."))
XCTAssertNoMatch(stdout, .contains("Building for debug..."))
XCTAssertNoMatch(stdout, .contains("-module-name MyExecutable"))
XCTAssertMatch(stdout, .contains("Build of product 'MyExecutable' complete!"))
XCTAssertMatch(stdout, .contains("succeeded: true"))
XCTAssertMatch(stdout, .and(.contains("artifact-path:"), .contains("release/MyExecutable")))
XCTAssertMatch(stdout, .and(.contains("artifact-kind:"), .contains("executable")))
}
// Invoke the plugin with parameters choosing a verbose build of MyStaticLibrary for release.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["my-build-tester", "--product", "MyStaticLibrary", "--print-commands", "--release"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Building for production..."))
XCTAssertNoMatch(stdout, .contains("Building for debug..."))
XCTAssertNoMatch(stdout, .contains("-module-name MyLibrary"))
XCTAssertMatch(stdout, .contains("Build of product 'MyStaticLibrary' complete!"))
XCTAssertMatch(stdout, .contains("succeeded: true"))
XCTAssertMatch(stdout, .and(.contains("artifact-path:"), .contains("release/libMyStaticLibrary.")))
XCTAssertMatch(stdout, .and(.contains("artifact-kind:"), .contains("staticLibrary")))
}
// Invoke the plugin with parameters choosing a verbose build of MyDynamicLibrary for release.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["my-build-tester", "--product", "MyDynamicLibrary", "--print-commands", "--release"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Building for production..."))
XCTAssertNoMatch(stdout, .contains("Building for debug..."))
XCTAssertNoMatch(stdout, .contains("-module-name MyLibrary"))
XCTAssertMatch(stdout, .contains("Build of product 'MyDynamicLibrary' complete!"))
XCTAssertMatch(stdout, .contains("succeeded: true"))
XCTAssertMatch(stdout, .and(.contains("artifact-path:"), .contains("release/libMyDynamicLibrary.")))
XCTAssertMatch(stdout, .and(.contains("artifact-kind:"), .contains("dynamicLibrary")))
}
}
}
func testCommandPluginTestingCallbacks() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
// Depending on how the test is running, the `llvm-profdata` and `llvm-cov` tool might be unavailable.
try XCTSkipIf((try? UserToolchain.default.getLLVMProf()) == nil, "skipping test because the `llvm-profdata` tool isn't available")
try XCTSkipIf((try? UserToolchain.default.getLLVMCov()) == nil, "skipping test because the `llvm-cov` tool isn't available")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library, a command plugin, and a couple of tests.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
targets: [
.target(
name: "MyLibrary"
),
.plugin(
name: "MyPlugin",
capability: .command(
intent: .custom(verb: "my-test-tester", description: "Help description")
)
),
.testTarget(
name: "MyBasicTests"
),
.testTarget(
name: "MyExtendedTests"
),
]
)
"""
)
let myPluginTargetDir = packageDir.appending(components: "Plugins", "MyPlugin")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main
struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
do {
let result = try packageManager.test(.filtered(["MyBasicTests"]), parameters: .init(enableCodeCoverage: true))
assert(result.succeeded == true)
assert(result.testTargets.count == 1)
assert(result.testTargets[0].name == "MyBasicTests")
assert(result.testTargets[0].testCases.count == 2)
assert(result.testTargets[0].testCases[0].name == "MyBasicTests.TestSuite1")
assert(result.testTargets[0].testCases[0].tests.count == 2)
assert(result.testTargets[0].testCases[0].tests[0].name == "testBooleanInvariants")
assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)
assert(result.testTargets[0].testCases[0].tests[1].name == "testNumericalInvariants")
assert(result.testTargets[0].testCases[0].tests[1].result == .succeeded)
assert(result.testTargets[0].testCases[1].name == "MyBasicTests.TestSuite2")
assert(result.testTargets[0].testCases[1].tests.count == 1)
assert(result.testTargets[0].testCases[1].tests[0].name == "testStringInvariants")
assert(result.testTargets[0].testCases[1].tests[0].result == .succeeded)
assert(result.codeCoverageDataFile?.extension == "json")
}
catch {
print("error from the plugin host: \\(error)")
}
}
}
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending("library.swift"), string: """
public func Foo() { }
"""
)
let myBasicTestsTargetDir = packageDir.appending(components: "Tests", "MyBasicTests")
try localFileSystem.createDirectory(myBasicTestsTargetDir, recursive: true)
try localFileSystem.writeFileContents(myBasicTestsTargetDir.appending("Test1.swift"), string: """
import XCTest
class TestSuite1: XCTestCase {
func testBooleanInvariants() throws {
XCTAssertEqual(true || true, true)
}
func testNumericalInvariants() throws {
XCTAssertEqual(1 + 1, 2)
}
}
"""
)
try localFileSystem.writeFileContents(myBasicTestsTargetDir.appending("Test2.swift"), string: """
import XCTest
class TestSuite2: XCTestCase {
func testStringInvariants() throws {
XCTAssertEqual("" + "", "")
}
}
"""
)
let myExtendedTestsTargetDir = packageDir.appending(components: "Tests", "MyExtendedTests")
try localFileSystem.createDirectory(myExtendedTestsTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExtendedTestsTargetDir.appending("Test3.swift"), string: """
import XCTest
class TestSuite3: XCTestCase {
func testArrayInvariants() throws {
XCTAssertEqual([] + [], [])
}
func testImpossibilities() throws {
XCTFail("no can do")
}
}
"""
)
// Check basic usage with filtering and code coverage. The plugin itself asserts a bunch of values.
try await SwiftPM.Package.execute(["my-test-tester"], packagePath: packageDir)
// We'll add checks for various error conditions here in a future commit.
}
}
func testPluginAPIs() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a plugin to test various parts of the API.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending("Package.swift"), string: """
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "MyPackage",
dependencies: [
.package(name: "HelperPackage", path: "VendoredDependencies/HelperPackage")
],
targets: [
.target(
name: "FirstTarget",
dependencies: [
]
),
.target(
name: "SecondTarget",
dependencies: [
"FirstTarget",
]
),
.target(
name: "ThirdTarget",
dependencies: [
"FirstTarget",
]
),
.target(
name: "FourthTarget",
dependencies: [
"SecondTarget",
"ThirdTarget",
.product(name: "HelperLibrary", package: "HelperPackage"),
]
),
.executableTarget(
name: "FifthTarget",
dependencies: [
"FirstTarget",
"ThirdTarget",
]
),
.testTarget(
name: "TestTarget",
dependencies: [
"SecondTarget",
]
),
.plugin(
name: "PrintTargetDependencies",
capability: .command(
intent: .custom(verb: "print-target-dependencies", description: "Plugin that prints target dependencies; argument is name of target")
)
),
]
)
""")
let firstTargetDir = packageDir.appending(components: "Sources", "FirstTarget")
try localFileSystem.createDirectory(firstTargetDir, recursive: true)
try localFileSystem.writeFileContents(firstTargetDir.appending("library.swift"), string: """
public func FirstFunc() { }
""")
let secondTargetDir = packageDir.appending(components: "Sources", "SecondTarget")
try localFileSystem.createDirectory(secondTargetDir, recursive: true)
try localFileSystem.writeFileContents(secondTargetDir.appending("library.swift"), string: """
public func SecondFunc() { }
""")
let thirdTargetDir = packageDir.appending(components: "Sources", "ThirdTarget")
try localFileSystem.createDirectory(thirdTargetDir, recursive: true)
try localFileSystem.writeFileContents(thirdTargetDir.appending("library.swift"), string: """
public func ThirdFunc() { }
""")
let fourthTargetDir = packageDir.appending(components: "Sources", "FourthTarget")
try localFileSystem.createDirectory(fourthTargetDir, recursive: true)
try localFileSystem.writeFileContents(fourthTargetDir.appending("library.swift"), string: """
public func FourthFunc() { }
""")
let fifthTargetDir = packageDir.appending(components: "Sources", "FifthTarget")
try localFileSystem.createDirectory(fifthTargetDir, recursive: true)
try localFileSystem.writeFileContents(fifthTargetDir.appending("main.swift"), string: """
@main struct MyExec {
func run() throws {}
}
""")
let testTargetDir = packageDir.appending(components: "Tests", "TestTarget")
try localFileSystem.createDirectory(testTargetDir, recursive: true)
try localFileSystem.writeFileContents(testTargetDir.appending("tests.swift"), string: """
import XCTest
class MyTestCase: XCTestCase {
}
""")
let pluginTargetTargetDir = packageDir.appending(components: "Plugins", "PrintTargetDependencies")
try localFileSystem.createDirectory(pluginTargetTargetDir, recursive: true)
try localFileSystem.writeFileContents(pluginTargetTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main struct PrintTargetDependencies: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
// Print names of the recursive dependencies of the given target.
var argExtractor = ArgumentExtractor(arguments)
guard let targetName = argExtractor.extractOption(named: "target").first else {
throw "No target argument provided"
}
guard let target = try? context.package.targets(named: [targetName]).first else {
throw "No target found with the name '\\(targetName)'"
}
print("Recursive dependencies of '\\(target.name)': \\(target.recursiveTargetDependencies.map(\\.name))")
let execProducts = context.package.products(ofType: ExecutableProduct.self)
print("execProducts: \\(execProducts.map{ $0.name })")
let swiftTargets = context.package.targets(ofType: SwiftSourceModuleTarget.self)
print("swiftTargets: \\(swiftTargets.map{ $0.name }.sorted())")
let swiftSources = swiftTargets.flatMap{ $0.sourceFiles(withSuffix: ".swift") }
print("swiftSources: \\(swiftSources.map{ $0.path.lastComponent }.sorted())")
if let target = target.sourceModule {
print("Module kind of '\\(target.name)': \\(target.kind)")
}
var sourceModules = context.package.sourceModules
print("sourceModules in package: \\(sourceModules.map { $0.name })")
sourceModules = context.package.products.first?.sourceModules ?? []
print("sourceModules in first product: \\(sourceModules.map { $0.name })")
}
}
extension String: Error {}
""")
// Create a separate vendored package so that we can test dependencies across products in other packages.
let helperPackageDir = packageDir.appending(components: "VendoredDependencies", "HelperPackage")
try localFileSystem.createDirectory(helperPackageDir, recursive: true)
try localFileSystem.writeFileContents(helperPackageDir.appending("Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "HelperPackage",
products: [
.library(
name: "HelperLibrary",
targets: ["HelperLibrary"])
],
targets: [
.target(
name: "HelperLibrary",
path: ".")
]
)
""")
try localFileSystem.writeFileContents(helperPackageDir.appending("library.swift"), string: """
public func Foo() { }
""")
// Check that a target doesn't include itself in its recursive dependencies.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["print-target-dependencies", "--target", "SecondTarget"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Recursive dependencies of 'SecondTarget': [\"FirstTarget\"]"))
XCTAssertMatch(stdout, .contains("Module kind of 'SecondTarget': generic"))
}
// Check that targets are not included twice in recursive dependencies.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["print-target-dependencies", "--target", "ThirdTarget"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Recursive dependencies of 'ThirdTarget': [\"FirstTarget\"]"))
XCTAssertMatch(stdout, .contains("Module kind of 'ThirdTarget': generic"))
}
// Check that product dependencies work in recursive dependencies.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["print-target-dependencies", "--target", "FourthTarget"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Recursive dependencies of 'FourthTarget': [\"FirstTarget\", \"SecondTarget\", \"ThirdTarget\", \"HelperLibrary\"]"))
XCTAssertMatch(stdout, .contains("Module kind of 'FourthTarget': generic"))
}
// Check some of the other utility APIs.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["print-target-dependencies", "--target", "FifthTarget"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("execProducts: [\"FifthTarget\"]"))
XCTAssertMatch(stdout, .contains("swiftTargets: [\"FifthTarget\", \"FirstTarget\", \"FourthTarget\", \"SecondTarget\", \"TestTarget\", \"ThirdTarget\"]"))
XCTAssertMatch(stdout, .contains("swiftSources: [\"library.swift\", \"library.swift\", \"library.swift\", \"library.swift\", \"main.swift\", \"tests.swift\"]"))
XCTAssertMatch(stdout, .contains("Module kind of 'FifthTarget': executable"))
}
// Check a test target.
do {
let (stdout, _) = try await SwiftPM.Package.execute(["print-target-dependencies", "--target", "TestTarget"], packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Recursive dependencies of 'TestTarget': [\"FirstTarget\", \"SecondTarget\"]"))
XCTAssertMatch(stdout, .contains("Module kind of 'TestTarget': test"))
}
}
}
func testPluginCompilationBeforeBuilding() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a couple of plugins a other targets and products.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending(components: "Package.swift"), string: """
// swift-tools-version: 5.6
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.library(
name: "MyLibrary",
targets: ["MyLibrary"]
),
.executable(
name: "MyExecutable",
targets: ["MyExecutable"]
),
],
targets: [
.target(
name: "MyLibrary"
),
.executableTarget(
name: "MyExecutable",
dependencies: ["MyLibrary"]
),
.plugin(
name: "MyBuildToolPlugin",
capability: .buildTool()
),
.plugin(
name: "MyCommandPlugin",
capability: .command(
intent: .custom(verb: "my-build-tester", description: "Help description")
)
),
]
)
"""
)
let myLibraryTargetDir = packageDir.appending(components: "Sources", "MyLibrary")
try localFileSystem.createDirectory(myLibraryTargetDir, recursive: true)
try localFileSystem.writeFileContents(myLibraryTargetDir.appending("library.swift"), string: """
public func GetGreeting() -> String { return "Hello" }
"""
)
let myExecutableTargetDir = packageDir.appending(components: "Sources", "MyExecutable")
try localFileSystem.createDirectory(myExecutableTargetDir, recursive: true)
try localFileSystem.writeFileContents(myExecutableTargetDir.appending("main.swift"), string: """
import MyLibrary
print("\\(GetGreeting()), World!")
"""
)
let myBuildToolPluginTargetDir = packageDir.appending(components: "Plugins", "MyBuildToolPlugin")
try localFileSystem.createDirectory(myBuildToolPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myBuildToolPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main struct MyBuildToolPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] {
return []
}
}
"""
)
let myCommandPluginTargetDir = packageDir.appending(components: "Plugins", "MyCommandPlugin")
try localFileSystem.createDirectory(myCommandPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myCommandPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
}
}
"""
)
// Check that building without options compiles both plugins and that the build proceeds.
do {
let (stdout, _) = try await SwiftPM.Build.execute(packagePath: packageDir)
XCTAssertMatch(stdout, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(stdout, .contains("Compiling plugin MyCommandPlugin"))
XCTAssertMatch(stdout, .contains("Building for debugging..."))
}
// Check that building just one of them just compiles that plugin and doesn't build anything else.
do {
let (stdout, _) = try await SwiftPM.Build.execute(["--target", "MyCommandPlugin"], packagePath: packageDir)
XCTAssertNoMatch(stdout, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(stdout, .contains("Compiling plugin MyCommandPlugin"))
XCTAssertNoMatch(stdout, .contains("Building for debugging..."))
}
// Deliberately break the command plugin.
try localFileSystem.writeFileContents(myCommandPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main struct MyCommandPlugin: CommandPlugin {
func performCommand(
context: PluginContext,
arguments: [String]
) throws {
this is an error
}
}
"""
)
// Check that building stops after compiling the plugin and doesn't proceed.
// Run this test a number of times to try to catch any race conditions.
for _ in 1...5 {
await XCTAssertAsyncThrowsError(try await SwiftPM.Build.execute(packagePath: packageDir)) { error in
guard case SwiftPMError.executionFailure(_, let stdout, _) = error else {
return XCTFail("invalid error \(error)")
}
XCTAssertMatch(stdout, .contains("Compiling plugin MyBuildToolPlugin"))
XCTAssertMatch(stdout, .contains("Compiling plugin MyCommandPlugin"))
XCTAssertMatch(stdout, .contains("error: consecutive statements on a line must be separated by ';'"))
XCTAssertNoMatch(stdout, .contains("Building for debugging..."))
}
}
}
}
func testSinglePluginTarget() async throws {
// Only run the test if the environment in which we're running actually supports Swift concurrency (which the plugin APIs require).
try XCTSkipIf(!UserToolchain.default.supportsSwiftConcurrency(), "skipping because test environment doesn't support concurrency")
try await testWithTemporaryDirectory { tmpPath in
// Create a sample package with a library target and a plugin.
let packageDir = tmpPath.appending(components: "MyPackage")
try localFileSystem.createDirectory(packageDir, recursive: true)
try localFileSystem.writeFileContents(packageDir.appending("Package.swift"), string: """
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "MyPackage",
products: [
.plugin(name: "Foo", targets: ["Foo"])
],
dependencies: [
],
targets: [
.plugin(
name: "Foo",
capability: .command(
intent: .custom(verb: "Foo", description: "Plugin example"),
permissions: []
)
)
]
)
""")
let myPluginTargetDir = packageDir.appending(components: "Plugins", "Foo")
try localFileSystem.createDirectory(myPluginTargetDir, recursive: true)
try localFileSystem.writeFileContents(myPluginTargetDir.appending("plugin.swift"), string: """
import PackagePlugin
@main struct FooPlugin: BuildToolPlugin {
func createBuildCommands(
context: PluginContext,
target: Target
) throws -> [Command] { }
}
""")
// Load a workspace from the package.
let observability = ObservabilitySystem.makeForTesting()
let workspace = try Workspace(
fileSystem: localFileSystem,
forRootPackage: packageDir,
customManifestLoader: ManifestLoader(toolchain: UserToolchain.default),
delegate: MockWorkspaceDelegate()
)
// Load the root manifest.
let rootInput = PackageGraphRootInput(packages: [packageDir], dependencies: [])
let rootManifests = try await workspace.loadRootManifests(
packages: rootInput.packages,
observabilityScope: observability.topScope
)
XCTAssert(rootManifests.count == 1, "\(rootManifests)")
// Load the package graph.
let _ = try workspace.loadPackageGraph(rootInput: rootInput, observabilityScope: observability.topScope)
XCTAssertNoDiagnostics(observability.diagnostics)
}
}
}
|