/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmExportFileGenerator_h #define cmExportFileGenerator_h #include "cmCommand.h" #include "cmGeneratorExpression.h" #include "cmVersion.h" #include "cmVersionMacros.h" #define STRINGIFY_HELPER(X) #X #define STRINGIFY(X) STRINGIFY_HELPER(X) #define DEVEL_CMAKE_VERSION(major, minor) \ (CMake_VERSION_ENCODE(major, minor, 0) > \ CMake_VERSION_ENCODE(CMake_VERSION_MAJOR, CMake_VERSION_MINOR, 0) \ ? STRINGIFY(CMake_VERSION_MAJOR) "." STRINGIFY( \ CMake_VERSION_MINOR) "." STRINGIFY(CMake_VERSION_PATCH) \ : #major "." #minor ".0") class cmTargetExport; /** \class cmExportFileGenerator * \brief Generate a file exporting targets from a build or install tree. * * cmExportFileGenerator is the superclass for * cmExportBuildFileGenerator and cmExportInstallFileGenerator. It * contains common code generation routines for the two kinds of * export implementations. */ class cmExportFileGenerator { public: cmExportFileGenerator(); virtual ~cmExportFileGenerator() {} /** Set the full path to the export file to generate. */ void SetExportFile(const char* mainFile); const char* GetMainExportFileName() const; /** Set the namespace in which to place exported target names. */ void SetNamespace(const std::string& ns) { this->Namespace = ns; } std::string GetNamespace() const { return this->Namespace; } void SetExportOld(bool exportOld) { this->ExportOld = exportOld; } /** Add a configuration to be exported. */ void AddConfiguration(const std::string& config); /** Actually generate the export file. Returns whether there was an error. */ bool GenerateImportFile(); protected: typedef std::map ImportPropertyMap; // Generate per-configuration target information to the given output // stream. void GenerateImportConfig(std::ostream& os, const std::string& config, std::vector& missingTargets); // Methods to implement export file code generation. void GenerateImportHeaderCode(std::ostream& os, const std::string& config = ""); void GenerateImportFooterCode(std::ostream& os); void GenerateImportVersionCode(std::ostream& os); void GenerateImportTargetCode(std::ostream& os, cmGeneratorTarget const* target); void GenerateImportPropertyCode(std::ostream& os, const std::string& config, cmGeneratorTarget const* target, ImportPropertyMap const& properties); void GenerateImportedFileChecksCode( std::ostream& os, cmGeneratorTarget* target, ImportPropertyMap const& properties, const std::set& importedLocations); void GenerateImportedFileCheckLoop(std::ostream& os); void GenerateMissingTargetsCheckCode( std::ostream& os, const std::vector& missingTargets); void GenerateExpectedTargetsCode(std::ostream& os, const std::string& expectedTargets); // Collect properties with detailed information about targets beyond // their location on disk. void SetImportDetailProperties(const std::string& config, std::string const& suffix, cmGeneratorTarget* target, ImportPropertyMap& properties, std::vector& missingTargets); template void SetImportLinkProperty(std::string const& suffix, cmGeneratorTarget* target, const std::string& propName, std::vector const& entries, ImportPropertyMap& properties, std::vector& missingTargets); /** Each subclass knows how to generate its kind of export file. */ virtual bool GenerateMainFile(std::ostream& os) = 0; /** Each subclass knows where the target files are located. */ virtual void GenerateImportTargetsConfig( std::ostream& os, const std::string& config, std::string const& suffix, std::vector& missingTargets) = 0; /** Each subclass knows how to deal with a target that is missing from an * export set. */ virtual void HandleMissingTarget(std::string& link_libs, std::vector& missingTargets, cmGeneratorTarget* depender, cmGeneratorTarget* dependee) = 0; void PopulateInterfaceProperty(const std::string&, cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext, ImportPropertyMap& properties, std::vector& missingTargets); bool PopulateInterfaceLinkLibrariesProperty( cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext, ImportPropertyMap& properties, std::vector& missingTargets); void PopulateInterfaceProperty(const std::string& propName, cmGeneratorTarget* target, ImportPropertyMap& properties); void PopulateCompatibleInterfaceProperties(cmGeneratorTarget* target, ImportPropertyMap& properties); void GenerateInterfaceProperties(cmGeneratorTarget const* target, std::ostream& os, const ImportPropertyMap& properties); void PopulateIncludeDirectoriesInterface( cmTargetExport* target, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector& missingTargets); void PopulateSourcesInterface( cmTargetExport* target, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector& missingTargets); void SetImportLinkInterface( const std::string& config, std::string const& suffix, cmGeneratorExpression::PreprocessContext preprocessRule, cmGeneratorTarget* target, ImportPropertyMap& properties, std::vector& missingTargets); enum FreeTargetsReplace { ReplaceFreeTargets, NoReplaceFreeTargets }; void ResolveTargetsInGeneratorExpressions( std::string& input, cmGeneratorTarget* target, std::vector& missingTargets, FreeTargetsReplace replace = NoReplaceFreeTargets); void GenerateRequiredCMakeVersion(std::ostream& os, const char* versionString); // The namespace in which the exports are placed in the generated file. std::string Namespace; bool ExportOld; // The set of configurations to export. std::vector Configurations; // The file to generate. std::string MainImportFile; std::string FileDir; std::string FileBase; std::string FileExt; bool AppendMode; // The set of targets included in the export. std::set ExportedTargets; private: void PopulateInterfaceProperty(const std::string&, const std::string&, cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext, ImportPropertyMap& properties, std::vector& missingTargets); bool AddTargetNamespace(std::string& input, cmGeneratorTarget* target, std::vector& missingTargets); void ResolveTargetsInGeneratorExpression( std::string& input, cmGeneratorTarget* target, std::vector& missingTargets); virtual void ReplaceInstallPrefix(std::string& input); virtual std::string InstallNameDir(cmGeneratorTarget* target, const std::string& config) = 0; }; #endif >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
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmCTestTestHandler.h"

#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstddef> // IWYU pragma: keep
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <functional>
#include <iomanip>
#include <iterator>
#include <set>
#include <sstream>
#include <utility>

#include <cm/memory>
#include <cm/string_view>
#include <cmext/algorithm>
#include <cmext/string_view>

#include "cmsys/FStream.hxx"
#include <cmsys/Base64.h>
#include <cmsys/Directory.hxx>
#include <cmsys/RegularExpression.hxx>

#include "cm_utf8.h"

#include "cmCTest.h"
#include "cmCTestMultiProcessHandler.h"
#include "cmCTestResourceGroupsLexerHelper.h"
#include "cmDuration.h"
#include "cmExecutionStatus.h"
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmProperty.h"
#include "cmState.h"
#include "cmStateSnapshot.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"
#include "cmXMLWriter.h"
#include "cmake.h"

namespace {

class cmCTestCommand
{
public:
  cmCTestCommand(cmCTestTestHandler* testHandler)
    : TestHandler(testHandler)
  {
  }

  virtual ~cmCTestCommand() = default;

  bool operator()(std::vector<cmListFileArgument> const& args,
                  cmExecutionStatus& status)
  {
    cmMakefile& mf = status.GetMakefile();
    std::vector<std::string> expandedArguments;
    if (!mf.ExpandArguments(args, expandedArguments)) {
      // There was an error expanding arguments.  It was already
      // reported, so we can skip this command without error.
      return true;
    }
    return this->InitialPass(expandedArguments, status);
  }

  virtual bool InitialPass(std::vector<std::string> const& args,
                           cmExecutionStatus& status) = 0;

  cmCTestTestHandler* TestHandler;
};

bool cmCTestSubdirCommand(std::vector<std::string> const& args,
                          cmExecutionStatus& status)
{
  if (args.empty()) {
    status.SetError("called with incorrect number of arguments");
    return false;
  }
  std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  for (std::string const& arg : args) {
    std::string fname;

    if (cmSystemTools::FileIsFullPath(arg)) {
      fname = arg;
    } else {
      fname = cmStrCat(cwd, '/', arg);
    }

    if (!cmSystemTools::FileIsDirectory(fname)) {
      // No subdirectory? So what...
      continue;
    }
    bool readit = false;
    {
      cmWorkingDirectory workdir(fname);
      if (workdir.Failed()) {
        status.SetError("Failed to change directory to " + fname + " : " +
                        std::strerror(workdir.GetLastResult()));
        return false;
      }
      const char* testFilename;
      if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
        // does the CTestTestfile.cmake exist ?
        testFilename = "CTestTestfile.cmake";
      } else if (cmSystemTools::FileExists("DartTestfile.txt")) {
        // does the DartTestfile.txt exist ?
        testFilename = "DartTestfile.txt";
      } else {
        // No CTestTestfile? Who cares...
        continue;
      }
      fname += "/";
      fname += testFilename;
      readit = status.GetMakefile().ReadDependentFile(fname);
    }
    if (!readit) {
      status.SetError(cmStrCat("Could not load include file: ", fname));
      return false;
    }
  }
  return true;
}

bool cmCTestAddSubdirectoryCommand(std::vector<std::string> const& args,
                                   cmExecutionStatus& status)
{
  if (args.empty()) {
    status.SetError("called with incorrect number of arguments");
    return false;
  }

  std::string fname =
    cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), '/', args[0]);

  if (!cmSystemTools::FileExists(fname)) {
    // No subdirectory? So what...
    return true;
  }
  bool readit = false;
  {
    const char* testFilename;
    if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
      // does the CTestTestfile.cmake exist ?
      testFilename = "CTestTestfile.cmake";
    } else if (cmSystemTools::FileExists("DartTestfile.txt")) {
      // does the DartTestfile.txt exist ?
      testFilename = "DartTestfile.txt";
    } else {
      // No CTestTestfile? Who cares...
      return true;
    }
    fname += "/";
    fname += testFilename;
    readit = status.GetMakefile().ReadDependentFile(fname);
  }
  if (!readit) {
    status.SetError(cmStrCat("Could not find include file: ", fname));
    return false;
  }
  return true;
}

class cmCTestAddTestCommand : public cmCTestCommand
{
public:
  using cmCTestCommand::cmCTestCommand;

  /**
   * This is called when the command is first encountered in
   * the CMakeLists.txt file.
   */
  bool InitialPass(std::vector<std::string> const& /*args*/,
                   cmExecutionStatus& /*unused*/) override;
};

bool cmCTestAddTestCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus& status)
{
  if (args.size() < 2) {
    status.SetError("called with incorrect number of arguments");
    return false;
  }
  return this->TestHandler->AddTest(args);
}

class cmCTestSetTestsPropertiesCommand : public cmCTestCommand
{
public:
  using cmCTestCommand::cmCTestCommand;

  /**
   * This is called when the command is first encountered in
   * the CMakeLists.txt file.
   */
  bool InitialPass(std::vector<std::string> const& /*args*/,
                   cmExecutionStatus& /*unused*/) override;
};

