cmCTestBuildAndTestHandler.cxx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTestBuildAndTestHandler.h"
  4. #include <chrono>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <ratio>
  8. #include "cmsys/Process.h"
  9. #include "cmBuildOptions.h"
  10. #include "cmCTest.h"
  11. #include "cmCTestTestHandler.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmState.h"
  15. #include "cmStringAlgorithms.h"
  16. #include "cmSystemTools.h"
  17. #include "cmWorkingDirectory.h"
  18. #include "cmake.h"
  19. struct cmMessageMetadata;
  20. cmCTestBuildAndTestHandler::cmCTestBuildAndTestHandler()
  21. {
  22. this->BuildTwoConfig = false;
  23. this->BuildNoClean = false;
  24. this->BuildNoCMake = false;
  25. this->Timeout = cmDuration::zero();
  26. }
  27. void cmCTestBuildAndTestHandler::Initialize()
  28. {
  29. this->BuildTargets.clear();
  30. this->Superclass::Initialize();
  31. }
  32. const char* cmCTestBuildAndTestHandler::GetOutput()
  33. {
  34. return this->Output.c_str();
  35. }
  36. int cmCTestBuildAndTestHandler::ProcessHandler()
  37. {
  38. this->Output.clear();
  39. std::string output;
  40. cmSystemTools::ResetErrorOccuredFlag();
  41. int retv = this->RunCMakeAndTest(&this->Output);
  42. cmSystemTools::ResetErrorOccuredFlag();
  43. return retv;
  44. }
  45. int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
  46. std::ostringstream& out,
  47. std::string& cmakeOutString,
  48. cmake* cm)
  49. {
  50. std::vector<std::string> args;
  51. args.push_back(cmSystemTools::GetCMakeCommand());
  52. args.push_back(this->SourceDir);
  53. if (!this->BuildGenerator.empty()) {
  54. args.push_back("-G" + this->BuildGenerator);
  55. }
  56. if (!this->BuildGeneratorPlatform.empty()) {
  57. args.push_back("-A" + this->BuildGeneratorPlatform);
  58. }
  59. if (!this->BuildGeneratorToolset.empty()) {
  60. args.push_back("-T" + this->BuildGeneratorToolset);
  61. }
  62. const char* config = nullptr;
  63. if (!this->CTest->GetConfigType().empty()) {
  64. config = this->CTest->GetConfigType().c_str();
  65. }
  66. #ifdef CMAKE_INTDIR
  67. if (!config) {
  68. config = CMAKE_INTDIR;
  69. }
  70. #endif
  71. if (config) {
  72. args.push_back("-DCMAKE_BUILD_TYPE:STRING=" + std::string(config));
  73. }
  74. if (!this->BuildMakeProgram.empty() &&
  75. (this->BuildGenerator.find("Make") != std::string::npos ||
  76. this->BuildGenerator.find("Ninja") != std::string::npos)) {
  77. args.push_back("-DCMAKE_MAKE_PROGRAM:FILEPATH=" + this->BuildMakeProgram);
  78. }
  79. for (std::string const& opt : this->BuildOptions) {
  80. args.push_back(opt);
  81. }
  82. if (cm->Run(args) != 0) {
  83. out << "Error: cmake execution failed\n";
  84. out << cmakeOutString << "\n";
  85. if (outstring) {
  86. *outstring = out.str();
  87. } else {
  88. cmCTestLog(this->CTest, ERROR_MESSAGE, out.str() << std::endl);
  89. }
  90. return 1;
  91. }
  92. // do another config?
  93. if (this->BuildTwoConfig) {
  94. if (cm->Run(args) != 0) {
  95. out << "Error: cmake execution failed\n";
  96. out << cmakeOutString << "\n";
  97. if (outstring) {
  98. *outstring = out.str();
  99. } else {
  100. cmCTestLog(this->CTest, ERROR_MESSAGE, out.str() << std::endl);
  101. }
  102. return 1;
  103. }
  104. }
  105. out << "======== CMake output ======\n";
  106. out << cmakeOutString;
  107. out << "======== End CMake output ======\n";
  108. return 0;
  109. }
  110. class cmCTestBuildAndTestCaptureRAII
  111. {
  112. cmake& CM;
  113. public:
  114. cmCTestBuildAndTestCaptureRAII(cmake& cm, std::string& s)
  115. : CM(cm)
  116. {
  117. cmSystemTools::SetMessageCallback(
  118. [&s](const std::string& msg, const cmMessageMetadata& /* unused */) {
  119. s += msg;
  120. s += "\n";
  121. });
  122. cmSystemTools::SetStdoutCallback([&s](std::string const& m) { s += m; });
  123. cmSystemTools::SetStderrCallback([&s](std::string const& m) { s += m; });
  124. this->CM.SetProgressCallback([&s](const std::string& msg, float prog) {
  125. if (prog < 0) {
  126. s += msg;
  127. s += "\n";
  128. }
  129. });
  130. }
  131. ~cmCTestBuildAndTestCaptureRAII()
  132. {
  133. this->CM.SetProgressCallback(nullptr);
  134. cmSystemTools::SetStderrCallback(nullptr);
  135. cmSystemTools::SetStdoutCallback(nullptr);
  136. cmSystemTools::SetMessageCallback(nullptr);
  137. }
  138. cmCTestBuildAndTestCaptureRAII(const cmCTestBuildAndTestCaptureRAII&) =
  139. delete;
  140. cmCTestBuildAndTestCaptureRAII& operator=(
  141. const cmCTestBuildAndTestCaptureRAII&) = delete;
  142. };
  143. int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
  144. {
  145. // if the generator and make program are not specified then it is an error
  146. if (this->BuildGenerator.empty()) {
  147. if (outstring) {
  148. *outstring = "--build-and-test requires that the generator "
  149. "be provided using the --build-generator "
  150. "command line option. ";
  151. }
  152. return 1;
  153. }
  154. cmake cm(cmake::RoleProject, cmState::Project);
  155. cm.SetHomeDirectory("");
  156. cm.SetHomeOutputDirectory("");
  157. std::string cmakeOutString;
  158. cmCTestBuildAndTestCaptureRAII captureRAII(cm, cmakeOutString);
  159. static_cast<void>(captureRAII);
  160. std::ostringstream out;
  161. if (this->CTest->GetConfigType().empty() && !this->ConfigSample.empty()) {
  162. // use the config sample to set the ConfigType
  163. std::string fullPath;
  164. std::string resultingConfig;
  165. std::vector<std::string> extraPaths;
  166. std::vector<std::string> failed;
  167. fullPath = cmCTestTestHandler::FindExecutable(
  168. this->CTest, this->ConfigSample, resultingConfig, extraPaths, failed);
  169. if (!fullPath.empty() && !resultingConfig.empty()) {
  170. this->CTest->SetConfigType(resultingConfig);
  171. }
  172. out << "Using config sample with results: " << fullPath << " and "
  173. << resultingConfig << std::endl;
  174. }
  175. // we need to honor the timeout specified, the timeout include cmake, build
  176. // and test time
  177. auto clock_start = std::chrono::steady_clock::now();
  178. // make sure the binary dir is there
  179. out << "Internal cmake changing into directory: " << this->BinaryDir
  180. << std::endl;
  181. if (!cmSystemTools::FileIsDirectory(this->BinaryDir)) {
  182. cmSystemTools::MakeDirectory(this->BinaryDir);
  183. }
  184. cmWorkingDirectory workdir(this->BinaryDir);
  185. if (workdir.Failed()) {
  186. auto msg = "Failed to change working directory to " + this->BinaryDir +
  187. " : " + std::strerror(workdir.GetLastResult()) + "\n";
  188. if (outstring) {
  189. *outstring = msg;
  190. } else {
  191. cmCTestLog(this->CTest, ERROR_MESSAGE, msg);
  192. }
  193. return 1;
  194. }
  195. if (this->BuildNoCMake) {
  196. // Make the generator available for the Build call below.
  197. cm.SetGlobalGenerator(cm.CreateGlobalGenerator(this->BuildGenerator));
  198. if (!this->BuildGeneratorPlatform.empty()) {
  199. cmMakefile mf(cm.GetGlobalGenerator(), cm.GetCurrentSnapshot());
  200. if (!cm.GetGlobalGenerator()->SetGeneratorPlatform(
  201. this->BuildGeneratorPlatform, &mf)) {
  202. return 1;
  203. }
  204. }
  205. // Load the cache to make CMAKE_MAKE_PROGRAM available.
  206. cm.LoadCache(this->BinaryDir);
  207. } else {
  208. // do the cmake step, no timeout here since it is not a sub process
  209. if (this->RunCMake(outstring, out, cmakeOutString, &cm)) {
  210. return 1;
  211. }
  212. }
  213. // do the build
  214. if (this->BuildTargets.empty()) {
  215. this->BuildTargets.emplace_back();
  216. }
  217. for (std::string const& tar : this->BuildTargets) {
  218. cmDuration remainingTime = std::chrono::seconds(0);
  219. if (this->Timeout > cmDuration::zero()) {
  220. remainingTime =
  221. this->Timeout - (std::chrono::steady_clock::now() - clock_start);
  222. if (remainingTime <= std::chrono::seconds(0)) {
  223. if (outstring) {
  224. *outstring = "--build-and-test timeout exceeded. ";
  225. }
  226. return 1;
  227. }
  228. }
  229. std::string output;
  230. const char* config = nullptr;
  231. if (!this->CTest->GetConfigType().empty()) {
  232. config = this->CTest->GetConfigType().c_str();
  233. }
  234. #ifdef CMAKE_INTDIR
  235. if (!config) {
  236. config = CMAKE_INTDIR;
  237. }
  238. #endif
  239. if (!config) {
  240. config = "Debug";
  241. }
  242. cmBuildOptions buildOptions(!this->BuildNoClean, false,
  243. PackageResolveMode::Disable);
  244. int retVal = cm.GetGlobalGenerator()->Build(
  245. cmake::NO_BUILD_PARALLEL_LEVEL, this->SourceDir, this->BinaryDir,
  246. this->BuildProject, { tar }, output, this->BuildMakeProgram, config,
  247. buildOptions, false, remainingTime);
  248. out << output;
  249. // if the build failed then return
  250. if (retVal) {
  251. if (outstring) {
  252. *outstring = out.str();
  253. }
  254. return 1;
  255. }
  256. }
  257. if (outstring) {
  258. *outstring = out.str();
  259. }
  260. // if no test was specified then we are done
  261. if (this->TestCommand.empty()) {
  262. return 0;
  263. }
  264. // now run the compiled test if we can find it
  265. // store the final location in fullPath
  266. std::string fullPath;
  267. std::string resultingConfig;
  268. std::vector<std::string> extraPaths;
  269. // if this->ExecutableDirectory is set try that as well
  270. if (!this->ExecutableDirectory.empty()) {
  271. std::string tempPath =
  272. cmStrCat(this->ExecutableDirectory, '/', this->TestCommand);
  273. extraPaths.push_back(tempPath);
  274. }
  275. std::vector<std::string> failed;
  276. fullPath = cmCTestTestHandler::FindExecutable(
  277. this->CTest, this->TestCommand, resultingConfig, extraPaths, failed);
  278. if (!cmSystemTools::FileExists(fullPath)) {
  279. out << "Could not find path to executable, perhaps it was not built: "
  280. << this->TestCommand << "\n";
  281. out << "tried to find it in these places:\n";
  282. out << fullPath << "\n";
  283. for (std::string const& fail : failed) {
  284. out << fail << "\n";
  285. }
  286. if (outstring) {
  287. *outstring = out.str();
  288. } else {
  289. cmCTestLog(this->CTest, ERROR_MESSAGE, out.str());
  290. }
  291. return 1;
  292. }
  293. std::vector<const char*> testCommand;
  294. testCommand.push_back(fullPath.c_str());
  295. for (std::string const& testCommandArg : this->TestCommandArgs) {
  296. testCommand.push_back(testCommandArg.c_str());
  297. }
  298. testCommand.push_back(nullptr);
  299. std::string outs;
  300. int retval = 0;
  301. // run the test from the this->BuildRunDir if set
  302. if (!this->BuildRunDir.empty()) {
  303. out << "Run test in directory: " << this->BuildRunDir << "\n";
  304. if (!workdir.SetDirectory(this->BuildRunDir)) {
  305. out << "Failed to change working directory : "
  306. << std::strerror(workdir.GetLastResult()) << "\n";
  307. if (outstring) {
  308. *outstring = out.str();
  309. } else {
  310. cmCTestLog(this->CTest, ERROR_MESSAGE, out.str());
  311. }
  312. return 1;
  313. }
  314. }
  315. out << "Running test command: \"" << fullPath << "\"";
  316. for (std::string const& testCommandArg : this->TestCommandArgs) {
  317. out << " \"" << testCommandArg << "\"";
  318. }
  319. out << "\n";
  320. // how much time is remaining
  321. cmDuration remainingTime = std::chrono::seconds(0);
  322. if (this->Timeout > cmDuration::zero()) {
  323. remainingTime =
  324. this->Timeout - (std::chrono::steady_clock::now() - clock_start);
  325. if (remainingTime <= std::chrono::seconds(0)) {
  326. if (outstring) {
  327. *outstring = "--build-and-test timeout exceeded. ";
  328. }
  329. return 1;
  330. }
  331. }
  332. int runTestRes = this->CTest->RunTest(testCommand, &outs, &retval, nullptr,
  333. remainingTime, nullptr);
  334. if (runTestRes != cmsysProcess_State_Exited || retval != 0) {
  335. out << "Test command failed: " << testCommand[0] << "\n";
  336. retval = 1;
  337. }
  338. out << outs << "\n";
  339. if (outstring) {
  340. *outstring = out.str();
  341. } else {
  342. cmCTestLog(this->CTest, OUTPUT, out.str() << std::endl);
  343. }
  344. return retval;
  345. }
  346. int cmCTestBuildAndTestHandler::ProcessCommandLineArguments(
  347. const std::string& currentArg, size_t& idx,
  348. const std::vector<std::string>& allArgs)
  349. {
  350. // --build-and-test options
  351. if (cmHasLiteralPrefix(currentArg, "--build-and-test") &&
  352. idx < allArgs.size() - 1) {
  353. if (idx + 2 < allArgs.size()) {
  354. idx++;
  355. this->SourceDir = allArgs[idx];
  356. idx++;
  357. this->BinaryDir = allArgs[idx];
  358. // dir must exist before CollapseFullPath is called
  359. cmSystemTools::MakeDirectory(this->BinaryDir);
  360. this->BinaryDir = cmSystemTools::CollapseFullPath(this->BinaryDir);
  361. this->SourceDir = cmSystemTools::CollapseFullPath(this->SourceDir);
  362. } else {
  363. cmCTestLog(this->CTest, ERROR_MESSAGE,
  364. "--build-and-test must have source and binary dir"
  365. << std::endl);
  366. return 0;
  367. }
  368. }
  369. if (cmHasLiteralPrefix(currentArg, "--build-target") &&
  370. idx < allArgs.size() - 1) {
  371. idx++;
  372. this->BuildTargets.push_back(allArgs[idx]);
  373. }
  374. if (cmHasLiteralPrefix(currentArg, "--build-nocmake")) {
  375. this->BuildNoCMake = true;
  376. }
  377. if (cmHasLiteralPrefix(currentArg, "--build-run-dir") &&
  378. idx < allArgs.size() - 1) {
  379. idx++;
  380. this->BuildRunDir = allArgs[idx];
  381. }
  382. if (cmHasLiteralPrefix(currentArg, "--build-two-config")) {
  383. this->BuildTwoConfig = true;
  384. }
  385. if (cmHasLiteralPrefix(currentArg, "--build-exe-dir") &&
  386. idx < allArgs.size() - 1) {
  387. idx++;
  388. this->ExecutableDirectory = allArgs[idx];
  389. }
  390. if (cmHasLiteralPrefix(currentArg, "--test-timeout") &&
  391. idx < allArgs.size() - 1) {
  392. idx++;
  393. this->Timeout = cmDuration(atof(allArgs[idx].c_str()));
  394. }
  395. if (currentArg == "--build-generator" && idx < allArgs.size() - 1) {
  396. idx++;
  397. this->BuildGenerator = allArgs[idx];
  398. }
  399. if (currentArg == "--build-generator-platform" && idx < allArgs.size() - 1) {
  400. idx++;
  401. this->BuildGeneratorPlatform = allArgs[idx];
  402. }
  403. if (currentArg == "--build-generator-toolset" && idx < allArgs.size() - 1) {
  404. idx++;
  405. this->BuildGeneratorToolset = allArgs[idx];
  406. }
  407. if (cmHasLiteralPrefix(currentArg, "--build-project") &&
  408. idx < allArgs.size() - 1) {
  409. idx++;
  410. this->BuildProject = allArgs[idx];
  411. }
  412. if (cmHasLiteralPrefix(currentArg, "--build-makeprogram") &&
  413. idx < allArgs.size() - 1) {
  414. idx++;
  415. this->BuildMakeProgram = allArgs[idx];
  416. }
  417. if (cmHasLiteralPrefix(currentArg, "--build-config-sample") &&
  418. idx < allArgs.size() - 1) {
  419. idx++;
  420. this->ConfigSample = allArgs[idx];
  421. }
  422. if (cmHasLiteralPrefix(currentArg, "--build-noclean")) {
  423. this->BuildNoClean = true;
  424. }
  425. if (cmHasLiteralPrefix(currentArg, "--build-options")) {
  426. while (idx + 1 < allArgs.size() && allArgs[idx + 1] != "--build-target" &&
  427. allArgs[idx + 1] != "--test-command") {
  428. ++idx;
  429. this->BuildOptions.push_back(allArgs[idx]);
  430. }
  431. }
  432. if (cmHasLiteralPrefix(currentArg, "--test-command") &&
  433. idx < allArgs.size() - 1) {
  434. ++idx;
  435. this->TestCommand = allArgs[idx];
  436. while (idx + 1 < allArgs.size()) {
  437. ++idx;
  438. this->TestCommandArgs.push_back(allArgs[idx]);
  439. }
  440. }
  441. return 1;
  442. }