bool cmCTestSetTestsPropertiesCommand::InitialPass(
  std::vector<std::string> const& args, cmExecutionStatus& /*unused*/)
{
  return this->TestHandler->SetTestsProperties(args);
}

class cmCTestSetDirectoryPropertiesCommand : public cmCTestCommand
{
public:
  using cmCTestCommand::cmCTestCommand;

  /**
   * This is called when the command is first encountered in
   * the CMakeLists.txt file.
   */
  bool InitialPass(std::vector<std::string> const& /*unused*/,
                   cmExecutionStatus& /*unused*/) override;
};

bool cmCTestSetDirectoryPropertiesCommand::InitialPass(
  std::vector<std::string> const& args, cmExecutionStatus&)
{
  return this->TestHandler->SetDirectoryProperties(args);
}

// get the next number in a string with numbers separated by ,
// pos is the start of the search and pos2 is the end of the search
// pos becomes pos2 after a call to GetNextNumber.
// -1 is returned at the end of the list.
inline int GetNextNumber(std::string const& in, int& val,
                         std::string::size_type& pos,
                         std::string::size_type& pos2)
{
  pos2 = in.find(',', pos);
  if (pos2 != std::string::npos) {
    if (pos2 - pos == 0) {
      val = -1;
    } else {
      val = atoi(in.substr(pos, pos2 - pos).c_str());
    }
    pos = pos2 + 1;
    return 1;
  }
  if (in.size() - pos == 0) {
    val = -1;
  } else {
    val = atoi(in.substr(pos, in.size() - pos).c_str());
  }
  return 0;
}

// get the next number in a string with numbers separated by ,
// pos is the start of the search and pos2 is the end of the search
// pos becomes pos2 after a call to GetNextNumber.
// -1 is returned at the end of the list.
inline int GetNextRealNumber(std::string const& in, double& val,
                             std::string::size_type& pos,
                             std::string::size_type& pos2)
{
  pos2 = in.find(',', pos);
  if (pos2 != std::string::npos) {
    if (pos2 - pos == 0) {
      val = -1;
    } else {
      val = atof(in.substr(pos, pos2 - pos).c_str());
    }
    pos = pos2 + 1;
    return 1;
  }
  if (in.size() - pos == 0) {
    val = -1;
  } else {
    val = atof(in.substr(pos, in.size() - pos).c_str());
  }
  return 0;
}

} // namespace

cmCTestTestHandler::cmCTestTestHandler()
{
  this->UseUnion = false;

  this->UseIncludeLabelRegExpFlag = false;
  this->UseExcludeLabelRegExpFlag = false;
  this->UseIncludeRegExpFlag = false;
  this->UseExcludeRegExpFlag = false;
  this->UseExcludeRegExpFirst = false;
  this->UseResourceSpec = false;

  this->CustomMaximumPassedTestOutputSize = 1 * 1024;
  this->CustomMaximumFailedTestOutputSize = 300 * 1024;

  this->MemCheck = false;

  this->LogFile = nullptr;

  // regex to detect <DartMeasurement>...</DartMeasurement>
  this->DartStuff.compile("(<DartMeasurement.*/DartMeasurement[a-zA-Z]*>)");
  // regex to detect each individual <DartMeasurement>...</DartMeasurement>
  this->DartStuff1.compile(
    "(<DartMeasurement[^<]*</DartMeasurement[a-zA-Z]*>)");
}

void cmCTestTestHandler::Initialize()
{
  this->Superclass::Initialize();

  this->ElapsedTestingTime = cmDuration();

  this->TestResults.clear();

  this->CustomTestsIgnore.clear();
  this->StartTest.clear();
  this->EndTest.clear();

  this->CustomPreTest.clear();
  this->CustomPostTest.clear();
  this->CustomMaximumPassedTestOutputSize = 1 * 1024;
  this->CustomMaximumFailedTestOutputSize = 300 * 1024;

  this->TestsToRun.clear();

  this->UseIncludeLabelRegExpFlag = false;
  this->UseExcludeLabelRegExpFlag = false;
  this->UseIncludeRegExpFlag = false;
  this->UseExcludeRegExpFlag = false;
  this->UseExcludeRegExpFirst = false;
  this->IncludeLabelRegularExpression = "";
  this->ExcludeLabelRegularExpression = "";
  this->IncludeRegExp.clear();
  this->ExcludeRegExp.clear();
  this->ExcludeFixtureRegExp.clear();
  this->ExcludeFixtureSetupRegExp.clear();
  this->ExcludeFixtureCleanupRegExp.clear();

  this->TestsToRunString.clear();
  this->UseUnion = false;
  this->TestList.clear();
}

void cmCTestTestHandler::PopulateCustomVectors(cmMakefile* mf)
{
  this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_PRE_TEST",
                                    this->CustomPreTest);
  this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_POST_TEST",
                                    this->CustomPostTest);
  this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_TESTS_IGNORE",
                                    this->CustomTestsIgnore);
  this->CTest->PopulateCustomInteger(
    mf, "CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE",
    this->CustomMaximumPassedTestOutputSize);
  this->CTest->PopulateCustomInteger(
    mf, "CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE",
    this->CustomMaximumFailedTestOutputSize);
}

int cmCTestTestHandler::PreProcessHandler()
{
  if (!this->ExecuteCommands(this->CustomPreTest)) {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "Problem executing pre-test command(s)." << std::endl);
    return 0;
  }
  return 1;
}

int cmCTestTestHandler::PostProcessHandler()
{
  if (!this->ExecuteCommands(this->CustomPostTest)) {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "Problem executing post-test command(s)." << std::endl);
    return 0;
  }
  return 1;
}

int cmCTestTestHandler::ProcessHandler()
{
  if (!this->ProcessOptions()) {
    return -1;
  }

  this->TestResults.clear();

  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                     (this->MemCheck ? "Memory check" : "Test")
                       << " project "
                       << cmSystemTools::GetCurrentWorkingDirectory()
                       << std::endl,
                     this->Quiet);
  if (!this->PreProcessHandler()) {
    return -1;
  }

  cmGeneratedFileStream mLogFile;
  this->StartLogFile((this->MemCheck ? "DynamicAnalysis" : "Test"), mLogFile);
  this->LogFile = &mLogFile;

  std::vector<std::string> passed;
  std::vector<std::string> failed;

  // start the real time clock
  auto clock_start = std::chrono::steady_clock::now();

  if (!this->ProcessDirectory(passed, failed)) {
    return -1;
  }

  auto clock_finish = std::chrono::steady_clock::now();

  bool noTestsFoundError = false;
  if (passed.size() + failed.size() == 0) {
    if (!this->CTest->GetShowOnly() && !this->CTest->ShouldPrintLabels() &&
        this->CTest->GetNoTestsMode() != cmCTest::NoTests::Ignore) {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 "No tests were found!!!" << std::endl);
      if (this->CTest->GetNoTestsMode() == cmCTest::NoTests::Error) {
        noTestsFoundError = true;
      }
    }
  } else {
    if (this->HandlerVerbose && !passed.empty() &&
        (this->UseIncludeRegExpFlag || this->UseExcludeRegExpFlag)) {
      cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                         std::endl
                           << "The following tests passed:" << std::endl,
                         this->Quiet);
      for (std::string const& j : passed) {
        cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                           "\t" << j << std::endl, this->Quiet);
      }
    }

    SetOfTests resultsSet(this->TestResults.begin(), this->TestResults.end());
    std::vector<cmCTestTestHandler::cmCTestTestResult> disabledTests;

    for (cmCTestTestResult const& ft : resultsSet) {
      if (cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_") ||
          ft.CompletionStatus == "Disabled") {
        disabledTests.push_back(ft);
      }
    }

    cmDuration durationInSecs = clock_finish - clock_start;
    this->LogTestSummary(passed, failed, durationInSecs);

    this->LogDisabledTests(disabledTests);

    this->LogFailedTests(failed, resultsSet);
  }

  if (!this->GenerateXML()) {
    return 1;
  }

  if (!this->PostProcessHandler()) {
    this->LogFile = nullptr;
    return -1;
  }

  if (!failed.empty()) {
    this->LogFile = nullptr;
    return -1;
  }

  if (noTestsFoundError) {
    this->LogFile = nullptr;
    return -1;
  }

  this->LogFile = nullptr;
  return 0;
}

bool cmCTestTestHandler::ProcessOptions()
{
  // Update internal data structure from generic one
  this->SetTestsToRunInformation(this->GetOption("TestsToRunInformation"));
  this->SetUseUnion(cmIsOn(this->GetOption("UseUnion")));
  if (cmIsOn(this->GetOption("ScheduleRandom"))) {
    this->CTest->SetScheduleType("Random");
  }
  if (const char* repeat = this->GetOption("Repeat")) {
    cmsys::RegularExpression repeatRegex(
      "^(UNTIL_FAIL|UNTIL_PASS|AFTER_TIMEOUT):([0-9]+)$");
    if (repeatRegex.find(repeat)) {
      std::string const& count = repeatRegex.match(2);
      unsigned long n = 1;
      cmStrToULong(count, &n); // regex guarantees success
      this->RepeatCount = static_cast<int>(n);
      if (this->RepeatCount > 1) {
        std::string const& mode = repeatRegex.match(1);
        if (mode == "UNTIL_FAIL") {
          this->RepeatMode = cmCTest::Repeat::UntilFail;
        } else if (mode == "UNTIL_PASS") {
          this->RepeatMode = cmCTest::Repeat::UntilPass;
        } else if (mode == "AFTER_TIMEOUT") {
          this->RepeatMode = cmCTest::Repeat::AfterTimeout;
        }
      }
    } else {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 "Repeat option invalid value: " << repeat << std::endl);
      return false;
    }
  }
  if (this->GetOption("ParallelLevel")) {
    this->CTest->SetParallelLevel(atoi(this->GetOption("ParallelLevel")));
  }

  if (this->GetOption("StopOnFailure")) {
    this->CTest->SetStopOnFailure(true);
  }

  const char* val;
  val = this->GetOption("LabelRegularExpression");
  if (val) {
    this->UseIncludeLabelRegExpFlag = true;
    this->IncludeLabelRegExp = val;
  }
  val = this->GetOption("ExcludeLabelRegularExpression");
  if (val) {
    this->UseExcludeLabelRegExpFlag = true;
    this->ExcludeLabelRegExp = val;
  }
  val = this->GetOption("IncludeRegularExpression");
  if (val) {
    this->UseIncludeRegExp();
    this->SetIncludeRegExp(val);
  }
  val = this->GetOption("ExcludeRegularExpression");
  if (val) {
    this->UseExcludeRegExp();
    this->SetExcludeRegExp(val);
  }
  val = this->GetOption("ExcludeFixtureRegularExpression");
  if (val) {
    this->ExcludeFixtureRegExp = val;
  }
  val = this->GetOption("ExcludeFixtureSetupRegularExpression");
  if (val) {
    this->ExcludeFixtureSetupRegExp = val;
  }
  val = this->GetOption("ExcludeFixtureCleanupRegularExpression");
  if (val) {
    this->ExcludeFixtureCleanupRegExp = val;
  }
  val = this->GetOption("ResourceSpecFile");
  if (val) {
    this->ResourceSpecFile = val;
  }
  this->SetRerunFailed(cmIsOn(this->GetOption("RerunFailed")));

  return true;
}

void cmCTestTestHandler::LogTestSummary(const std::vector<std::string>& passed,
                                        const std::vector<std::string>& failed,
                                        const cmDuration& durationInSecs)
{
  std::size_t total = passed.size() + failed.size();

  float percent = float(passed.size()) * 100.0f / float(total);
  if (!failed.empty() && percent > 99) {
    percent = 99;
  }

  std::string passColorCode;
  std::string failedColorCode;
  if (failed.empty()) {
    passColorCode = this->CTest->GetColorCode(cmCTest::Color::GREEN);
  } else {
    failedColorCode = this->CTest->GetColorCode(cmCTest::Color::RED);
  }
  cmCTestLog(this->CTest, HANDLER_OUTPUT,
             std::endl
               << passColorCode << std::lround(percent) << "% tests passed"
               << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
               << ", " << failedColorCode << failed.size() << " tests failed"
               << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
               << " out of " << total << std::endl);
  if ((!this->CTest->GetLabelsForSubprojects().empty() &&
       this->CTest->GetSubprojectSummary())) {
    this->PrintLabelOrSubprojectSummary(true);
  }
  if (this->CTest->GetLabelSummary()) {
    this->PrintLabelOrSubprojectSummary(false);
  }
  char realBuf[1024];
  sprintf(realBuf, "%6.2f sec", durationInSecs.count());
  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                     "\nTotal Test time (real) = " << realBuf << "\n",
                     this->Quiet);
}

void cmCTestTestHandler::LogDisabledTests(
  const std::vector<cmCTestTestResult>& disabledTests)
{
  if (!disabledTests.empty()) {
    cmGeneratedFileStream ofs;
    cmCTestLog(this->CTest, HANDLER_OUTPUT,
               std::endl
                 << "The following tests did not run:" << std::endl);
    this->StartLogFile("TestsDisabled", ofs);

    const char* disabled_reason;
    cmCTestLog(this->CTest, HANDLER_OUTPUT,
               this->CTest->GetColorCode(cmCTest::Color::BLUE));
    for (cmCTestTestResult const& dt : disabledTests) {
      ofs << dt.TestCount << ":" << dt.Name << std::endl;
      if (dt.CompletionStatus == "Disabled") {
        disabled_reason = "Disabled";
      } else {
        disabled_reason = "Skipped";
      }
      cmCTestLog(this->CTest, HANDLER_OUTPUT,
                 "\t" << std::setw(3) << dt.TestCount << " - " << dt.Name
                      << " (" << disabled_reason << ")" << std::endl);
    }
    cmCTestLog(this->CTest, HANDLER_OUTPUT,
               this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR));
  }
}

void cmCTestTestHandler::LogFailedTests(const std::vector<std::string>& failed,
                                        const SetOfTests& resultsSet)
{
  if (!failed.empty()) {
    cmGeneratedFileStream ofs;
    cmCTestLog(this->CTest, HANDLER_OUTPUT,
               std::endl
                 << "The following tests FAILED:" << std::endl);
    this->StartLogFile("TestsFailed", ofs);

    for (cmCTestTestResult const& ft : resultsSet) {
      if (ft.Status != cmCTestTestHandler::COMPLETED &&
          !cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_") &&
          ft.CompletionStatus != "Disabled") {
        ofs << ft.TestCount << ":" << ft.Name << std::endl;
        auto testColor = cmCTest::Color::RED;
        if (this->GetTestStatus(ft) == "Not Run") {
          testColor = cmCTest::Color::YELLOW;
        }
        cmCTestLog(
          this->CTest, HANDLER_OUTPUT,
          "\t" << this->CTest->GetColorCode(testColor) << std::setw(3)
               << ft.TestCount << " - " << ft.Name << " ("
               << this->GetTestStatus(ft) << ")"
               << this->CTest->GetColorCode(cmCTest::Color::CLEAR_COLOR)
               << std::endl);
      }
    }
  }
}

bool cmCTestTestHandler::GenerateXML()
{
  if (this->CTest->GetProduceXML()) {
    cmGeneratedFileStream xmlfile;
    if (!this->StartResultingXML(
          (this->MemCheck ? cmCTest::PartMemCheck : cmCTest::PartTest),
          (this->MemCheck ? "DynamicAnalysis" : "Test"), xmlfile)) {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 "Cannot create "
                   << (this->MemCheck ? "memory check" : "testing")
                   << " XML file" << std::endl);
      this->LogFile = nullptr;
      return false;
    }
    cmXMLWriter xml(xmlfile);
    this->GenerateDartOutput(xml);
  }

  return true;
}

void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject)
{
  // collect subproject labels
  std::vector<std::string> subprojects =
    this->CTest->GetLabelsForSubprojects();
  std::map<std::string, double> labelTimes;
  std::map<std::string, int> labelCounts;
  std::set<std::string> labels;
  std::string::size_type maxlen = 0;
  // initialize maps
  for (cmCTestTestProperties& p : this->TestList) {
    for (std::string const& l : p.Labels) {
      // first check to see if the current label is a subproject label
      bool isSubprojectLabel = false;
      auto subproject = std::find(subprojects.begin(), subprojects.end(), l);
      if (subproject != subprojects.end()) {
        isSubprojectLabel = true;
      }
      // if we are doing sub projects and this label is one, then use it
      // if we are not doing sub projects and the label is not one use it
      if (doSubProject == isSubprojectLabel) {
        if (l.size() > maxlen) {
          maxlen = l.size();
        }
        labels.insert(l);
        labelTimes[l] = 0;
        labelCounts[l] = 0;
      }
    }
  }
  // fill maps
  for (cmCTestTestResult& result : this->TestResults) {
    cmCTestTestProperties& p = *result.Properties;
    for (std::string const& l : p.Labels) {
      // only use labels found in labels
      if (cm::contains(labels, l)) {
        labelTimes[l] +=
          result.ExecutionTime.count() * result.Properties->Processors;
        ++labelCounts[l];
      }
    }
  }
  // if no labels are found return and print nothing
  if (labels.empty()) {
    return;
  }
  // now print times
  if (doSubProject) {
    cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                       "\nSubproject Time Summary:", this->Quiet);
  } else {
    cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                       "\nLabel Time Summary:", this->Quiet);
  }
  for (std::string const& i : labels) {
    std::string label = i;
    label.resize(maxlen + 3, ' ');

    char buf[1024];
    sprintf(buf, "%6.2f sec*proc", labelTimes[i]);

    std::ostringstream labelCountStr;
    labelCountStr << "(" << labelCounts[i] << " test";
    if (labelCounts[i] > 1) {
      labelCountStr << "s";
    }
    labelCountStr << ")";
    cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                       "\n"
                         << label << " = " << buf << " "
                         << labelCountStr.str(),
                       this->Quiet);
    if (this->LogFile) {
      *this->LogFile << "\n" << i << " = " << buf << "\n";
    }
  }
  if (this->LogFile) {
    *this->LogFile << "\n";
  }
  cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet);
}

void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it)
{
  // if not using Labels to filter then return
  if (!this->UseIncludeLabelRegExpFlag) {
    return;
  }
  // if there are no labels and we are filtering by labels
  // then exclude the test as it does not have the label
  if (it.Labels.empty()) {
    it.IsInBasedOnREOptions = false;
    return;
  }
  // check to see if the label regular expression matches
  bool found = false; // assume it does not match
  // loop over all labels and look for match
  for (std::string const& l : it.Labels) {
    if (this->IncludeLabelRegularExpression.find(l)) {
      found = true;
    }
  }
  // if no match was found, exclude the test
  if (!found) {
    it.IsInBasedOnREOptions = false;
  }
}

void cmCTestTestHandler::CheckLabelFilterExclude(cmCTestTestProperties& it)
{
  // if not using Labels to filter then return
  if (!this->UseExcludeLabelRegExpFlag) {
    return;
  }
  // if there are no labels and we are excluding by labels
  // then do nothing as a no label can not be a match
  if (it.Labels.empty()) {
    return;
  }
  // check to see if the label regular expression matches
  bool found = false; // assume it does not match
  // loop over all labels and look for match
  for (std::string const& l : it.Labels) {
    if (this->ExcludeLabelRegularExpression.find(l)) {
      found = true;
    }
  }
  // if match was found, exclude the test
  if (found) {
    it.IsInBasedOnREOptions = false;
  }
}

void cmCTestTestHandler::CheckLabelFilter(cmCTestTestProperties& it)
{
  this->CheckLabelFilterInclude(it);
  this->CheckLabelFilterExclude(it);
}

bool cmCTestTestHandler::ComputeTestList()
{
  this->TestList.clear(); // clear list of test
  if (!this->GetListOfTests()) {
    return false;
  }

  if (this->RerunFailed) {
    this->ComputeTestListForRerunFailed();
    return true;
  }

  cmCTestTestHandler::ListOfTests::size_type tmsize = this->TestList.size();
  // how many tests are in based on RegExp?
  int inREcnt = 0;
  for (cmCTestTestProperties& tp : this->TestList) {
    this->CheckLabelFilter(tp);
    if (tp.IsInBasedOnREOptions) {
      inREcnt++;
    }
  }
  // expand the test list based on the union flag
  if (this->UseUnion) {
    this->ExpandTestsToRunInformation(static_cast<int>(tmsize));
  } else {
    this->ExpandTestsToRunInformation(inREcnt);
  }
  // Now create a final list of tests to run
  int cnt = 0;
  inREcnt = 0;
  std::string last_directory;
  ListOfTests finalList;
  for (cmCTestTestProperties& tp : this->TestList) {
    cnt++;
    if (tp.IsInBasedOnREOptions) {
      inREcnt++;
    }

    if (this->UseUnion) {
      // if it is not in the list and not in the regexp then skip
      if ((!this->TestsToRun.empty() &&
           !cm::contains(this->TestsToRun, cnt)) &&
          !tp.IsInBasedOnREOptions) {
        continue;
      }
    } else {
      // is this test in the list of tests to run? If not then skip it
      if ((!this->TestsToRun.empty() &&
           !cm::contains(this->TestsToRun, inREcnt)) ||
          !tp.IsInBasedOnREOptions) {
        continue;
      }
    }
    tp.Index = cnt; // save the index into the test list for this test
    finalList.push_back(tp);
  }

  this->UpdateForFixtures(finalList);

  // Save the total number of tests before exclusions
  this->TotalNumberOfTests = this->TestList.size();
  // Set the TestList to the final list of all test
  this->TestList = finalList;

  this->UpdateMaxTestNameWidth();
  return true;
}

void cmCTestTestHandler::ComputeTestListForRerunFailed()
{
  this->ExpandTestsToRunInformationForRerunFailed();

  ListOfTests finalList;
  int cnt = 0;
  for (cmCTestTestProperties& tp : this->TestList) {
    cnt++;

    // if this test is not in our list of tests to run, then skip it.
    if (!this->TestsToRun.empty() && !cm::contains(this->TestsToRun, cnt)) {
      continue;
    }

    tp.Index = cnt;
    finalList.push_back(tp);
  }

  this->UpdateForFixtures(finalList);

  // Save the total number of tests before exclusions
  this->TotalNumberOfTests = this->TestList.size();

  // Set the TestList to the list of failed tests to rerun
  this->TestList = finalList;

  this->UpdateMaxTestNameWidth();
}

void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
{
  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                     "Updating test list for fixtures" << std::endl,
                     this->Quiet);

  // Prepare regular expression evaluators
  std::string setupRegExp(this->ExcludeFixtureRegExp);
  std::string cleanupRegExp(this->ExcludeFixtureRegExp);
  if (!this->ExcludeFixtureSetupRegExp.empty()) {
    if (setupRegExp.empty()) {
      setupRegExp = this->ExcludeFixtureSetupRegExp;
    } else {
      setupRegExp.append("(" + setupRegExp + ")|(" +
                         this->ExcludeFixtureSetupRegExp + ")");
    }
  }
  if (!this->ExcludeFixtureCleanupRegExp.empty()) {
    if (cleanupRegExp.empty()) {
      cleanupRegExp = this->ExcludeFixtureCleanupRegExp;
    } else {
      cleanupRegExp.append("(" + cleanupRegExp + ")|(" +
                           this->ExcludeFixtureCleanupRegExp + ")");
    }
  }
  cmsys::RegularExpression excludeSetupRegex(setupRegExp);
  cmsys::RegularExpression excludeCleanupRegex(cleanupRegExp);

  // Prepare some maps to help us find setup and cleanup tests for
  // any given fixture
  using TestIterator = ListOfTests::const_iterator;
  using FixtureDependencies = std::multimap<std::string, TestIterator>;
  using FixtureDepsIterator = FixtureDependencies::const_iterator;
  FixtureDependencies fixtureSetups;
  FixtureDependencies fixtureCleanups;

  for (auto it = this->TestList.begin(); it != this->TestList.end(); ++it) {
    const cmCTestTestProperties& p = *it;

    for (std::string const& deps : p.FixturesSetup) {
      fixtureSetups.insert(std::make_pair(deps, it));
    }

    for (std::string const& deps : p.FixturesCleanup) {
      fixtureCleanups.insert(std::make_pair(deps, it));
    }
  }

  // Prepare fast lookup of tests already included in our list of tests
  std::set<std::string> addedTests;
  for (cmCTestTestProperties const& p : tests) {
    addedTests.insert(p.Name);
  }

  // These are lookups of fixture name to a list of indices into the final
  // tests array for tests which require that fixture and tests which are
  // setups for that fixture. They are needed at the end to populate
  // dependencies of the cleanup tests in our final list of tests.
  std::map<std::string, std::vector<size_t>> fixtureRequirements;
  std::map<std::string, std::vector<size_t>> setupFixturesAdded;

  // Use integer index for iteration because we append to
  // the tests vector as we go
  size_t fixtureTestsAdded = 0;
  std::set<std::string> addedFixtures;
  for (size_t i = 0; i < tests.size(); ++i) {
    // Skip disabled tests
    if (tests[i].Disabled) {
      continue;
    }

    // There are two things to do for each test:
    //   1. For every fixture required by this test, record that fixture as
    //      being required and create dependencies on that fixture's setup
    //      tests.
    //   2. Record all setup tests in the final test list so we can later make
    //      cleanup tests in the test list depend on their associated setup
    //      tests to enforce correct ordering.

    // 1. Handle fixture requirements
    //
    // Must copy the set of fixtures required because we may invalidate
    // the tests array by appending to it
    std::set<std::string> fixtures = tests[i].FixturesRequired;
    for (std::string const& requiredFixtureName : fixtures) {
      if (requiredFixtureName.empty()) {
        continue;
      }

      fixtureRequirements[requiredFixtureName].push_back(i);

      // Add dependencies to this test for all of the setup tests
      // associated with the required fixture. If any of those setup
      // tests fail, this test should not run. We make the fixture's
      // cleanup tests depend on this test case later.
      std::pair<FixtureDepsIterator, FixtureDepsIterator> setupRange =
        fixtureSetups.equal_range(requiredFixtureName);
      for (auto sIt = setupRange.first; sIt != setupRange.second; ++sIt) {
        const std::string& setupTestName = sIt->second->Name;
        tests[i].RequireSuccessDepends.insert(setupTestName);
        if (!cm::contains(tests[i].Depends, setupTestName)) {
          tests[i].Depends.push_back(setupTestName);
        }
      }

      // Append any fixture setup/cleanup tests to our test list if they
      // are not already in it (they could have been in the original
      // set of tests passed to us at the outset or have already been
      // added from a previously checked test). A fixture isn't required
      // to have setup/cleanup tests.
      if (!addedFixtures.insert(requiredFixtureName).second) {
        // Already seen this fixture, no need to check it again
        continue;
      }

      // Only add setup tests if this fixture has not been excluded
      if (setupRegExp.empty() ||
          !excludeSetupRegex.find(requiredFixtureName)) {
        std::pair<FixtureDepsIterator, FixtureDepsIterator> fixtureRange =
          fixtureSetups.equal_range(requiredFixtureName);
        for (auto it = fixtureRange.first; it != fixtureRange.second; ++it) {
          ListOfTests::const_iterator lotIt = it->second;
          const cmCTestTestProperties& p = *lotIt;

          if (!addedTests.insert(p.Name).second) {
            // Already have p in our test list
            continue;
          }

          // This is a test not yet in our list, so add it and
          // update its index to reflect where it was in the original
          // full list of all tests (needed to track individual tests
          // across ctest runs for re-run failed, etc.)
          tests.push_back(p);
          tests.back().Index =
            1 + static_cast<int>(std::distance(this->TestList.begin(), lotIt));
          ++fixtureTestsAdded;

          cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                             "Added setup test "
                               << p.Name << " required by fixture "
                               << requiredFixtureName << std::endl,
                             this->Quiet);
        }
      }

      // Only add cleanup tests if this fixture has not been excluded
      if (cleanupRegExp.empty() ||
          !excludeCleanupRegex.find(requiredFixtureName)) {
        std::pair<FixtureDepsIterator, FixtureDepsIterator> fixtureRange =
          fixtureCleanups.equal_range(requiredFixtureName);
        for (auto it = fixtureRange.first; it != fixtureRange.second; ++it) {
          ListOfTests::const_iterator lotIt = it->second;
          const cmCTestTestProperties& p = *lotIt;

          if (!addedTests.insert(p.Name).second) {
            // Already have p in our test list
            continue;
          }

          // This is a test not yet in our list, so add it and
          // update its index to reflect where it was in the original
          // full list of all tests (needed to track individual tests
          // across ctest runs for re-run failed, etc.)
          tests.push_back(p);
          tests.back().Index =
            1 + static_cast<int>(std::distance(this->TestList.begin(), lotIt));
          ++fixtureTestsAdded;

          cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                             "Added cleanup test "
                               << p.Name << " required by fixture "
                               << requiredFixtureName << std::endl,
                             this->Quiet);
        }
      }
    }

    // 2. Record all setup fixtures included in the final list of tests
    for (std::string const& setupFixtureName : tests[i].FixturesSetup) {
      if (setupFixtureName.empty()) {
        continue;
      }

      setupFixturesAdded[setupFixtureName].push_back(i);
    }
  }

  // Now that we have the final list of tests, we can update all cleanup
  // tests to depend on those tests which require that fixture and on any
  // setup tests for that fixture. The latter is required to handle the
  // pathological case where setup and cleanup tests are in the test set
  // but no other test has that fixture as a requirement.
  for (cmCTestTestProperties& p : tests) {
    const std::set<std::string>& cleanups = p.FixturesCleanup;
    for (std::string const& fixture : cleanups) {
      // This cleanup test could be part of the original test list that was
      // passed in. It is then possible that no other test requires the
      // fIt fixture, so we have to check for this.
      auto cIt = fixtureRequirements.find(fixture);
      if (cIt != fixtureRequirements.end()) {
        const std::vector<size_t>& indices = cIt->second;
        for (size_t index : indices) {
          const std::string& reqTestName = tests[index].Name;
          if (!cm::contains(p.Depends, reqTestName)) {
            p.Depends.push_back(reqTestName);
          }
        }
      }

      // Ensure fixture cleanup tests always run after their setup tests, even
      // if no other test cases require the fixture
      cIt = setupFixturesAdded.find(fixture);
      if (cIt != setupFixturesAdded.end()) {
        const std::vector<size_t>& indices = cIt->second;
        for (size_t index : indices) {
          const std::string& setupTestName = tests[index].Name;
          if (!cm::contains(p.Depends, setupTestName)) {
            p.Depends.push_back(setupTestName);
          }
        }
      }
    }
  }

  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                     "Added " << fixtureTestsAdded
                              << " tests to meet fixture requirements"
                              << std::endl,
                     this->Quiet);
}

void cmCTestTestHandler::UpdateMaxTestNameWidth()
{
  std::string::size_type max = this->CTest->GetMaxTestNameWidth();
  for (cmCTestTestProperties& p : this->TestList) {
    if (max < p.Name.size()) {
      max = p.Name.size();
    }
  }
  if (static_cast<std::string::size_type>(
        this->CTest->GetMaxTestNameWidth()) != max) {
    this->CTest->SetMaxTestNameWidth(static_cast<int>(max));
  }
}

bool cmCTestTestHandler::GetValue(const char* tag, int& value,
                                  std::istream& fin)
{
  std::string line;
  bool ret = true;
  cmSystemTools::GetLineFromStream(fin, line);
  if (line == tag) {
    fin >> value;
    ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  } else {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "parse error: missing tag: " << tag << " found [" << line << "]"
                                            << std::endl);
    ret = false;
  }
  return ret;
}

bool cmCTestTestHandler::GetValue(const char* tag, double& value,
                                  std::istream& fin)
{
  std::string line;
  cmSystemTools::GetLineFromStream(fin, line);
  bool ret = true;
  if (line == tag) {
    fin >> value;
    ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  } else {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "parse error: missing tag: " << tag << " found [" << line << "]"
                                            << std::endl);
    ret = false;
  }
  return ret;
}

bool cmCTestTestHandler::GetValue(const char* tag, bool& value,
                                  std::istream& fin)
{
  std::string line;
  cmSystemTools::GetLineFromStream(fin, line);
  bool ret = true;
  if (line == tag) {
#ifdef __HAIKU__
    int tmp = 0;
    fin >> tmp;
    value = false;
    if (tmp) {
      value = true;
    }
#else
    fin >> value;
#endif
    ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  } else {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "parse error: missing tag: " << tag << " found [" << line << "]"
                                            << std::endl);
    ret = false;
  }
  return ret;
}

bool cmCTestTestHandler::GetValue(const char* tag, size_t& value,
                                  std::istream& fin)
{
  std::string line;
  cmSystemTools::GetLineFromStream(fin, line);
  bool ret = true;
  if (line == tag) {
    fin >> value;
    ret = cmSystemTools::GetLineFromStream(fin, line); // read blank line
  } else {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "parse error: missing tag: " << tag << " found [" << line << "]"
                                            << std::endl);
    ret = false;
  }
  return ret;
}

bool cmCTestTestHandler::GetValue(const char* tag, std::string& value,
                                  std::istream& fin)
{
  std::string line;
  cmSystemTools::GetLineFromStream(fin, line);
  bool ret = true;
  if (line == tag) {
    ret = cmSystemTools::GetLineFromStream(fin, value);
  } else {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "parse error: missing tag: " << tag << " found [" << line << "]"
                                            << std::endl);
    ret = false;
  }
  return ret;
}

bool cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
                                          std::vector<std::string>& failed)
{
  if (!this->ComputeTestList()) {
    return false;
  }

  this->StartTest = this->CTest->CurrentTime();
  this->StartTestTime = std::chrono::system_clock::now();
  auto elapsed_time_start = std::chrono::steady_clock::now();

  auto parallel = cm::make_unique<cmCTestMultiProcessHandler>();
  parallel->SetCTest(this->CTest);
  parallel->SetParallelLevel(this->CTest->GetParallelLevel());
  parallel->SetTestHandler(this);
  if (this->RepeatMode != cmCTest::Repeat::Never) {
    parallel->SetRepeatMode(this->RepeatMode, this->RepeatCount);
  } else {
    parallel->SetRepeatMode(this->CTest->GetRepeatMode(),
                            this->CTest->GetRepeatCount());
  }
  parallel->SetQuiet(this->Quiet);
  if (this->TestLoad > 0) {
    parallel->SetTestLoad(this->TestLoad);
  } else {
    parallel->SetTestLoad(this->CTest->GetTestLoad());
  }
  if (!this->ResourceSpecFile.empty()) {
    this->UseResourceSpec = true;
    auto result = this->ResourceSpec.ReadFromJSONFile(this->ResourceSpecFile);
    if (result != cmCTestResourceSpec::ReadFileResult::READ_OK) {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 "Could not read/parse resource spec file "
                   << this->ResourceSpecFile << ": "
                   << cmCTestResourceSpec::ResultToString(result)
                   << std::endl);
      return false;
    }
    parallel->InitResourceAllocator(this->ResourceSpec);
  }

  *this->LogFile
    << "Start testing: " << this->CTest->CurrentTime() << std::endl
    << "----------------------------------------------------------"
    << std::endl;

  cmCTestMultiProcessHandler::TestMap tests;
  cmCTestMultiProcessHandler::PropertiesMap properties;

  bool randomSchedule = this->CTest->GetScheduleType() == "Random";
  if (randomSchedule) {
    srand(static_cast<unsigned>(time(nullptr)));
  }

  for (cmCTestTestProperties& p : this->TestList) {
    cmCTestMultiProcessHandler::TestSet depends;

    if (randomSchedule) {
      p.Cost = static_cast<float>(rand());
    }

    if (p.Timeout == cmDuration::zero() &&
        this->CTest->GetGlobalTimeout() != cmDuration::zero()) {
      p.Timeout = this->CTest->GetGlobalTimeout();
    }

    if (!p.Depends.empty()) {
      for (std::string const& i : p.Depends) {
        for (cmCTestTestProperties const& it2 : this->TestList) {
          if (it2.Name == i) {
            depends.insert(it2.Index);
            break; // break out of test loop as name can only match 1
          }
        }
      }
    }
    tests[p.Index] = depends;
    properties[p.Index] = &p;
  }
  parallel->SetTests(tests, properties);
  parallel->SetPassFailVectors(&passed, &failed);
  this->TestResults.clear();
  parallel->SetTestResults(&this->TestResults);
  parallel->CheckResourcesAvailable();

  if (this->CTest->ShouldPrintLabels()) {
    parallel->PrintLabels();
  } else if (this->CTest->GetShowOnly()) {
    parallel->PrintTestList();
  } else {
    parallel->RunTests();
  }
  this->EndTest = this->CTest->CurrentTime();
  this->EndTestTime = std::chrono::system_clock::now();
  this->ElapsedTestingTime =
    std::chrono::steady_clock::now() - elapsed_time_start;
  *this->LogFile << "End testing: " << this->CTest->CurrentTime() << std::endl;

  return true;
}

void cmCTestTestHandler::GenerateTestCommand(
  std::vector<std::string>& /*unused*/, int /*unused*/)
{
}

void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml)
{
  if (!this->CTest->GetProduceXML()) {
    return;
  }

  this->CTest->StartXML(xml, this->AppendXML);
  this->CTest->GenerateSubprojectsOutput(xml);
  xml.StartElement("Testing");
  xml.Element("StartDateTime", this->StartTest);
  xml.Element("StartTestTime", this->StartTestTime);
  xml.StartElement("TestList");
  for (cmCTestTestResult const& result : this->TestResults) {
    std::string testPath = result.Path + "/" + result.Name;
    xml.Element("Test", this->CTest->GetShortPathToFile(testPath));
  }
  xml.EndElement(); // TestList
  for (cmCTestTestResult& result : this->TestResults) {
    this->WriteTestResultHeader(xml, result);
    xml.StartElement("Results");

    if (result.Status != cmCTestTestHandler::NOT_RUN) {
      if (result.Status != cmCTestTestHandler::COMPLETED ||
          result.ReturnValue) {
        xml.StartElement("NamedMeasurement");
        xml.Attribute("type", "text/string");
        xml.Attribute("name", "Exit Code");
        xml.Element("Value", this->GetTestStatus(result));
        xml.EndElement(); // NamedMeasurement

        xml.StartElement("NamedMeasurement");
        xml.Attribute("type", "text/string");
        xml.Attribute("name", "Exit Value");
        xml.Element("Value", result.ReturnValue);
        xml.EndElement(); // NamedMeasurement
      }
      this->GenerateRegressionImages(xml, result.DartString);
      xml.StartElement("NamedMeasurement");
      xml.Attribute("type", "numeric/double");
      xml.Attribute("name", "Execution Time");
      xml.Element("Value", result.ExecutionTime.count());
      xml.EndElement(); // NamedMeasurement
      if (!result.Reason.empty()) {
        const char* reasonType = "Pass Reason";
        if (result.Status != cmCTestTestHandler::COMPLETED) {
          reasonType = "Fail Reason";
        }
        xml.StartElement("NamedMeasurement");
        xml.Attribute("type", "text/string");
        xml.Attribute("name", reasonType);
        xml.Element("Value", result.Reason);
        xml.EndElement(); // NamedMeasurement
      }
    }

    xml.StartElement("NamedMeasurement");
    xml.Attribute("type", "numeric/double");
    xml.Attribute("name", "Processors");
    xml.Element("Value", result.Properties->Processors);
    xml.EndElement(); // NamedMeasurement

    xml.StartElement("NamedMeasurement");
    xml.Attribute("type", "text/string");
    xml.Attribute("name", "Completion Status");
    xml.Element("Value", result.CompletionStatus);
    xml.EndElement(); // NamedMeasurement

    xml.StartElement("NamedMeasurement");
    xml.Attribute("type", "text/string");
    xml.Attribute("name", "Command Line");
    xml.Element("Value", result.FullCommandLine);
    xml.EndElement(); // NamedMeasurement

    xml.StartElement("NamedMeasurement");
    xml.Attribute("type", "text/string");
    xml.Attribute("name", "Environment");
    xml.Element("Value", result.Environment);
    xml.EndElement(); // NamedMeasurement
    for (auto const& measure : result.Properties->Measurements) {
      xml.StartElement("NamedMeasurement");
      xml.Attribute("type", "text/string");
      xml.Attribute("name", measure.first);
      xml.Element("Value", measure.second);
      xml.EndElement(); // NamedMeasurement
    }
    xml.StartElement("Measurement");
    xml.StartElement("Value");
    if (result.CompressOutput) {
      xml.Attribute("encoding", "base64");
      xml.Attribute("compression", "gzip");
    }
    xml.Content(result.Output);
    xml.EndElement(); // Value
    xml.EndElement(); // Measurement
    xml.EndElement(); // Results

    this->AttachFiles(xml, result);
    this->WriteTestResultFooter(xml, result);
  }

  xml.Element("EndDateTime", this->EndTest);
  xml.Element("EndTestTime", this->EndTestTime);
  xml.Element(
    "ElapsedMinutes",
    std::chrono::duration_cast<std::chrono::minutes>(this->ElapsedTestingTime)
      .count());
  xml.EndElement(); // Testing
  this->CTest->EndXML(xml);
}

void cmCTestTestHandler::WriteTestResultHeader(cmXMLWriter& xml,
                                               cmCTestTestResult const& result)
{
  xml.StartElement("Test");
  if (result.Status == cmCTestTestHandler::COMPLETED) {
    xml.Attribute("Status", "passed");
  } else if (result.Status == cmCTestTestHandler::NOT_RUN) {
    xml.Attribute("Status", "notrun");
  } else {
    xml.Attribute("Status", "failed");
  }
  std::string testPath = result.Path + "/" + result.Name;
  xml.Element("Name", result.Name);
  xml.Element("Path", this->CTest->GetShortPathToFile(result.Path));
  xml.Element("FullName", this->CTest->GetShortPathToFile(testPath));
  xml.Element("FullCommandLine", result.FullCommandLine);
}

void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml,
                                               cmCTestTestResult const& result)
{
  if (!result.Properties->Labels.empty()) {
    xml.StartElement("Labels");
    std::vector<std::string> const& labels = result.Properties->Labels;
    for (std::string const& label : labels) {
      xml.Element("Label", label);
    }
    xml.EndElement(); // Labels
  }

  xml.EndElement(); // Test
}

void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml,
                                     cmCTestTestResult& result)
{
  if (result.Status != cmCTestTestHandler::COMPLETED &&
      !result.Properties->AttachOnFail.empty()) {
    result.Properties->AttachedFiles.insert(
      result.Properties->AttachedFiles.end(),
      result.Properties->AttachOnFail.begin(),
      result.Properties->AttachOnFail.end());
  }
  for (std::string const& file : result.Properties->AttachedFiles) {
    const std::string& base64 = this->CTest->Base64GzipEncodeFile(file);
    std::string const fname = cmSystemTools::GetFilenameName(file);
    xml.StartElement("NamedMeasurement");
    xml.Attribute("name", "Attached File");
    xml.Attribute("encoding", "base64");
    xml.Attribute("compression", "tar/gzip");
    xml.Attribute("filename", fname);
    xml.Attribute("type", "file");
    xml.Element("Value", base64);
    xml.EndElement(); // NamedMeasurement
  }
}

int cmCTestTestHandler::ExecuteCommands(std::vector<std::string>& vec)
{
  for (std::string const& it : vec) {
    int retVal = 0;
    cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                       "Run command: " << it << std::endl, this->Quiet);
    if (!cmSystemTools::RunSingleCommand(it, nullptr, nullptr, &retVal,
                                         nullptr, cmSystemTools::OUTPUT_MERGE
                                         /*this->Verbose*/) ||
        retVal != 0) {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 "Problem running command: " << it << std::endl);
      return 0;
    }
  }
  return 1;
}

// Find the appropriate executable to run for a test
std::string cmCTestTestHandler::FindTheExecutable(const std::string& exe)
{
  std::string resConfig;
  std::vector<std::string> extraPaths;
  std::vector<std::string> failedPaths;
  if (exe == "NOT_AVAILABLE") {
    return exe;
  }
  return cmCTestTestHandler::FindExecutable(this->CTest, exe, resConfig,
                                            extraPaths, failedPaths);
}

// add additional configurations to the search path
void cmCTestTestHandler::AddConfigurations(
  cmCTest* ctest, std::vector<std::string>& attempted,
  std::vector<std::string>& attemptedConfigs, std::string filepath,
  std::string& filename)
{
  std::string tempPath;

  if (!filepath.empty() && filepath[filepath.size() - 1] != '/') {
    filepath += "/";
  }
  tempPath = filepath + filename;
  attempted.push_back(tempPath);
  attemptedConfigs.emplace_back();

  if (!ctest->GetConfigType().empty()) {
    tempPath = cmStrCat(filepath, ctest->GetConfigType(), '/', filename);
    attempted.push_back(tempPath);
    attemptedConfigs.push_back(ctest->GetConfigType());
    // If the file is an OSX bundle then the configtype
    // will be at the start of the path
    tempPath = cmStrCat(ctest->GetConfigType(), '/', filepath, filename);
    attempted.push_back(tempPath);
    attemptedConfigs.push_back(ctest->GetConfigType());
  } else {
    // no config specified - try some options...
    tempPath = cmStrCat(filepath, "Release/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("Release");
    tempPath = cmStrCat(filepath, "Debug/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("Debug");
    tempPath = cmStrCat(filepath, "MinSizeRel/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("MinSizeRel");
    tempPath = cmStrCat(filepath, "RelWithDebInfo/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("RelWithDebInfo");
    tempPath = cmStrCat(filepath, "Deployment/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("Deployment");
    tempPath = cmStrCat(filepath, "Development/", filename);
    attempted.push_back(tempPath);
    attemptedConfigs.emplace_back("Deployment");
  }
}

// Find the appropriate executable to run for a test
std::string cmCTestTestHandler::FindExecutable(
  cmCTest* ctest, const std::string& testCommand, std::string& resultingConfig,
  std::vector<std::string>& extraPaths, std::vector<std::string>& failed)
{
  // now run the compiled test if we can find it
  std::vector<std::string> attempted;
  std::vector<std::string> attemptedConfigs;
  std::string tempPath;
  std::string filepath = cmSystemTools::GetFilenamePath(testCommand);
  std::string filename = cmSystemTools::GetFilenameName(testCommand);

  cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
                                        filepath, filename);

  // even if a fullpath was specified also try it relative to the current
  // directory
  if (!filepath.empty() && filepath[0] == '/') {
    std::string localfilepath = filepath.substr(1, filepath.size() - 1);
    cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
                                          localfilepath, filename);
  }

  // if extraPaths are provided and we were not passed a full path, try them,
  // try any extra paths
  if (filepath.empty()) {
    for (std::string const& extraPath : extraPaths) {
      std::string filepathExtra = cmSystemTools::GetFilenamePath(extraPath);
      std::string filenameExtra = cmSystemTools::GetFilenameName(extraPath);
      cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
                                            filepathExtra, filenameExtra);
    }
  }

  // store the final location in fullPath
  std::string fullPath;

  // now look in the paths we specified above
  for (unsigned int ai = 0; ai < attempted.size() && fullPath.empty(); ++ai) {
    // first check without exe extension
    if (cmSystemTools::FileExists(attempted[ai]) &&
        !cmSystemTools::FileIsDirectory(attempted[ai])) {
      fullPath = cmSystemTools::CollapseFullPath(attempted[ai]);
      resultingConfig = attemptedConfigs[ai];
    }
    // then try with the exe extension
    else {
      failed.push_back(attempted[ai]);
      tempPath =
        cmStrCat(attempted[ai], cmSystemTools::GetExecutableExtension());
      if (cmSystemTools::FileExists(tempPath) &&
          !cmSystemTools::FileIsDirectory(tempPath)) {
        fullPath = cmSystemTools::CollapseFullPath(tempPath);
        resultingConfig = attemptedConfigs[ai];
      } else {
        failed.push_back(tempPath);
      }
    }
  }

  // if everything else failed, check the users path, but only if a full path
  // wasn't specified
  if (fullPath.empty() && filepath.empty()) {
    std::string path = cmSystemTools::FindProgram(filename.c_str());
    if (!path.empty()) {
      resultingConfig.clear();
      return path;
    }
  }
  if (fullPath.empty()) {
    cmCTestLog(ctest, HANDLER_OUTPUT,
               "Could not find executable "
                 << testCommand << "\n"
                 << "Looked in the following places:\n");
    for (std::string const& f : failed) {
      cmCTestLog(ctest, HANDLER_OUTPUT, f << "\n");
    }
  }

  return fullPath;
}

bool cmCTestTestHandler::ParseResourceGroupsProperty(
  const std::string& val,
  std::vector<std::vector<cmCTestTestResourceRequirement>>& resourceGroups)
{
  cmCTestResourceGroupsLexerHelper lexer(resourceGroups);
  return lexer.ParseString(val);
}

bool cmCTestTestHandler::GetListOfTests()
{
  if (!this->IncludeLabelRegExp.empty()) {
    this->IncludeLabelRegularExpression.compile(
      this->IncludeLabelRegExp.c_str());
  }
  if (!this->ExcludeLabelRegExp.empty()) {
    this->ExcludeLabelRegularExpression.compile(
      this->ExcludeLabelRegExp.c_str());
  }
  if (!this->IncludeRegExp.empty()) {
    this->IncludeTestsRegularExpression.compile(this->IncludeRegExp.c_str());
  }
  if (!this->ExcludeRegExp.empty()) {
    this->ExcludeTestsRegularExpression.compile(this->ExcludeRegExp.c_str());
  }
  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                     "Constructing a list of tests" << std::endl, this->Quiet);
  cmake cm(cmake::RoleScript, cmState::CTest);
  cm.SetHomeDirectory("");
  cm.SetHomeOutputDirectory("");
  cm.GetCurrentSnapshot().SetDefaultDefinitions();
  cmGlobalGenerator gg(&cm);
  cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  mf.AddDefinition("CTEST_CONFIGURATION_TYPE", this->CTest->GetConfigType());

  // Add handler for ADD_TEST
  cm.GetState()->AddBuiltinCommand("add_test", cmCTestAddTestCommand(this));

  // Add handler for SUBDIRS
  cm.GetState()->AddBuiltinCommand("subdirs", cmCTestSubdirCommand);

  // Add handler for ADD_SUBDIRECTORY
  cm.GetState()->AddBuiltinCommand("add_subdirectory",
                                   cmCTestAddSubdirectoryCommand);

  // Add handler for SET_TESTS_PROPERTIES
  cm.GetState()->AddBuiltinCommand("set_tests_properties",
                                   cmCTestSetTestsPropertiesCommand(this));

  // Add handler for SET_DIRECTORY_PROPERTIES
  cm.GetState()->RemoveBuiltinCommand("set_directory_properties");
  cm.GetState()->AddBuiltinCommand("set_directory_properties",
                                   cmCTestSetDirectoryPropertiesCommand(this));

  const char* testFilename;
  if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
    // does the CTestTestfile.cmake exist ?
    testFilename = "CTestTestfile.cmake";
  } else if (cmSystemTools::FileExists("DartTestfile.txt")) {
    // does the DartTestfile.txt exist ?
    testFilename = "DartTestfile.txt";
  } else {
    return true;
  }

  if (!mf.ReadListFile(testFilename)) {
    return false;
  }
  if (cmSystemTools::GetErrorOccuredFlag()) {
    // SEND_ERROR or FATAL_ERROR in CTestTestfile or TEST_INCLUDE_FILES
    return false;
  }
  cmProp specFile = mf.GetDefinition("CTEST_RESOURCE_SPEC_FILE");
  if (this->ResourceSpecFile.empty() && specFile) {
    this->ResourceSpecFile = *specFile;
  }
  cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                     "Done constructing a list of tests" << std::endl,
                     this->Quiet);
  return true;
}

void cmCTestTestHandler::UseIncludeRegExp()
{
  this->UseIncludeRegExpFlag = true;
}

void cmCTestTestHandler::UseExcludeRegExp()
{
  this->UseExcludeRegExpFlag = true;
  this->UseExcludeRegExpFirst = !this->UseIncludeRegExpFlag;
}

std::string cmCTestTestHandler::GetTestStatus(cmCTestTestResult const& result)
{
  static const char* statuses[] = { "Not Run",     "Timeout",   "SEGFAULT",
                                    "ILLEGAL",     "INTERRUPT", "NUMERICAL",
                                    "OTHER_FAULT", "Failed",    "BAD_COMMAND",
                                    "Completed" };
  int status = result.Status;
  if (status < cmCTestTestHandler::NOT_RUN ||
      status > cmCTestTestHandler::COMPLETED) {
    return "No Status";
  }
  if (status == cmCTestTestHandler::OTHER_FAULT) {
    return result.ExceptionStatus;
  }
  return statuses[status];
}

void cmCTestTestHandler::ExpandTestsToRunInformation(size_t numTests)
{
  if (this->TestsToRunString.empty()) {
    return;
  }

  int start;
  int end = -1;
  double stride = -1;
  std::string::size_type pos = 0;
  std::string::size_type pos2;
  // read start
  if (GetNextNumber(this->TestsToRunString, start, pos, pos2)) {
    // read end
    if (GetNextNumber(this->TestsToRunString, end, pos, pos2)) {
      // read stride
      if (GetNextRealNumber(this->TestsToRunString, stride, pos, pos2)) {
        int val = 0;
        // now read specific numbers
        while (GetNextNumber(this->TestsToRunString, val, pos, pos2)) {
          this->TestsToRun.push_back(val);
        }
        this->TestsToRun.push_back(val);
      }
    }
  }

  // if start is not specified then we assume we start at 1
  if (start == -1) {
    start = 1;
  }

  // if end isnot specified then we assume we end with the last test
  if (end == -1) {
    end = static_cast<int>(numTests);
  }

  // if the stride wasn't specified then it defaults to 1
  if (stride == -1) {
    stride = 1;
  }

  // if we have a range then add it
  if (end != -1 && start != -1 && stride > 0) {
    int i = 0;
    while (i * stride + start <= end) {
      this->TestsToRun.push_back(static_cast<int>(i * stride + start));
      ++i;
    }
  }

  // sort the array
  std::sort(this->TestsToRun.begin(), this->TestsToRun.end(),
            std::less<int>());
  // remove duplicates
  auto new_end = std::unique(this->TestsToRun.begin(), this->TestsToRun.end());
  this->TestsToRun.erase(new_end, this->TestsToRun.end());
}

void cmCTestTestHandler::ExpandTestsToRunInformationForRerunFailed()
{

  std::string dirName = this->CTest->GetBinaryDir() + "/Testing/Temporary";

  cmsys::Directory directory;
  if (directory.Load(dirName) == 0) {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "Unable to read the contents of " << dirName << std::endl);
    return;
  }

  int numFiles =
    static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  std::string pattern = "LastTestsFailed";
  std::string logName;

  for (int i = 0; i < numFiles; ++i) {
    std::string fileName = directory.GetFile(i);
    // bcc crashes if we attempt a normal substring comparison,
    // hence the following workaround
    std::string fileNameSubstring = fileName.substr(0, pattern.length());
    if (fileNameSubstring != pattern) {
      continue;
    }
    if (logName.empty()) {
      logName = fileName;
    } else {
      // if multiple matching logs were found we use the most recently
      // modified one.
      int res;
      cmSystemTools::FileTimeCompare(logName, fileName, &res);
      if (res == -1) {
        logName = fileName;
      }
    }
  }

  std::string lastTestsFailedLog =
    this->CTest->GetBinaryDir() + "/Testing/Temporary/" + logName;

  if (!cmSystemTools::FileExists(lastTestsFailedLog)) {
    if (!this->CTest->GetShowOnly() && !this->CTest->ShouldPrintLabels()) {
      cmCTestLog(this->CTest, ERROR_MESSAGE,
                 lastTestsFailedLog << " does not exist!" << std::endl);
    }
    return;
  }

  // parse the list of tests to rerun from LastTestsFailed.log
  cmsys::ifstream ifs(lastTestsFailedLog.c_str());
  if (ifs) {
    std::string line;
    std::string::size_type pos;
    while (cmSystemTools::GetLineFromStream(ifs, line)) {
      pos = line.find(':', 0);
      if (pos == std::string::npos) {
        continue;
      }

      line.erase(pos);
      int val = atoi(line.c_str());
      this->TestsToRun.push_back(val);
    }
    ifs.close();
  } else if (!this->CTest->GetShowOnly() &&
             !this->CTest->ShouldPrintLabels()) {
    cmCTestLog(this->CTest, ERROR_MESSAGE,
               "Problem reading file: "
                 << lastTestsFailedLog
                 << " while generating list of previously failed tests."
                 << std::endl);
  }
}

// Just for convenience
#define SPACE_REGEX "[ \t\r\n]"
void cmCTestTestHandler::GenerateRegressionImages(cmXMLWriter& xml,
                                                  const std::string& dart)
{
  cmsys::RegularExpression twoattributes(
    "<DartMeasurement" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*>([^<]*)</DartMeasurement>");
  cmsys::RegularExpression threeattributes(
    "<DartMeasurement" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*>([^<]*)</DartMeasurement>");
  cmsys::RegularExpression fourattributes(
    "<DartMeasurement" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*>([^<]*)</DartMeasurement>");
  cmsys::RegularExpression cdatastart(
    "<DartMeasurement" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*>" SPACE_REGEX "*<!\\[CDATA\\[");
  cmsys::RegularExpression cdataend("]]>" SPACE_REGEX "*</DartMeasurement>");
  cmsys::RegularExpression measurementfile(
    "<DartMeasurementFile" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*(name|type|encoding|compression)=\"([^\"]*)\"" SPACE_REGEX
    "*>([^<]*)</DartMeasurementFile>");

  bool done = false;
  std::string cxml = dart;
  while (!done) {
    if (twoattributes.find(cxml)) {
      xml.StartElement("NamedMeasurement");
      xml.Attribute(twoattributes.match(1).c_str(), twoattributes.match(2));
      xml.Attribute(twoattributes.match(3).c_str(), twoattributes.match(4));
      xml.Element("Value", twoattributes.match(5));
      xml.EndElement();
      cxml.erase(twoattributes.start(),
                 twoattributes.end() - twoattributes.start());
    } else if (threeattributes.find(cxml)) {
      xml.StartElement("NamedMeasurement");
      xml.Attribute(threeattributes.match(1).c_str(),
                    threeattributes.match(2));
      xml.Attribute(threeattributes.match(3).c_str(),
                    threeattributes.match(4));
      xml.Attribute(threeattributes.match(5).c_str(),
                    threeattributes.match(6));
      xml.Element("Value", twoattributes.match(7));
      xml.EndElement();
      cxml.erase(threeattributes.start(),
                 threeattributes.end() - threeattributes.start());
    } else if (fourattributes.find(cxml)) {
      xml.StartElement("NamedMeasurement");
      xml.Attribute(fourattributes.match(1).c_str(), fourattributes.match(2));
      xml.Attribute(fourattributes.match(3).c_str(), fourattributes.match(4));
      xml.Attribute(fourattributes.match(5).c_str(), fourattributes.match(6));
      xml.Attribute(fourattributes.match(7).c_str(), fourattributes.match(8));
      xml.Element("Value", twoattributes.match(9));
      xml.EndElement();
      cxml.erase(fourattributes.start(),
                 fourattributes.end() - fourattributes.start());
    } else if (cdatastart.find(cxml) && cdataend.find(cxml)) {
      xml.StartElement("NamedMeasurement");
      xml.Attribute(cdatastart.match(1).c_str(), cdatastart.match(2));
      xml.Attribute(cdatastart.match(3).c_str(), cdatastart.match(4));
      xml.StartElement("Value");
      xml.CData(
        cxml.substr(cdatastart.end(), cdataend.start() - cdatastart.end()));
      xml.EndElement(); // Value
      xml.EndElement(); // NamedMeasurement
      cxml.erase(cdatastart.start(), cdataend.end() - cdatastart.start());
    } else if (measurementfile.find(cxml)) {
      const std::string& filename =
        cmCTest::CleanString(measurementfile.match(5));
      if (cmSystemTools::FileExists(filename)) {
        long len = cmSystemTools::FileLength(filename);
        if (len == 0) {
          std::string k1 = measurementfile.match(1);
          std::string v1 = measurementfile.match(2);
          std::string k2 = measurementfile.match(3);
          std::string v2 = measurementfile.match(4);
          if (cmSystemTools::LowerCase(k1) == "type") {
            v1 = "text/string";
          }
          if (cmSystemTools::LowerCase(k2) == "type") {
            v2 = "text/string";
          }

          xml.StartElement("NamedMeasurement");
          xml.Attribute(k1.c_str(), v1);
          xml.Attribute(k2.c_str(), v2);
          xml.Attribute("encoding", "none");
          xml.Element("Value", "Image " + filename + " is empty");
          xml.EndElement();
        } else {
          cmsys::ifstream ifs(filename.c_str(),
                              std::ios::in
#ifdef _WIN32
                                | std::ios::binary
#endif
          );
          auto file_buffer = cm::make_unique<unsigned char[]>(len + 1);
          ifs.read(reinterpret_cast<char*>(file_buffer.get()), len);
          auto encoded_buffer = cm::make_unique<unsigned char[]>(
            static_cast<int>(static_cast<double>(len) * 1.5 + 5.0));

          size_t rlen = cmsysBase64_Encode(file_buffer.get(), len,
                                           encoded_buffer.get(), 1);

          xml.StartElement("NamedMeasurement");
          xml.Attribute(measurementfile.match(1).c_str(),
                        measurementfile.match(2));
          xml.Attribute(measurementfile.match(3).c_str(),
                        measurementfile.match(4));
          xml.Attribute("encoding", "base64");
          std::ostringstream ostr;
          for (size_t cc = 0; cc < rlen; cc++) {
            ostr << encoded_buffer[cc];
            if (cc % 60 == 0 && cc) {
              ostr << std::endl;
            }
          }
          xml.Element("Value", ostr.str());
          xml.EndElement(); // NamedMeasurement
        }
      } else {
        int idx = 4;
        if (measurementfile.match(1) == "name") {
          idx = 2;
        }
        xml.StartElement("NamedMeasurement");
        xml.Attribute("name", measurementfile.match(idx));
        xml.Attribute("text", "text/string");
        xml.Element("Value", "File " + filename + " not found");
        xml.EndElement();
        cmCTestOptionalLog(
          this->CTest, HANDLER_OUTPUT,
          "File \"" << filename << "\" not found." << std::endl, this->Quiet);
      }
      cxml.erase(measurementfile.start(),
                 measurementfile.end() - measurementfile.start());
    } else {
      done = true;
    }
  }
}

void cmCTestTestHandler::SetIncludeRegExp(const char* arg)
{
  this->IncludeRegExp = arg;
}

void cmCTestTestHandler::SetExcludeRegExp(const char* arg)
{
  this->ExcludeRegExp = arg;
}

void cmCTestTestHandler::SetTestsToRunInformation(const char* in)
{
  if (!in) {
    return;
  }
  this->TestsToRunString = in;
  // if the argument is a file, then read it and use the contents as the
  // string
  if (cmSystemTools::FileExists(in)) {
    cmsys::ifstream fin(in);
    unsigned long filelen = cmSystemTools::FileLength(in);
    auto buff = cm::make_unique<char[]>(filelen + 1);
    fin.getline(buff.get(), filelen);
    buff[fin.gcount()] = 0;
    this->TestsToRunString = buff.get();
  }
}

void cmCTestTestHandler::CleanTestOutput(std::string& output, size_t length)
{
  if (!length || length >= output.size() ||
      output.find("CTEST_FULL_OUTPUT") != std::string::npos) {
    return;
  }

  // Truncate at given length but do not break in the middle of a multi-byte
  // UTF-8 encoding.
  char const* const begin = output.c_str();
  char const* const end = begin + output.size();
  char const* const truncate = begin + length;
  char const* current = begin;
  while (current < truncate) {
    unsigned int ch;
    if (const char* next = cm_utf8_decode_character(current, end, &ch)) {
      if (next > truncate) {
        break;
      }
      current = next;
    } else // Bad byte will be handled by cmXMLWriter.
    {
      ++current;
    }
  }
  output.erase(current - begin);

  // Append truncation message.
  std::ostringstream msg;
  msg << "...\n"
         "The rest of the test output was removed since it exceeds the "
         "threshold "
         "of "
      << length << " bytes.\n";
  output += msg.str();
}

bool cmCTestTestHandler::SetTestsProperties(
  const std::vector<std::string>& args)
{
  std::vector<std::string>::const_iterator it;
  std::vector<std::string> tests;
  bool found = false;
  for (it = args.begin(); it != args.end(); ++it) {
    if (*it == "PROPERTIES") {
      found = true;
      break;
    }
    tests.push_back(*it);
  }
  if (!found) {
    return false;
  }
  ++it; // skip PROPERTIES
  for (; it != args.end(); ++it) {
    std::string const& key = *it;
    ++it;
    if (it == args.end()) {
      break;
    }
    std::string const& val = *it;
    for (std::string const& t : tests) {
      for (cmCTestTestProperties& rt : this->TestList) {
        if (t == rt.Name) {
          if (key == "_BACKTRACE_TRIPLES"_s) {
            std::vector<std::string> triples;
            // allow empty args in the triples
            cmExpandList(val, triples, true);

            // Ensure we have complete triples otherwise the data is corrupt.
            if (triples.size() % 3 == 0) {
              cmState state;
              rt.Backtrace = cmListFileBacktrace(state.CreateBaseSnapshot());

              // the first entry represents the top of the trace so we need to
              // reconstruct the backtrace in reverse
              for (size_t i = triples.size(); i >= 3; i -= 3) {
                cmListFileContext fc;
                fc.FilePath = triples[i - 3];
                long line = 0;
                if (!cmStrToLong(triples[i - 2], &line)) {
                  line = 0;
                }
                fc.Line = line;
                fc.Name = triples[i - 1];
                rt.Backtrace = rt.Backtrace.Push(fc);
              }
            }
          } else if (key == "WILL_FAIL"_s) {
            rt.WillFail = cmIsOn(val);
          } else if (key == "DISABLED"_s) {
            rt.Disabled = cmIsOn(val);
          } else if (key == "ATTACHED_FILES"_s) {
            cmExpandList(val, rt.AttachedFiles);
          } else if (key == "ATTACHED_FILES_ON_FAIL"_s) {
            cmExpandList(val, rt.AttachOnFail);
          } else if (key == "RESOURCE_LOCK"_s) {
            std::vector<std::string> lval = cmExpandedList(val);

            rt.LockedResources.insert(lval.begin(), lval.end());
          } else if (key == "FIXTURES_SETUP"_s) {
            std::vector<std::string> lval = cmExpandedList(val);

            rt.FixturesSetup.insert(lval.begin(), lval.end());
          } else if (key == "FIXTURES_CLEANUP"_s) {
            std::vector<std::string> lval = cmExpandedList(val);

            rt.FixturesCleanup.insert(lval.begin(), lval.end());
          } else if (key == "FIXTURES_REQUIRED"_s) {
            std::vector<std::string> lval = cmExpandedList(val);

            rt.FixturesRequired.insert(lval.begin(), lval.end());
          } else if (key == "TIMEOUT"_s) {
            rt.Timeout = cmDuration(atof(val.c_str()));
            rt.ExplicitTimeout = true;
          } else if (key == "COST"_s) {
            rt.Cost = static_cast<float>(atof(val.c_str()));
          } else if (key == "REQUIRED_FILES"_s) {
            cmExpandList(val, rt.RequiredFiles);
          } else if (key == "RUN_SERIAL"_s) {
            rt.RunSerial = cmIsOn(val);
          } else if (key == "FAIL_REGULAR_EXPRESSION"_s) {
            std::vector<std::string> lval = cmExpandedList(val);
            for (std::string const& cr : lval) {
              rt.ErrorRegularExpressions.emplace_back(cr, cr);
            }
          } else if (key == "SKIP_REGULAR_EXPRESSION"_s) {
            std::vector<std::string> lval = cmExpandedList(val);
            for (std::string const& cr : lval) {
              rt.SkipRegularExpressions.emplace_back(cr, cr);
            }
          } else if (key == "PROCESSORS"_s) {
            rt.Processors = atoi(val.c_str());
            if (rt.Processors < 1) {
              rt.Processors = 1;
            }
          } else if (key == "PROCESSOR_AFFINITY"_s) {
            rt.WantAffinity = cmIsOn(val);
          } else if (key == "RESOURCE_GROUPS"_s) {
            if (!ParseResourceGroupsProperty(val, rt.ResourceGroups)) {
              return false;
            }
          } else if (key == "SKIP_RETURN_CODE"_s) {
            rt.SkipReturnCode = atoi(val.c_str());
            if (rt.SkipReturnCode < 0 || rt.SkipReturnCode > 255) {
              rt.SkipReturnCode = -1;
            }
          } else if (key == "DEPENDS"_s) {
            cmExpandList(val, rt.Depends);
          } else if (key == "ENVIRONMENT"_s) {
            cmExpandList(val, rt.Environment);
          } else if (key == "LABELS"_s) {
            std::vector<std::string> Labels = cmExpandedList(val);
            rt.Labels.insert(rt.Labels.end(), Labels.begin(), Labels.end());
            // sort the array
            std::sort(rt.Labels.begin(), rt.Labels.end());
            // remove duplicates
            auto new_end = std::unique(rt.Labels.begin(), rt.Labels.end());
            rt.Labels.erase(new_end, rt.Labels.end());
          } else if (key == "MEASUREMENT"_s) {
            size_t pos = val.find_first_of('=');
            if (pos != std::string::npos) {
              std::string mKey = val.substr(0, pos);
              std::string mVal = val.substr(pos + 1);
              rt.Measurements[mKey] = std::move(mVal);
            } else {
              rt.Measurements[val] = "1";
            }
          } else if (key == "PASS_REGULAR_EXPRESSION"_s) {
            std::vector<std::string> lval = cmExpandedList(val);
            for (std::string const& cr : lval) {
              rt.RequiredRegularExpressions.emplace_back(cr, cr);
            }
          } else if (key == "WORKING_DIRECTORY"_s) {
            rt.Directory = val;
          } else if (key == "TIMEOUT_AFTER_MATCH"_s) {
            std::vector<std::string> propArgs = cmExpandedList(val);
            if (propArgs.size() != 2) {
              cmCTestLog(this->CTest, WARNING,
                         "TIMEOUT_AFTER_MATCH expects two arguments, found "
                           << propArgs.size() << std::endl);
            } else {
              rt.AlternateTimeout = cmDuration(atof(propArgs[0].c_str()));
              std::vector<std::string> lval = cmExpandedList(propArgs[1]);
              for (std::string const& cr : lval) {
                rt.TimeoutRegularExpressions.emplace_back(cr, cr);
              }
            }
          }
        }
      }
    }
  }
  return true;
}

bool cmCTestTestHandler::SetDirectoryProperties(
  const std::vector<std::string>& args)
{
  std::vector<std::string>::const_iterator it;
  std::vector<std::string> tests;
  bool found = false;
  for (it = args.begin(); it != args.end(); ++it) {
    if (*it == "PROPERTIES") {
      found = true;
      break;
    }
    tests.push_back(*it);
  }

  if (!found) {
    return false;
  }
  ++it; // skip PROPERTIES
  for (; it != args.end(); ++it) {
    std::string const& key = *it;
    ++it;
    if (it == args.end()) {
      break;
    }
    std::string const& val = *it;
    for (cmCTestTestProperties& rt : this->TestList) {
      std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
      if (cwd == rt.Directory) {
        if (key == "LABELS"_s) {
          std::vector<std::string> DirectoryLabels = cmExpandedList(val);
          rt.Labels.insert(rt.Labels.end(), DirectoryLabels.begin(),
                           DirectoryLabels.end());

          // sort the array
          std::sort(rt.Labels.begin(), rt.Labels.end());
          // remove duplicates
          auto new_end = std::unique(rt.Labels.begin(), rt.Labels.end());
          rt.Labels.erase(new_end, rt.Labels.end());
        }
      }
    }
  }
  return true;
}

bool cmCTestTestHandler::AddTest(const std::vector<std::string>& args)
{
  const std::string& testname = args[0];
  cmCTestOptionalLog(this->CTest, DEBUG, "Add test: " << args[0] << std::endl,
                     this->Quiet);

  if (this->UseExcludeRegExpFlag && this->UseExcludeRegExpFirst &&
      this->ExcludeTestsRegularExpression.find(testname)) {
    return true;
  }
  if (this->MemCheck) {
    std::vector<std::string>::iterator it;
    bool found = false;
    for (it = this->CustomTestsIgnore.begin();
         it != this->CustomTestsIgnore.end(); ++it) {
      if (*it == testname) {
        found = true;
        break;
      }
    }
    if (found) {
      cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                         "Ignore memcheck: " << *it << std::endl, this->Quiet);
      return true;
    }
  } else {
    std::vector<std::string>::iterator it;
    bool found = false;
    for (it = this->CustomTestsIgnore.begin();
         it != this->CustomTestsIgnore.end(); ++it) {
      if (*it == testname) {
        found = true;
        break;
      }
    }
    if (found) {
      cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                         "Ignore test: " << *it << std::endl, this->Quiet);
      return true;
    }
  }

  cmCTestTestProperties test;
  test.Name = testname;
  test.Args = args;
  test.Directory = cmSystemTools::GetCurrentWorkingDirectory();
  cmCTestOptionalLog(this->CTest, DEBUG,
                     "Set test directory: " << test.Directory << std::endl,
                     this->Quiet);

  test.IsInBasedOnREOptions = true;
  test.WillFail = false;
  test.Disabled = false;
  test.RunSerial = false;
  test.Timeout = cmDuration::zero();
  test.ExplicitTimeout = false;
  test.Cost = 0;
  test.Processors = 1;
  test.WantAffinity = false;
  test.SkipReturnCode = -1;
  test.PreviousRuns = 0;
  if (this->UseIncludeRegExpFlag &&
      (!this->IncludeTestsRegularExpression.find(testname) ||
       (!this->UseExcludeRegExpFirst &&
        this->ExcludeTestsRegularExpression.find(testname)))) {
    test.IsInBasedOnREOptions = false;
  }
  this->TestList.push_back(test);
  return true;
}

bool cmCTestTestHandler::cmCTestTestResourceRequirement::operator==(
  const cmCTestTestResourceRequirement& other) const
{
  return this->ResourceType == other.ResourceType &&
    this->SlotsNeeded == other.SlotsNeeded &&
    this->UnitsNeeded == other.UnitsNeeded;
}

bool cmCTestTestHandler::cmCTestTestResourceRequirement::operator!=(
  const cmCTestTestResourceRequirement& other) const
{
  return !(*this == other);
}