cmCTest.cxx 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070
  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 "cmCTest.h"
  4. #include "cm_curl.h"
  5. #include "cm_zlib.h"
  6. #include "cmsys/Base64.h"
  7. #include "cmsys/Directory.hxx"
  8. #include "cmsys/FStream.hxx"
  9. #include "cmsys/Glob.hxx"
  10. #include "cmsys/Process.h"
  11. #include "cmsys/SystemInformation.hxx"
  12. #include <algorithm>
  13. #include <chrono>
  14. #include <ctype.h>
  15. #include <iostream>
  16. #include <map>
  17. #include <memory> // IWYU pragma: keep
  18. #include <sstream>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <string>
  23. #include <time.h>
  24. #include <utility>
  25. #include <vector>
  26. #if defined(_WIN32)
  27. # include <windows.h> // IWYU pragma: keep
  28. #else
  29. # include <unistd.h> // IWYU pragma: keep
  30. #endif
  31. #include "cmAlgorithms.h"
  32. #include "cmCTestBuildAndTestHandler.h"
  33. #include "cmCTestBuildHandler.h"
  34. #include "cmCTestConfigureHandler.h"
  35. #include "cmCTestCoverageHandler.h"
  36. #include "cmCTestGenericHandler.h"
  37. #include "cmCTestMemCheckHandler.h"
  38. #include "cmCTestScriptHandler.h"
  39. #include "cmCTestStartCommand.h"
  40. #include "cmCTestSubmitHandler.h"
  41. #include "cmCTestTestHandler.h"
  42. #include "cmCTestUpdateHandler.h"
  43. #include "cmCTestUploadHandler.h"
  44. #include "cmCurl.h"
  45. #include "cmDynamicLoader.h"
  46. #include "cmGeneratedFileStream.h"
  47. #include "cmGlobalGenerator.h"
  48. #include "cmMakefile.h"
  49. #include "cmProcessOutput.h"
  50. #include "cmState.h"
  51. #include "cmStateSnapshot.h"
  52. #include "cmStateTypes.h"
  53. #include "cmSystemTools.h"
  54. #include "cmVersion.h"
  55. #include "cmVersionConfig.h"
  56. #include "cmXMLWriter.h"
  57. #include "cmake.h"
  58. #if defined(__BEOS__) || defined(__HAIKU__)
  59. # include <be/kernel/OS.h> /* disable_debugger() API. */
  60. #endif
  61. #define DEBUGOUT \
  62. std::cout << __LINE__ << " "; \
  63. std::cout
  64. #define DEBUGERR \
  65. std::cerr << __LINE__ << " "; \
  66. std::cerr
  67. struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
  68. {
  69. struct tm* lctime;
  70. time_t tctime = time(nullptr);
  71. lctime = gmtime(&tctime);
  72. char buf[1024];
  73. // add todays year day and month to the time in str because
  74. // curl_getdate no longer assumes the day is today
  75. sprintf(buf, "%d%02d%02d %s", lctime->tm_year + 1900, lctime->tm_mon + 1,
  76. lctime->tm_mday, str.c_str());
  77. cmCTestLog(this, OUTPUT,
  78. "Determine Nightly Start Time" << std::endl
  79. << " Specified time: " << str
  80. << std::endl);
  81. // Convert the nightly start time to seconds. Since we are
  82. // providing only a time and a timezone, the current date of
  83. // the local machine is assumed. Consequently, nightlySeconds
  84. // is the time at which the nightly dashboard was opened or
  85. // will be opened on the date of the current client machine.
  86. // As such, this time may be in the past or in the future.
  87. time_t ntime = curl_getdate(buf, &tctime);
  88. cmCTestLog(this, DEBUG, " Get curl time: " << ntime << std::endl);
  89. tctime = time(nullptr);
  90. cmCTestLog(this, DEBUG, " Get the current time: " << tctime << std::endl);
  91. const int dayLength = 24 * 60 * 60;
  92. cmCTestLog(this, DEBUG, "Seconds: " << tctime << std::endl);
  93. while (ntime > tctime) {
  94. // If nightlySeconds is in the past, this is the current
  95. // open dashboard, then return nightlySeconds. If
  96. // nightlySeconds is in the future, this is the next
  97. // dashboard to be opened, so subtract 24 hours to get the
  98. // time of the current open dashboard
  99. ntime -= dayLength;
  100. cmCTestLog(this, DEBUG, "Pick yesterday" << std::endl);
  101. cmCTestLog(this, DEBUG,
  102. " Future time, subtract day: " << ntime << std::endl);
  103. }
  104. while (tctime > (ntime + dayLength)) {
  105. ntime += dayLength;
  106. cmCTestLog(this, DEBUG, " Past time, add day: " << ntime << std::endl);
  107. }
  108. cmCTestLog(this, DEBUG, "nightlySeconds: " << ntime << std::endl);
  109. cmCTestLog(this, DEBUG,
  110. " Current time: " << tctime << " Nightly time: " << ntime
  111. << std::endl);
  112. if (tomorrowtag) {
  113. cmCTestLog(this, OUTPUT, " Use future tag, Add a day" << std::endl);
  114. ntime += dayLength;
  115. }
  116. lctime = gmtime(&ntime);
  117. return lctime;
  118. }
  119. std::string cmCTest::CleanString(const std::string& str)
  120. {
  121. std::string::size_type spos = str.find_first_not_of(" \n\t\r\f\v");
  122. std::string::size_type epos = str.find_last_not_of(" \n\t\r\f\v");
  123. if (spos == std::string::npos) {
  124. return std::string();
  125. }
  126. if (epos != std::string::npos) {
  127. epos = epos - spos + 1;
  128. }
  129. return str.substr(spos, epos);
  130. }
  131. std::string cmCTest::CurrentTime()
  132. {
  133. time_t currenttime = time(nullptr);
  134. struct tm* t = localtime(&currenttime);
  135. // return ::CleanString(ctime(&currenttime));
  136. char current_time[1024];
  137. if (this->ShortDateFormat) {
  138. strftime(current_time, 1000, "%b %d %H:%M %Z", t);
  139. } else {
  140. strftime(current_time, 1000, "%a %b %d %H:%M:%S %Z %Y", t);
  141. }
  142. cmCTestLog(this, DEBUG, " Current_Time: " << current_time << std::endl);
  143. return cmCTest::CleanString(current_time);
  144. }
  145. std::string cmCTest::GetCostDataFile()
  146. {
  147. std::string fname = this->GetCTestConfiguration("CostDataFile");
  148. if (fname.empty()) {
  149. fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt";
  150. }
  151. return fname;
  152. }
  153. #ifdef CMAKE_BUILD_WITH_CMAKE
  154. static size_t HTTPResponseCallback(void* ptr, size_t size, size_t nmemb,
  155. void* data)
  156. {
  157. int realsize = static_cast<int>(size * nmemb);
  158. std::string* response = static_cast<std::string*>(data);
  159. const char* chPtr = static_cast<char*>(ptr);
  160. *response += chPtr;
  161. return realsize;
  162. }
  163. int cmCTest::HTTPRequest(std::string url, HTTPMethod method,
  164. std::string& response, std::string const& fields,
  165. std::string const& putFile, int timeout)
  166. {
  167. CURL* curl;
  168. FILE* file;
  169. ::curl_global_init(CURL_GLOBAL_ALL);
  170. curl = ::curl_easy_init();
  171. cmCurlSetCAInfo(curl);
  172. // set request options based on method
  173. switch (method) {
  174. case cmCTest::HTTP_POST:
  175. ::curl_easy_setopt(curl, CURLOPT_POST, 1);
  176. ::curl_easy_setopt(curl, CURLOPT_POSTFIELDS, fields.c_str());
  177. break;
  178. case cmCTest::HTTP_PUT:
  179. if (!cmSystemTools::FileExists(putFile)) {
  180. response = "Error: File ";
  181. response += putFile + " does not exist.\n";
  182. return -1;
  183. }
  184. ::curl_easy_setopt(curl, CURLOPT_PUT, 1);
  185. file = cmsys::SystemTools::Fopen(putFile, "rb");
  186. ::curl_easy_setopt(curl, CURLOPT_INFILE, file);
  187. // fall through to append GET fields
  188. CM_FALLTHROUGH;
  189. case cmCTest::HTTP_GET:
  190. if (!fields.empty()) {
  191. url += "?" + fields;
  192. }
  193. break;
  194. }
  195. ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  196. ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  197. ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  198. // set response options
  199. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTTPResponseCallback);
  200. ::curl_easy_setopt(curl, CURLOPT_FILE, &response);
  201. ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  202. CURLcode res = ::curl_easy_perform(curl);
  203. ::curl_easy_cleanup(curl);
  204. ::curl_global_cleanup();
  205. return static_cast<int>(res);
  206. }
  207. #endif
  208. std::string cmCTest::MakeURLSafe(const std::string& str)
  209. {
  210. std::ostringstream ost;
  211. char buffer[10];
  212. for (unsigned char ch : str) {
  213. if ((ch > 126 || ch < 32 || ch == '&' || ch == '%' || ch == '+' ||
  214. ch == '=' || ch == '@') &&
  215. ch != 9) {
  216. sprintf(buffer, "%02x;", static_cast<unsigned int>(ch));
  217. ost << buffer;
  218. } else {
  219. ost << ch;
  220. }
  221. }
  222. return ost.str();
  223. }
  224. std::string cmCTest::DecodeURL(const std::string& in)
  225. {
  226. std::string out;
  227. for (const char* c = in.c_str(); *c; ++c) {
  228. if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
  229. char buf[3] = { *(c + 1), *(c + 2), 0 };
  230. out.append(1, char(strtoul(buf, nullptr, 16)));
  231. c += 2;
  232. } else {
  233. out.append(1, *c);
  234. }
  235. }
  236. return out;
  237. }
  238. cmCTest::cmCTest()
  239. {
  240. this->LabelSummary = true;
  241. this->SubprojectSummary = true;
  242. this->ParallelLevel = 1;
  243. this->ParallelLevelSetInCli = false;
  244. this->TestLoad = 0;
  245. this->SubmitIndex = 0;
  246. this->Failover = false;
  247. this->ForceNewCTestProcess = false;
  248. this->TomorrowTag = false;
  249. this->TestProgressOutput = false;
  250. this->FlushTestProgressLine = false;
  251. this->Verbose = false;
  252. this->Debug = false;
  253. this->ShowLineNumbers = false;
  254. this->Quiet = false;
  255. this->ExtraVerbose = false;
  256. this->ProduceXML = false;
  257. this->ShowOnly = false;
  258. this->OutputAsJson = false;
  259. this->OutputAsJsonVersion = 1;
  260. this->RunConfigurationScript = false;
  261. this->UseHTTP10 = false;
  262. this->PrintLabels = false;
  263. this->CompressTestOutput = true;
  264. this->TestModel = cmCTest::EXPERIMENTAL;
  265. this->MaxTestNameWidth = 30;
  266. this->InteractiveDebugMode = true;
  267. this->TimeOut = cmDuration::zero();
  268. this->GlobalTimeout = cmDuration::zero();
  269. this->CompressXMLFiles = false;
  270. this->ScheduleType.clear();
  271. this->OutputLogFile = nullptr;
  272. this->OutputLogFileLastTag = -1;
  273. this->SuppressUpdatingCTestConfiguration = false;
  274. this->BuildID = "";
  275. this->OutputTestOutputOnTestFailure = false;
  276. this->OutputColorCode = cmCTest::ColoredOutputSupportedByConsole();
  277. this->RepeatTests = 1; // default to run each test once
  278. this->RepeatUntilFail = false;
  279. std::string envValue;
  280. if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", envValue)) {
  281. this->OutputTestOutputOnTestFailure = !cmSystemTools::IsOff(envValue);
  282. }
  283. envValue.clear();
  284. if (cmSystemTools::GetEnv("CTEST_PROGRESS_OUTPUT", envValue)) {
  285. this->TestProgressOutput = !cmSystemTools::IsOff(envValue);
  286. }
  287. this->InitStreams();
  288. this->Parts[PartStart].SetName("Start");
  289. this->Parts[PartUpdate].SetName("Update");
  290. this->Parts[PartConfigure].SetName("Configure");
  291. this->Parts[PartBuild].SetName("Build");
  292. this->Parts[PartTest].SetName("Test");
  293. this->Parts[PartCoverage].SetName("Coverage");
  294. this->Parts[PartMemCheck].SetName("MemCheck");
  295. this->Parts[PartSubmit].SetName("Submit");
  296. this->Parts[PartNotes].SetName("Notes");
  297. this->Parts[PartExtraFiles].SetName("ExtraFiles");
  298. this->Parts[PartUpload].SetName("Upload");
  299. this->Parts[PartDone].SetName("Done");
  300. // Fill the part name-to-id map.
  301. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  302. this->PartMap[cmSystemTools::LowerCase(this->Parts[p].GetName())] = p;
  303. }
  304. this->ShortDateFormat = true;
  305. this->TestingHandlers["build"] = new cmCTestBuildHandler;
  306. this->TestingHandlers["buildtest"] = new cmCTestBuildAndTestHandler;
  307. this->TestingHandlers["coverage"] = new cmCTestCoverageHandler;
  308. this->TestingHandlers["script"] = new cmCTestScriptHandler;
  309. this->TestingHandlers["test"] = new cmCTestTestHandler;
  310. this->TestingHandlers["update"] = new cmCTestUpdateHandler;
  311. this->TestingHandlers["configure"] = new cmCTestConfigureHandler;
  312. this->TestingHandlers["memcheck"] = new cmCTestMemCheckHandler;
  313. this->TestingHandlers["submit"] = new cmCTestSubmitHandler;
  314. this->TestingHandlers["upload"] = new cmCTestUploadHandler;
  315. for (auto& handler : this->TestingHandlers) {
  316. handler.second->SetCTestInstance(this);
  317. }
  318. // Make sure we can capture the build tool output.
  319. cmSystemTools::EnableVSConsoleOutput();
  320. }
  321. cmCTest::~cmCTest()
  322. {
  323. cmDeleteAll(this->TestingHandlers);
  324. this->SetOutputLogFileName(nullptr);
  325. }
  326. void cmCTest::SetParallelLevel(int level)
  327. {
  328. this->ParallelLevel = level < 1 ? 1 : level;
  329. }
  330. void cmCTest::SetTestLoad(unsigned long load)
  331. {
  332. this->TestLoad = load;
  333. }
  334. bool cmCTest::ShouldCompressTestOutput()
  335. {
  336. return this->CompressTestOutput;
  337. }
  338. cmCTest::Part cmCTest::GetPartFromName(const char* name)
  339. {
  340. // Look up by lower-case to make names case-insensitive.
  341. std::string lower_name = cmSystemTools::LowerCase(name);
  342. PartMapType::const_iterator i = this->PartMap.find(lower_name);
  343. if (i != this->PartMap.end()) {
  344. return i->second;
  345. }
  346. // The string does not name a valid part.
  347. return PartCount;
  348. }
  349. int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
  350. {
  351. bool quiet = false;
  352. if (command && command->ShouldBeQuiet()) {
  353. quiet = true;
  354. }
  355. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  356. if (!this->InteractiveDebugMode) {
  357. this->BlockTestErrorDiagnostics();
  358. } else {
  359. cmSystemTools::PutEnv("CTEST_INTERACTIVE_DEBUG_MODE=1");
  360. }
  361. this->BinaryDir = binary_dir;
  362. cmSystemTools::ConvertToUnixSlashes(this->BinaryDir);
  363. this->UpdateCTestConfiguration();
  364. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  365. if (this->ProduceXML) {
  366. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  367. cmCTestOptionalLog(this, OUTPUT,
  368. " Site: "
  369. << this->GetCTestConfiguration("Site") << std::endl
  370. << " Build name: "
  371. << cmCTest::SafeBuildIdField(
  372. this->GetCTestConfiguration("BuildName"))
  373. << std::endl,
  374. quiet);
  375. cmCTestOptionalLog(this, DEBUG, "Produce XML is on" << std::endl, quiet);
  376. if (this->TestModel == cmCTest::NIGHTLY &&
  377. this->GetCTestConfiguration("NightlyStartTime").empty()) {
  378. cmCTestOptionalLog(
  379. this, WARNING,
  380. "WARNING: No nightly start time found please set in CTestConfig.cmake"
  381. " or DartConfig.cmake"
  382. << std::endl,
  383. quiet);
  384. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl,
  385. quiet);
  386. return 0;
  387. }
  388. }
  389. cmake cm(cmake::RoleScript, cmState::CTest);
  390. cm.SetHomeDirectory("");
  391. cm.SetHomeOutputDirectory("");
  392. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  393. cmGlobalGenerator gg(&cm);
  394. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  395. if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), &mf)) {
  396. cmCTestOptionalLog(
  397. this, DEBUG, "Cannot find custom configuration file tree" << std::endl,
  398. quiet);
  399. return 0;
  400. }
  401. if (this->ProduceXML) {
  402. // Verify "Testing" directory exists:
  403. //
  404. std::string testingDir = this->BinaryDir + "/Testing";
  405. if (cmSystemTools::FileExists(testingDir)) {
  406. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  407. cmCTestLog(this, ERROR_MESSAGE,
  408. "File " << testingDir
  409. << " is in the place of the testing directory"
  410. << std::endl);
  411. return 0;
  412. }
  413. } else {
  414. if (!cmSystemTools::MakeDirectory(testingDir)) {
  415. cmCTestLog(this, ERROR_MESSAGE,
  416. "Cannot create directory " << testingDir << std::endl);
  417. return 0;
  418. }
  419. }
  420. // Create new "TAG" file or read existing one:
  421. //
  422. bool createNewTag = true;
  423. if (command) {
  424. createNewTag = command->ShouldCreateNewTag();
  425. }
  426. std::string tagfile = testingDir + "/TAG";
  427. cmsys::ifstream tfin(tagfile.c_str());
  428. std::string tag;
  429. if (createNewTag) {
  430. time_t tctime = time(nullptr);
  431. if (this->TomorrowTag) {
  432. tctime += (24 * 60 * 60);
  433. }
  434. struct tm* lctime = gmtime(&tctime);
  435. if (tfin && cmSystemTools::GetLineFromStream(tfin, tag)) {
  436. int year = 0;
  437. int mon = 0;
  438. int day = 0;
  439. int hour = 0;
  440. int min = 0;
  441. sscanf(tag.c_str(), "%04d%02d%02d-%02d%02d", &year, &mon, &day, &hour,
  442. &min);
  443. if (year != lctime->tm_year + 1900 || mon != lctime->tm_mon + 1 ||
  444. day != lctime->tm_mday) {
  445. tag.clear();
  446. }
  447. std::string track;
  448. if (cmSystemTools::GetLineFromStream(tfin, track) &&
  449. !this->Parts[PartStart] && !command) {
  450. this->SpecificTrack = track;
  451. }
  452. std::string model;
  453. if (cmSystemTools::GetLineFromStream(tfin, model) &&
  454. !this->Parts[PartStart] && !command) {
  455. this->TestModel = GetTestModelFromString(model.c_str());
  456. }
  457. tfin.close();
  458. }
  459. if (tag.empty() || (nullptr != command) || this->Parts[PartStart]) {
  460. cmCTestOptionalLog(
  461. this, DEBUG,
  462. "TestModel: " << this->GetTestModelString() << std::endl, quiet);
  463. cmCTestOptionalLog(
  464. this, DEBUG, "TestModel: " << this->TestModel << std::endl, quiet);
  465. if (this->TestModel == cmCTest::NIGHTLY) {
  466. lctime = this->GetNightlyTime(
  467. this->GetCTestConfiguration("NightlyStartTime"),
  468. this->TomorrowTag);
  469. }
  470. char datestring[100];
  471. sprintf(datestring, "%04d%02d%02d-%02d%02d", lctime->tm_year + 1900,
  472. lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour,
  473. lctime->tm_min);
  474. tag = datestring;
  475. cmsys::ofstream ofs(tagfile.c_str());
  476. if (ofs) {
  477. ofs << tag << std::endl;
  478. ofs << this->GetTestModelString() << std::endl;
  479. switch (this->TestModel) {
  480. case cmCTest::EXPERIMENTAL:
  481. ofs << "Experimental" << std::endl;
  482. break;
  483. case cmCTest::NIGHTLY:
  484. ofs << "Nightly" << std::endl;
  485. break;
  486. case cmCTest::CONTINUOUS:
  487. ofs << "Continuous" << std::endl;
  488. break;
  489. }
  490. }
  491. ofs.close();
  492. if (nullptr == command) {
  493. cmCTestOptionalLog(this, OUTPUT,
  494. "Create new tag: " << tag << " - "
  495. << this->GetTestModelString()
  496. << std::endl,
  497. quiet);
  498. }
  499. }
  500. } else {
  501. std::string track;
  502. std::string modelStr;
  503. int model = cmCTest::UNKNOWN;
  504. if (tfin) {
  505. cmSystemTools::GetLineFromStream(tfin, tag);
  506. cmSystemTools::GetLineFromStream(tfin, track);
  507. if (cmSystemTools::GetLineFromStream(tfin, modelStr)) {
  508. model = GetTestModelFromString(modelStr.c_str());
  509. }
  510. tfin.close();
  511. }
  512. if (tag.empty()) {
  513. cmCTestLog(this, ERROR_MESSAGE,
  514. "Cannot read existing TAG file in " << testingDir
  515. << std::endl);
  516. return 0;
  517. }
  518. if (this->TestModel == cmCTest::UNKNOWN) {
  519. if (model == cmCTest::UNKNOWN) {
  520. cmCTestLog(this, ERROR_MESSAGE,
  521. "TAG file does not contain model and "
  522. "no model specified in start command"
  523. << std::endl);
  524. return 0;
  525. }
  526. this->SetTestModel(model);
  527. }
  528. if (model != this->TestModel && model != cmCTest::UNKNOWN &&
  529. this->TestModel != cmCTest::UNKNOWN) {
  530. cmCTestOptionalLog(this, WARNING,
  531. "Model given in TAG does not match "
  532. "model given in ctest_start()"
  533. << std::endl,
  534. quiet);
  535. }
  536. if (!this->SpecificTrack.empty() && track != this->SpecificTrack) {
  537. cmCTestOptionalLog(this, WARNING,
  538. "Track given in TAG does not match "
  539. "track given in ctest_start()"
  540. << std::endl,
  541. quiet);
  542. } else {
  543. this->SpecificTrack = track;
  544. }
  545. cmCTestOptionalLog(this, OUTPUT,
  546. " Use existing tag: " << tag << " - "
  547. << this->GetTestModelString()
  548. << std::endl,
  549. quiet);
  550. }
  551. this->CurrentTag = tag;
  552. }
  553. return 1;
  554. }
  555. bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command)
  556. {
  557. std::string src_dir = this->GetCTestConfiguration("SourceDirectory");
  558. std::string bld_dir = this->GetCTestConfiguration("BuildDirectory");
  559. this->BuildID = "";
  560. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  561. this->Parts[p].SubmitFiles.clear();
  562. }
  563. cmMakefile* mf = command->GetMakefile();
  564. std::string fname;
  565. std::string src_dir_fname = src_dir;
  566. src_dir_fname += "/CTestConfig.cmake";
  567. cmSystemTools::ConvertToUnixSlashes(src_dir_fname);
  568. std::string bld_dir_fname = bld_dir;
  569. bld_dir_fname += "/CTestConfig.cmake";
  570. cmSystemTools::ConvertToUnixSlashes(bld_dir_fname);
  571. if (cmSystemTools::FileExists(bld_dir_fname)) {
  572. fname = bld_dir_fname;
  573. } else if (cmSystemTools::FileExists(src_dir_fname)) {
  574. fname = src_dir_fname;
  575. }
  576. if (!fname.empty()) {
  577. cmCTestOptionalLog(this, OUTPUT,
  578. " Reading ctest configuration file: " << fname
  579. << std::endl,
  580. command->ShouldBeQuiet());
  581. bool readit = mf->ReadDependentFile(fname);
  582. if (!readit) {
  583. std::string m = "Could not find include file: ";
  584. m += fname;
  585. command->SetError(m);
  586. return false;
  587. }
  588. }
  589. this->SetCTestConfigurationFromCMakeVariable(mf, "NightlyStartTime",
  590. "CTEST_NIGHTLY_START_TIME",
  591. command->ShouldBeQuiet());
  592. this->SetCTestConfigurationFromCMakeVariable(mf, "Site", "CTEST_SITE",
  593. command->ShouldBeQuiet());
  594. this->SetCTestConfigurationFromCMakeVariable(
  595. mf, "BuildName", "CTEST_BUILD_NAME", command->ShouldBeQuiet());
  596. if (!this->Initialize(bld_dir.c_str(), command)) {
  597. return false;
  598. }
  599. cmCTestOptionalLog(this, OUTPUT,
  600. " Use " << this->GetTestModelString() << " tag: "
  601. << this->GetCurrentTag() << std::endl,
  602. command->ShouldBeQuiet());
  603. return true;
  604. }
  605. bool cmCTest::UpdateCTestConfiguration()
  606. {
  607. if (this->SuppressUpdatingCTestConfiguration) {
  608. return true;
  609. }
  610. std::string fileName = this->BinaryDir + "/CTestConfiguration.ini";
  611. if (!cmSystemTools::FileExists(fileName)) {
  612. fileName = this->BinaryDir + "/DartConfiguration.tcl";
  613. }
  614. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  615. "UpdateCTestConfiguration from :" << fileName << "\n");
  616. if (!cmSystemTools::FileExists(fileName)) {
  617. // No need to exit if we are not producing XML
  618. if (this->ProduceXML) {
  619. cmCTestLog(this, ERROR_MESSAGE,
  620. "Cannot find file: " << fileName << std::endl);
  621. return false;
  622. }
  623. } else {
  624. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  625. "Parse Config file:" << fileName << "\n");
  626. // parse the dart test file
  627. cmsys::ifstream fin(fileName.c_str());
  628. if (!fin) {
  629. return false;
  630. }
  631. char buffer[1024];
  632. while (fin) {
  633. buffer[0] = 0;
  634. fin.getline(buffer, 1023);
  635. buffer[1023] = 0;
  636. std::string line = cmCTest::CleanString(buffer);
  637. if (line.empty()) {
  638. continue;
  639. }
  640. while (fin && (line.back() == '\\')) {
  641. line = line.substr(0, line.size() - 1);
  642. buffer[0] = 0;
  643. fin.getline(buffer, 1023);
  644. buffer[1023] = 0;
  645. line += cmCTest::CleanString(buffer);
  646. }
  647. if (line[0] == '#') {
  648. continue;
  649. }
  650. std::string::size_type cpos = line.find_first_of(':');
  651. if (cpos == std::string::npos) {
  652. continue;
  653. }
  654. std::string key = line.substr(0, cpos);
  655. std::string value = cmCTest::CleanString(line.substr(cpos + 1));
  656. this->CTestConfiguration[key] = value;
  657. }
  658. fin.close();
  659. }
  660. if (!this->GetCTestConfiguration("BuildDirectory").empty()) {
  661. this->BinaryDir = this->GetCTestConfiguration("BuildDirectory");
  662. cmSystemTools::ChangeDirectory(this->BinaryDir);
  663. }
  664. this->TimeOut =
  665. std::chrono::seconds(atoi(this->GetCTestConfiguration("TimeOut").c_str()));
  666. std::string const& testLoad = this->GetCTestConfiguration("TestLoad");
  667. if (!testLoad.empty()) {
  668. unsigned long load;
  669. if (cmSystemTools::StringToULong(testLoad.c_str(), &load)) {
  670. this->SetTestLoad(load);
  671. } else {
  672. cmCTestLog(this, WARNING,
  673. "Invalid value for 'Test Load' : " << testLoad << std::endl);
  674. }
  675. }
  676. if (this->ProduceXML) {
  677. this->CompressXMLFiles =
  678. cmSystemTools::IsOn(this->GetCTestConfiguration("CompressSubmission"));
  679. }
  680. return true;
  681. }
  682. void cmCTest::BlockTestErrorDiagnostics()
  683. {
  684. cmSystemTools::PutEnv("DART_TEST_FROM_DART=1");
  685. cmSystemTools::PutEnv("DASHBOARD_TEST_FROM_CTEST=" CMake_VERSION);
  686. #if defined(_WIN32)
  687. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  688. #elif defined(__BEOS__) || defined(__HAIKU__)
  689. disable_debugger(1);
  690. #endif
  691. }
  692. void cmCTest::SetTestModel(int mode)
  693. {
  694. this->InteractiveDebugMode = false;
  695. this->TestModel = mode;
  696. }
  697. bool cmCTest::SetTest(const char* ttype, bool report)
  698. {
  699. if (cmSystemTools::LowerCase(ttype) == "all") {
  700. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  701. this->Parts[p].Enable();
  702. }
  703. return true;
  704. }
  705. Part p = this->GetPartFromName(ttype);
  706. if (p != PartCount) {
  707. this->Parts[p].Enable();
  708. return true;
  709. }
  710. if (report) {
  711. cmCTestLog(this, ERROR_MESSAGE,
  712. "Don't know about test \"" << ttype << "\" yet..."
  713. << std::endl);
  714. }
  715. return false;
  716. }
  717. void cmCTest::Finalize()
  718. {
  719. }
  720. bool cmCTest::OpenOutputFile(const std::string& path, const std::string& name,
  721. cmGeneratedFileStream& stream, bool compress)
  722. {
  723. std::string testingDir = this->BinaryDir + "/Testing";
  724. if (!path.empty()) {
  725. testingDir += "/" + path;
  726. }
  727. if (cmSystemTools::FileExists(testingDir)) {
  728. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  729. cmCTestLog(this, ERROR_MESSAGE,
  730. "File " << testingDir
  731. << " is in the place of the testing directory"
  732. << std::endl);
  733. return false;
  734. }
  735. } else {
  736. if (!cmSystemTools::MakeDirectory(testingDir)) {
  737. cmCTestLog(this, ERROR_MESSAGE,
  738. "Cannot create directory " << testingDir << std::endl);
  739. return false;
  740. }
  741. }
  742. std::string filename = testingDir + "/" + name;
  743. stream.Open(filename);
  744. if (!stream) {
  745. cmCTestLog(this, ERROR_MESSAGE,
  746. "Problem opening file: " << filename << std::endl);
  747. return false;
  748. }
  749. if (compress) {
  750. if (this->CompressXMLFiles) {
  751. stream.SetCompression(true);
  752. }
  753. }
  754. return true;
  755. }
  756. bool cmCTest::AddIfExists(Part part, const char* file)
  757. {
  758. if (this->CTestFileExists(file)) {
  759. this->AddSubmitFile(part, file);
  760. } else {
  761. std::string name = file;
  762. name += ".gz";
  763. if (this->CTestFileExists(name)) {
  764. this->AddSubmitFile(part, file);
  765. } else {
  766. return false;
  767. }
  768. }
  769. return true;
  770. }
  771. bool cmCTest::CTestFileExists(const std::string& filename)
  772. {
  773. std::string testingDir =
  774. this->BinaryDir + "/Testing/" + this->CurrentTag + "/" + filename;
  775. return cmSystemTools::FileExists(testingDir);
  776. }
  777. cmCTestGenericHandler* cmCTest::GetInitializedHandler(const char* handler)
  778. {
  779. cmCTest::t_TestingHandlers::iterator it =
  780. this->TestingHandlers.find(handler);
  781. if (it == this->TestingHandlers.end()) {
  782. return nullptr;
  783. }
  784. it->second->Initialize();
  785. return it->second;
  786. }
  787. cmCTestGenericHandler* cmCTest::GetHandler(const char* handler)
  788. {
  789. cmCTest::t_TestingHandlers::iterator it =
  790. this->TestingHandlers.find(handler);
  791. if (it == this->TestingHandlers.end()) {
  792. return nullptr;
  793. }
  794. return it->second;
  795. }
  796. int cmCTest::ExecuteHandler(const char* shandler)
  797. {
  798. cmCTestGenericHandler* handler = this->GetHandler(shandler);
  799. if (!handler) {
  800. return -1;
  801. }
  802. handler->Initialize();
  803. return handler->ProcessHandler();
  804. }
  805. int cmCTest::ProcessSteps()
  806. {
  807. int res = 0;
  808. bool notest = true;
  809. int update_count = 0;
  810. for (Part p = PartStart; notest && p != PartCount; p = Part(p + 1)) {
  811. notest = !this->Parts[p];
  812. }
  813. if (this->Parts[PartUpdate] &&
  814. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  815. cmCTestGenericHandler* uphandler = this->GetHandler("update");
  816. uphandler->SetPersistentOption(
  817. "SourceDirectory",
  818. this->GetCTestConfiguration("SourceDirectory").c_str());
  819. update_count = uphandler->ProcessHandler();
  820. if (update_count < 0) {
  821. res |= cmCTest::UPDATE_ERRORS;
  822. }
  823. }
  824. if (this->TestModel == cmCTest::CONTINUOUS && !update_count) {
  825. return 0;
  826. }
  827. if (this->Parts[PartConfigure] &&
  828. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  829. if (this->GetHandler("configure")->ProcessHandler() < 0) {
  830. res |= cmCTest::CONFIGURE_ERRORS;
  831. }
  832. }
  833. if (this->Parts[PartBuild] &&
  834. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  835. this->UpdateCTestConfiguration();
  836. if (this->GetHandler("build")->ProcessHandler() < 0) {
  837. res |= cmCTest::BUILD_ERRORS;
  838. }
  839. }
  840. if ((this->Parts[PartTest] || notest) &&
  841. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  842. this->UpdateCTestConfiguration();
  843. if (this->GetHandler("test")->ProcessHandler() < 0) {
  844. res |= cmCTest::TEST_ERRORS;
  845. }
  846. }
  847. if (this->Parts[PartCoverage] &&
  848. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  849. this->UpdateCTestConfiguration();
  850. if (this->GetHandler("coverage")->ProcessHandler() < 0) {
  851. res |= cmCTest::COVERAGE_ERRORS;
  852. }
  853. }
  854. if (this->Parts[PartMemCheck] &&
  855. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  856. this->UpdateCTestConfiguration();
  857. if (this->GetHandler("memcheck")->ProcessHandler() < 0) {
  858. res |= cmCTest::MEMORY_ERRORS;
  859. }
  860. }
  861. if (!notest) {
  862. std::string notes_dir = this->BinaryDir + "/Testing/Notes";
  863. if (cmSystemTools::FileIsDirectory(notes_dir)) {
  864. cmsys::Directory d;
  865. d.Load(notes_dir);
  866. unsigned long kk;
  867. for (kk = 0; kk < d.GetNumberOfFiles(); kk++) {
  868. const char* file = d.GetFile(kk);
  869. std::string fullname = notes_dir + "/" + file;
  870. if (cmSystemTools::FileExists(fullname) &&
  871. !cmSystemTools::FileIsDirectory(fullname)) {
  872. if (!this->NotesFiles.empty()) {
  873. this->NotesFiles += ";";
  874. }
  875. this->NotesFiles += fullname;
  876. this->Parts[PartNotes].Enable();
  877. }
  878. }
  879. }
  880. }
  881. if (this->Parts[PartNotes]) {
  882. this->UpdateCTestConfiguration();
  883. if (!this->NotesFiles.empty()) {
  884. this->GenerateNotesFile(this->NotesFiles.c_str());
  885. }
  886. }
  887. if (this->Parts[PartSubmit]) {
  888. this->UpdateCTestConfiguration();
  889. if (this->GetHandler("submit")->ProcessHandler() < 0) {
  890. res |= cmCTest::SUBMIT_ERRORS;
  891. }
  892. }
  893. if (res != 0) {
  894. cmCTestLog(this, ERROR_MESSAGE, "Errors while running CTest" << std::endl);
  895. }
  896. return res;
  897. }
  898. std::string cmCTest::GetTestModelString()
  899. {
  900. if (!this->SpecificTrack.empty()) {
  901. return this->SpecificTrack;
  902. }
  903. switch (this->TestModel) {
  904. case cmCTest::NIGHTLY:
  905. return "Nightly";
  906. case cmCTest::CONTINUOUS:
  907. return "Continuous";
  908. }
  909. return "Experimental";
  910. }
  911. int cmCTest::GetTestModelFromString(const char* str)
  912. {
  913. if (!str) {
  914. return cmCTest::EXPERIMENTAL;
  915. }
  916. std::string rstr = cmSystemTools::LowerCase(str);
  917. if (cmHasLiteralPrefix(rstr, "cont")) {
  918. return cmCTest::CONTINUOUS;
  919. }
  920. if (cmHasLiteralPrefix(rstr, "nigh")) {
  921. return cmCTest::NIGHTLY;
  922. }
  923. return cmCTest::EXPERIMENTAL;
  924. }
  925. //######################################################################
  926. //######################################################################
  927. //######################################################################
  928. //######################################################################
  929. int cmCTest::RunMakeCommand(const char* command, std::string& output,
  930. int* retVal, const char* dir, cmDuration timeout,
  931. std::ostream& ofs, Encoding encoding)
  932. {
  933. // First generate the command and arguments
  934. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  935. if (args.empty()) {
  936. return false;
  937. }
  938. std::vector<const char*> argv;
  939. argv.reserve(args.size() + 1);
  940. for (std::string const& a : args) {
  941. argv.push_back(a.c_str());
  942. }
  943. argv.push_back(nullptr);
  944. output.clear();
  945. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
  946. for (char const* arg : argv) {
  947. if (!arg) {
  948. break;
  949. }
  950. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
  951. }
  952. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
  953. // Now create process object
  954. cmsysProcess* cp = cmsysProcess_New();
  955. cmsysProcess_SetCommand(cp, &*argv.begin());
  956. cmsysProcess_SetWorkingDirectory(cp, dir);
  957. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  958. cmsysProcess_SetTimeout(cp, timeout.count());
  959. cmsysProcess_Execute(cp);
  960. // Initialize tick's
  961. std::string::size_type tick = 0;
  962. std::string::size_type tick_len = 1024;
  963. std::string::size_type tick_line_len = 50;
  964. char* data;
  965. int length;
  966. cmProcessOutput processOutput(encoding);
  967. std::string strdata;
  968. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  969. " Each . represents " << tick_len << " bytes of output"
  970. << std::endl
  971. << " " << std::flush);
  972. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  973. processOutput.DecodeText(data, length, strdata);
  974. for (char& cc : strdata) {
  975. if (cc == 0) {
  976. cc = '\n';
  977. }
  978. }
  979. output.append(strdata);
  980. while (output.size() > (tick * tick_len)) {
  981. tick++;
  982. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
  983. if (tick % tick_line_len == 0 && tick > 0) {
  984. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  985. " Size: " << int((double(output.size()) / 1024.0) + 1)
  986. << "K" << std::endl
  987. << " " << std::flush);
  988. }
  989. }
  990. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  991. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  992. if (ofs) {
  993. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  994. }
  995. }
  996. processOutput.DecodeText(std::string(), strdata);
  997. if (!strdata.empty()) {
  998. output.append(strdata);
  999. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1000. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1001. if (ofs) {
  1002. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  1003. }
  1004. }
  1005. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1006. " Size of output: " << int(double(output.size()) / 1024.0) << "K"
  1007. << std::endl);
  1008. cmsysProcess_WaitForExit(cp, nullptr);
  1009. int result = cmsysProcess_GetState(cp);
  1010. if (result == cmsysProcess_State_Exited) {
  1011. *retVal = cmsysProcess_GetExitValue(cp);
  1012. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1013. "Command exited with the value: " << *retVal << std::endl);
  1014. } else if (result == cmsysProcess_State_Exception) {
  1015. *retVal = cmsysProcess_GetExitException(cp);
  1016. cmCTestLog(this, WARNING,
  1017. "There was an exception: " << *retVal << std::endl);
  1018. } else if (result == cmsysProcess_State_Expired) {
  1019. cmCTestLog(this, WARNING, "There was a timeout" << std::endl);
  1020. } else if (result == cmsysProcess_State_Error) {
  1021. output += "\n*** ERROR executing: ";
  1022. output += cmsysProcess_GetErrorString(cp);
  1023. output += "\n***The build process failed.";
  1024. cmCTestLog(this, ERROR_MESSAGE,
  1025. "There was an error: " << cmsysProcess_GetErrorString(cp)
  1026. << std::endl);
  1027. }
  1028. cmsysProcess_Delete(cp);
  1029. return result;
  1030. }
  1031. //######################################################################
  1032. //######################################################################
  1033. //######################################################################
  1034. //######################################################################
  1035. int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
  1036. int* retVal, std::ostream* log, cmDuration testTimeOut,
  1037. std::vector<std::string>* environment, Encoding encoding)
  1038. {
  1039. bool modifyEnv = (environment && !environment->empty());
  1040. // determine how much time we have
  1041. cmDuration timeout = this->GetRemainingTimeAllowed();
  1042. if (timeout != cmCTest::MaxDuration()) {
  1043. timeout -= std::chrono::minutes(2);
  1044. }
  1045. if (this->TimeOut > cmDuration::zero() && this->TimeOut < timeout) {
  1046. timeout = this->TimeOut;
  1047. }
  1048. if (testTimeOut > cmDuration::zero() &&
  1049. testTimeOut < this->GetRemainingTimeAllowed()) {
  1050. timeout = testTimeOut;
  1051. }
  1052. // always have at least 1 second if we got to here
  1053. if (timeout <= cmDuration::zero()) {
  1054. timeout = std::chrono::seconds(1);
  1055. }
  1056. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1057. "Test timeout computed to be: "
  1058. << (timeout == cmCTest::MaxDuration()
  1059. ? std::string("infinite")
  1060. : std::to_string(cmDurationTo<unsigned int>(timeout)))
  1061. << "\n");
  1062. if (cmSystemTools::SameFile(argv[0], cmSystemTools::GetCTestCommand()) &&
  1063. !this->ForceNewCTestProcess) {
  1064. cmCTest inst;
  1065. inst.ConfigType = this->ConfigType;
  1066. inst.TimeOut = timeout;
  1067. // Capture output of the child ctest.
  1068. std::ostringstream oss;
  1069. inst.SetStreams(&oss, &oss);
  1070. std::vector<std::string> args;
  1071. for (char const* i : argv) {
  1072. if (i) {
  1073. // make sure we pass the timeout in for any build and test
  1074. // invocations. Since --build-generator is required this is a
  1075. // good place to check for it, and to add the arguments in
  1076. if (strcmp(i, "--build-generator") == 0 &&
  1077. timeout != cmCTest::MaxDuration() &&
  1078. timeout > cmDuration::zero()) {
  1079. args.push_back("--test-timeout");
  1080. std::ostringstream msg;
  1081. msg << cmDurationTo<unsigned int>(timeout);
  1082. args.push_back(msg.str());
  1083. }
  1084. args.push_back(i);
  1085. }
  1086. }
  1087. if (log) {
  1088. *log << "* Run internal CTest" << std::endl;
  1089. }
  1090. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1091. if (modifyEnv) {
  1092. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1093. cmSystemTools::AppendEnv(*environment);
  1094. }
  1095. *retVal = inst.Run(args, output);
  1096. if (output) {
  1097. *output += oss.str();
  1098. }
  1099. if (log && output) {
  1100. *log << *output;
  1101. }
  1102. if (output) {
  1103. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1104. "Internal cmCTest object used to run test." << std::endl
  1105. << *output
  1106. << std::endl);
  1107. }
  1108. return cmsysProcess_State_Exited;
  1109. }
  1110. std::vector<char> tempOutput;
  1111. if (output) {
  1112. output->clear();
  1113. }
  1114. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1115. if (modifyEnv) {
  1116. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1117. cmSystemTools::AppendEnv(*environment);
  1118. }
  1119. cmsysProcess* cp = cmsysProcess_New();
  1120. cmsysProcess_SetCommand(cp, &*argv.begin());
  1121. cmCTestLog(this, DEBUG, "Command is: " << argv[0] << std::endl);
  1122. if (cmSystemTools::GetRunCommandHideConsole()) {
  1123. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  1124. }
  1125. cmsysProcess_SetTimeout(cp, timeout.count());
  1126. cmsysProcess_Execute(cp);
  1127. char* data;
  1128. int length;
  1129. cmProcessOutput processOutput(encoding);
  1130. std::string strdata;
  1131. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  1132. processOutput.DecodeText(data, length, strdata);
  1133. if (output) {
  1134. tempOutput.insert(tempOutput.end(), data, data + length);
  1135. }
  1136. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1137. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1138. if (log) {
  1139. log->write(strdata.c_str(), strdata.size());
  1140. }
  1141. }
  1142. processOutput.DecodeText(std::string(), strdata);
  1143. if (!strdata.empty()) {
  1144. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1145. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1146. if (log) {
  1147. log->write(strdata.c_str(), strdata.size());
  1148. }
  1149. }
  1150. cmsysProcess_WaitForExit(cp, nullptr);
  1151. processOutput.DecodeText(tempOutput, tempOutput);
  1152. if (output && tempOutput.begin() != tempOutput.end()) {
  1153. output->append(&*tempOutput.begin(), tempOutput.size());
  1154. }
  1155. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1156. "-- Process completed" << std::endl);
  1157. int result = cmsysProcess_GetState(cp);
  1158. if (result == cmsysProcess_State_Exited) {
  1159. *retVal = cmsysProcess_GetExitValue(cp);
  1160. if (*retVal != 0 && this->OutputTestOutputOnTestFailure) {
  1161. OutputTestErrors(tempOutput);
  1162. }
  1163. } else if (result == cmsysProcess_State_Exception) {
  1164. if (this->OutputTestOutputOnTestFailure) {
  1165. OutputTestErrors(tempOutput);
  1166. }
  1167. *retVal = cmsysProcess_GetExitException(cp);
  1168. std::string outerr = "\n*** Exception executing: ";
  1169. outerr += cmsysProcess_GetExceptionString(cp);
  1170. if (output) {
  1171. *output += outerr;
  1172. }
  1173. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1174. outerr << std::endl
  1175. << std::flush);
  1176. } else if (result == cmsysProcess_State_Error) {
  1177. std::string outerr = "\n*** ERROR executing: ";
  1178. outerr += cmsysProcess_GetErrorString(cp);
  1179. if (output) {
  1180. *output += outerr;
  1181. }
  1182. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1183. outerr << std::endl
  1184. << std::flush);
  1185. }
  1186. cmsysProcess_Delete(cp);
  1187. return result;
  1188. }
  1189. std::string cmCTest::SafeBuildIdField(const std::string& value)
  1190. {
  1191. std::string safevalue(value);
  1192. if (!safevalue.empty()) {
  1193. // Disallow non-filename and non-space whitespace characters.
  1194. // If they occur, replace them with ""
  1195. //
  1196. const char* disallowed = "\\:*?\"<>|\n\r\t\f\v";
  1197. if (safevalue.find_first_of(disallowed) != std::string::npos) {
  1198. std::string::size_type i = 0;
  1199. std::string::size_type n = strlen(disallowed);
  1200. char replace[2];
  1201. replace[1] = 0;
  1202. for (i = 0; i < n; ++i) {
  1203. replace[0] = disallowed[i];
  1204. cmSystemTools::ReplaceString(safevalue, replace, "");
  1205. }
  1206. }
  1207. }
  1208. if (safevalue.empty()) {
  1209. safevalue = "(empty)";
  1210. }
  1211. return safevalue;
  1212. }
  1213. void cmCTest::StartXML(cmXMLWriter& xml, bool append)
  1214. {
  1215. if (this->CurrentTag.empty()) {
  1216. cmCTestLog(this, ERROR_MESSAGE,
  1217. "Current Tag empty, this may mean"
  1218. " NightlStartTime was not set correctly."
  1219. << std::endl);
  1220. cmSystemTools::SetFatalErrorOccured();
  1221. }
  1222. // find out about the system
  1223. cmsys::SystemInformation info;
  1224. info.RunCPUCheck();
  1225. info.RunOSCheck();
  1226. info.RunMemoryCheck();
  1227. std::string buildname =
  1228. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1229. std::string stamp = cmCTest::SafeBuildIdField(this->CurrentTag + "-" +
  1230. this->GetTestModelString());
  1231. std::string site =
  1232. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("Site"));
  1233. xml.StartDocument();
  1234. xml.StartElement("Site");
  1235. xml.Attribute("BuildName", buildname);
  1236. xml.BreakAttributes();
  1237. xml.Attribute("BuildStamp", stamp);
  1238. xml.Attribute("Name", site);
  1239. xml.Attribute("Generator",
  1240. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1241. if (append) {
  1242. xml.Attribute("Append", "true");
  1243. }
  1244. xml.Attribute("CompilerName", this->GetCTestConfiguration("Compiler"));
  1245. xml.Attribute("CompilerVersion",
  1246. this->GetCTestConfiguration("CompilerVersion"));
  1247. xml.Attribute("OSName", info.GetOSName());
  1248. xml.Attribute("Hostname", info.GetHostname());
  1249. xml.Attribute("OSRelease", info.GetOSRelease());
  1250. xml.Attribute("OSVersion", info.GetOSVersion());
  1251. xml.Attribute("OSPlatform", info.GetOSPlatform());
  1252. xml.Attribute("Is64Bits", info.Is64Bits());
  1253. xml.Attribute("VendorString", info.GetVendorString());
  1254. xml.Attribute("VendorID", info.GetVendorID());
  1255. xml.Attribute("FamilyID", info.GetFamilyID());
  1256. xml.Attribute("ModelID", info.GetModelID());
  1257. xml.Attribute("ProcessorCacheSize", info.GetProcessorCacheSize());
  1258. xml.Attribute("NumberOfLogicalCPU", info.GetNumberOfLogicalCPU());
  1259. xml.Attribute("NumberOfPhysicalCPU", info.GetNumberOfPhysicalCPU());
  1260. xml.Attribute("TotalVirtualMemory", info.GetTotalVirtualMemory());
  1261. xml.Attribute("TotalPhysicalMemory", info.GetTotalPhysicalMemory());
  1262. xml.Attribute("LogicalProcessorsPerPhysical",
  1263. info.GetLogicalProcessorsPerPhysical());
  1264. xml.Attribute("ProcessorClockFrequency", info.GetProcessorClockFrequency());
  1265. std::string changeId = this->GetCTestConfiguration("ChangeId");
  1266. if (!changeId.empty()) {
  1267. xml.Attribute("ChangeId", changeId);
  1268. }
  1269. this->AddSiteProperties(xml);
  1270. }
  1271. void cmCTest::AddSiteProperties(cmXMLWriter& xml)
  1272. {
  1273. cmCTestScriptHandler* ch =
  1274. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1275. cmake* cm = ch->GetCMake();
  1276. // if no CMake then this is the old style script and props like
  1277. // this will not work anyway.
  1278. if (!cm) {
  1279. return;
  1280. }
  1281. // This code should go when cdash is changed to use labels only
  1282. const char* subproject = cm->GetState()->GetGlobalProperty("SubProject");
  1283. if (subproject) {
  1284. xml.StartElement("Subproject");
  1285. xml.Attribute("name", subproject);
  1286. const char* labels =
  1287. ch->GetCMake()->GetState()->GetGlobalProperty("SubProjectLabels");
  1288. if (labels) {
  1289. xml.StartElement("Labels");
  1290. std::string l = labels;
  1291. std::vector<std::string> args;
  1292. cmSystemTools::ExpandListArgument(l, args);
  1293. for (std::string const& i : args) {
  1294. xml.Element("Label", i);
  1295. }
  1296. xml.EndElement();
  1297. }
  1298. xml.EndElement();
  1299. }
  1300. // This code should stay when cdash only does label based sub-projects
  1301. const char* label = cm->GetState()->GetGlobalProperty("Label");
  1302. if (label) {
  1303. xml.StartElement("Labels");
  1304. xml.Element("Label", label);
  1305. xml.EndElement();
  1306. }
  1307. }
  1308. void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
  1309. {
  1310. for (std::string const& subproj : this->GetLabelsForSubprojects()) {
  1311. xml.StartElement("Subproject");
  1312. xml.Attribute("name", subproj);
  1313. xml.Element("Label", subproj);
  1314. xml.EndElement(); // Subproject
  1315. }
  1316. }
  1317. std::vector<std::string> cmCTest::GetLabelsForSubprojects()
  1318. {
  1319. std::string labelsForSubprojects =
  1320. this->GetCTestConfiguration("LabelsForSubprojects");
  1321. std::vector<std::string> subprojects;
  1322. cmSystemTools::ExpandListArgument(labelsForSubprojects, subprojects);
  1323. // sort the array
  1324. std::sort(subprojects.begin(), subprojects.end());
  1325. // remove duplicates
  1326. std::vector<std::string>::iterator new_end =
  1327. std::unique(subprojects.begin(), subprojects.end());
  1328. subprojects.erase(new_end, subprojects.end());
  1329. return subprojects;
  1330. }
  1331. void cmCTest::EndXML(cmXMLWriter& xml)
  1332. {
  1333. xml.EndElement(); // Site
  1334. xml.EndDocument();
  1335. }
  1336. int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
  1337. const cmCTest::VectorOfStrings& files)
  1338. {
  1339. std::string buildname =
  1340. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1341. xml.StartDocument();
  1342. xml.ProcessingInstruction("xml-stylesheet",
  1343. "type=\"text/xsl\" "
  1344. "href=\"Dart/Source/Server/XSL/Build.xsl "
  1345. "<file:///Dart/Source/Server/XSL/Build.xsl> \"");
  1346. xml.StartElement("Site");
  1347. xml.Attribute("BuildName", buildname);
  1348. xml.Attribute("BuildStamp",
  1349. this->CurrentTag + "-" + this->GetTestModelString());
  1350. xml.Attribute("Name", this->GetCTestConfiguration("Site"));
  1351. xml.Attribute("Generator",
  1352. std::string("ctest") + cmVersion::GetCMakeVersion());
  1353. this->AddSiteProperties(xml);
  1354. xml.StartElement("Notes");
  1355. for (std::string const& file : files) {
  1356. cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
  1357. std::string note_time = this->CurrentTime();
  1358. xml.StartElement("Note");
  1359. xml.Attribute("Name", file);
  1360. xml.Element("Time", std::chrono::system_clock::now());
  1361. xml.Element("DateTime", note_time);
  1362. xml.StartElement("Text");
  1363. cmsys::ifstream ifs(file.c_str());
  1364. if (ifs) {
  1365. std::string line;
  1366. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1367. xml.Content(line);
  1368. xml.Content("\n");
  1369. }
  1370. ifs.close();
  1371. } else {
  1372. xml.Content("Problem reading file: " + file + "\n");
  1373. cmCTestLog(this, ERROR_MESSAGE,
  1374. "Problem reading file: " << file << " while creating notes"
  1375. << std::endl);
  1376. }
  1377. xml.EndElement(); // Text
  1378. xml.EndElement(); // Note
  1379. }
  1380. xml.EndElement(); // Notes
  1381. xml.EndElement(); // Site
  1382. xml.EndDocument();
  1383. return 1;
  1384. }
  1385. int cmCTest::GenerateNotesFile(const VectorOfStrings& files)
  1386. {
  1387. cmGeneratedFileStream ofs;
  1388. if (!this->OpenOutputFile(this->CurrentTag, "Notes.xml", ofs)) {
  1389. cmCTestLog(this, ERROR_MESSAGE, "Cannot open notes file" << std::endl);
  1390. return 1;
  1391. }
  1392. cmXMLWriter xml(ofs);
  1393. this->GenerateCTestNotesOutput(xml, files);
  1394. return 0;
  1395. }
  1396. int cmCTest::GenerateNotesFile(const char* cfiles)
  1397. {
  1398. if (!cfiles) {
  1399. return 1;
  1400. }
  1401. VectorOfStrings files;
  1402. cmCTestLog(this, OUTPUT, "Create notes file" << std::endl);
  1403. files = cmSystemTools::SplitString(cfiles, ';');
  1404. if (files.empty()) {
  1405. return 1;
  1406. }
  1407. return this->GenerateNotesFile(files);
  1408. }
  1409. int cmCTest::GenerateDoneFile()
  1410. {
  1411. cmGeneratedFileStream ofs;
  1412. if (!this->OpenOutputFile(this->CurrentTag, "Done.xml", ofs)) {
  1413. cmCTestLog(this, ERROR_MESSAGE, "Cannot open done file" << std::endl);
  1414. return 1;
  1415. }
  1416. cmXMLWriter xml(ofs);
  1417. xml.StartDocument();
  1418. xml.StartElement("Done");
  1419. xml.Element("buildId", this->BuildID);
  1420. xml.Element("time", std::chrono::system_clock::now());
  1421. xml.EndElement(); // Done
  1422. xml.EndDocument();
  1423. return 0;
  1424. }
  1425. std::string cmCTest::Base64GzipEncodeFile(std::string const& file)
  1426. {
  1427. std::string tarFile = file + "_temp.tar.gz";
  1428. std::vector<std::string> files;
  1429. files.push_back(file);
  1430. if (!cmSystemTools::CreateTar(tarFile.c_str(), files,
  1431. cmSystemTools::TarCompressGZip, false)) {
  1432. cmCTestLog(this, ERROR_MESSAGE,
  1433. "Error creating tar while "
  1434. "encoding file: "
  1435. << file << std::endl);
  1436. return "";
  1437. }
  1438. std::string base64 = this->Base64EncodeFile(tarFile);
  1439. cmSystemTools::RemoveFile(tarFile);
  1440. return base64;
  1441. }
  1442. std::string cmCTest::Base64EncodeFile(std::string const& file)
  1443. {
  1444. size_t const len = cmSystemTools::FileLength(file);
  1445. cmsys::ifstream ifs(file.c_str(),
  1446. std::ios::in
  1447. #ifdef _WIN32
  1448. | std::ios::binary
  1449. #endif
  1450. );
  1451. std::vector<char> file_buffer(len + 1);
  1452. ifs.read(&file_buffer[0], len);
  1453. ifs.close();
  1454. std::vector<char> encoded_buffer((len * 3) / 2 + 5);
  1455. size_t const rlen = cmsysBase64_Encode(
  1456. reinterpret_cast<unsigned char*>(&file_buffer[0]), len,
  1457. reinterpret_cast<unsigned char*>(&encoded_buffer[0]), 1);
  1458. return std::string(&encoded_buffer[0], rlen);
  1459. }
  1460. bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
  1461. {
  1462. for (std::string const& file : files) {
  1463. if (!cmSystemTools::FileExists(file)) {
  1464. cmCTestLog(this, ERROR_MESSAGE,
  1465. "Cannot find extra file: " << file << " to submit."
  1466. << std::endl;);
  1467. return false;
  1468. }
  1469. this->AddSubmitFile(PartExtraFiles, file.c_str());
  1470. }
  1471. return true;
  1472. }
  1473. bool cmCTest::SubmitExtraFiles(const char* cfiles)
  1474. {
  1475. if (!cfiles) {
  1476. return true;
  1477. }
  1478. VectorOfStrings files;
  1479. cmCTestLog(this, OUTPUT, "Submit extra files" << std::endl);
  1480. files = cmSystemTools::SplitString(cfiles, ';');
  1481. if (files.empty()) {
  1482. return true;
  1483. }
  1484. return this->SubmitExtraFiles(files);
  1485. }
  1486. // for a -D argument convert the next argument into
  1487. // the proper list of dashboard steps via SetTest
  1488. bool cmCTest::AddTestsForDashboardType(std::string& targ)
  1489. {
  1490. if (targ == "Experimental") {
  1491. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1492. this->SetTest("Start");
  1493. this->SetTest("Configure");
  1494. this->SetTest("Build");
  1495. this->SetTest("Test");
  1496. this->SetTest("Coverage");
  1497. this->SetTest("Submit");
  1498. } else if (targ == "ExperimentalStart") {
  1499. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1500. this->SetTest("Start");
  1501. } else if (targ == "ExperimentalUpdate") {
  1502. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1503. this->SetTest("Update");
  1504. } else if (targ == "ExperimentalConfigure") {
  1505. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1506. this->SetTest("Configure");
  1507. } else if (targ == "ExperimentalBuild") {
  1508. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1509. this->SetTest("Build");
  1510. } else if (targ == "ExperimentalTest") {
  1511. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1512. this->SetTest("Test");
  1513. } else if (targ == "ExperimentalMemCheck" || targ == "ExperimentalPurify") {
  1514. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1515. this->SetTest("MemCheck");
  1516. } else if (targ == "ExperimentalCoverage") {
  1517. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1518. this->SetTest("Coverage");
  1519. } else if (targ == "ExperimentalSubmit") {
  1520. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1521. this->SetTest("Submit");
  1522. } else if (targ == "Continuous") {
  1523. this->SetTestModel(cmCTest::CONTINUOUS);
  1524. this->SetTest("Start");
  1525. this->SetTest("Update");
  1526. this->SetTest("Configure");
  1527. this->SetTest("Build");
  1528. this->SetTest("Test");
  1529. this->SetTest("Coverage");
  1530. this->SetTest("Submit");
  1531. } else if (targ == "ContinuousStart") {
  1532. this->SetTestModel(cmCTest::CONTINUOUS);
  1533. this->SetTest("Start");
  1534. } else if (targ == "ContinuousUpdate") {
  1535. this->SetTestModel(cmCTest::CONTINUOUS);
  1536. this->SetTest("Update");
  1537. } else if (targ == "ContinuousConfigure") {
  1538. this->SetTestModel(cmCTest::CONTINUOUS);
  1539. this->SetTest("Configure");
  1540. } else if (targ == "ContinuousBuild") {
  1541. this->SetTestModel(cmCTest::CONTINUOUS);
  1542. this->SetTest("Build");
  1543. } else if (targ == "ContinuousTest") {
  1544. this->SetTestModel(cmCTest::CONTINUOUS);
  1545. this->SetTest("Test");
  1546. } else if (targ == "ContinuousMemCheck" || targ == "ContinuousPurify") {
  1547. this->SetTestModel(cmCTest::CONTINUOUS);
  1548. this->SetTest("MemCheck");
  1549. } else if (targ == "ContinuousCoverage") {
  1550. this->SetTestModel(cmCTest::CONTINUOUS);
  1551. this->SetTest("Coverage");
  1552. } else if (targ == "ContinuousSubmit") {
  1553. this->SetTestModel(cmCTest::CONTINUOUS);
  1554. this->SetTest("Submit");
  1555. } else if (targ == "Nightly") {
  1556. this->SetTestModel(cmCTest::NIGHTLY);
  1557. this->SetTest("Start");
  1558. this->SetTest("Update");
  1559. this->SetTest("Configure");
  1560. this->SetTest("Build");
  1561. this->SetTest("Test");
  1562. this->SetTest("Coverage");
  1563. this->SetTest("Submit");
  1564. } else if (targ == "NightlyStart") {
  1565. this->SetTestModel(cmCTest::NIGHTLY);
  1566. this->SetTest("Start");
  1567. } else if (targ == "NightlyUpdate") {
  1568. this->SetTestModel(cmCTest::NIGHTLY);
  1569. this->SetTest("Update");
  1570. } else if (targ == "NightlyConfigure") {
  1571. this->SetTestModel(cmCTest::NIGHTLY);
  1572. this->SetTest("Configure");
  1573. } else if (targ == "NightlyBuild") {
  1574. this->SetTestModel(cmCTest::NIGHTLY);
  1575. this->SetTest("Build");
  1576. } else if (targ == "NightlyTest") {
  1577. this->SetTestModel(cmCTest::NIGHTLY);
  1578. this->SetTest("Test");
  1579. } else if (targ == "NightlyMemCheck" || targ == "NightlyPurify") {
  1580. this->SetTestModel(cmCTest::NIGHTLY);
  1581. this->SetTest("MemCheck");
  1582. } else if (targ == "NightlyCoverage") {
  1583. this->SetTestModel(cmCTest::NIGHTLY);
  1584. this->SetTest("Coverage");
  1585. } else if (targ == "NightlySubmit") {
  1586. this->SetTestModel(cmCTest::NIGHTLY);
  1587. this->SetTest("Submit");
  1588. } else if (targ == "MemoryCheck") {
  1589. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1590. this->SetTest("Start");
  1591. this->SetTest("Configure");
  1592. this->SetTest("Build");
  1593. this->SetTest("MemCheck");
  1594. this->SetTest("Coverage");
  1595. this->SetTest("Submit");
  1596. } else if (targ == "NightlyMemoryCheck") {
  1597. this->SetTestModel(cmCTest::NIGHTLY);
  1598. this->SetTest("Start");
  1599. this->SetTest("Update");
  1600. this->SetTest("Configure");
  1601. this->SetTest("Build");
  1602. this->SetTest("MemCheck");
  1603. this->SetTest("Coverage");
  1604. this->SetTest("Submit");
  1605. } else {
  1606. return false;
  1607. }
  1608. return true;
  1609. }
  1610. void cmCTest::ErrorMessageUnknownDashDValue(std::string& val)
  1611. {
  1612. cmCTestLog(this, ERROR_MESSAGE,
  1613. "CTest -D called with incorrect option: " << val << std::endl);
  1614. cmCTestLog(
  1615. this, ERROR_MESSAGE,
  1616. "Available options are:"
  1617. << std::endl
  1618. << " ctest -D Continuous" << std::endl
  1619. << " ctest -D Continuous(Start|Update|Configure|Build)" << std::endl
  1620. << " ctest -D Continuous(Test|Coverage|MemCheck|Submit)" << std::endl
  1621. << " ctest -D Experimental" << std::endl
  1622. << " ctest -D Experimental(Start|Update|Configure|Build)" << std::endl
  1623. << " ctest -D Experimental(Test|Coverage|MemCheck|Submit)" << std::endl
  1624. << " ctest -D Nightly" << std::endl
  1625. << " ctest -D Nightly(Start|Update|Configure|Build)" << std::endl
  1626. << " ctest -D Nightly(Test|Coverage|MemCheck|Submit)" << std::endl
  1627. << " ctest -D NightlyMemoryCheck" << std::endl);
  1628. }
  1629. bool cmCTest::CheckArgument(const std::string& arg, const char* varg1,
  1630. const char* varg2)
  1631. {
  1632. return (varg1 && arg == varg1) || (varg2 && arg == varg2);
  1633. }
  1634. // Processes one command line argument (and its arguments if any)
  1635. // for many simple options and then returns
  1636. bool cmCTest::HandleCommandLineArguments(size_t& i,
  1637. std::vector<std::string>& args,
  1638. std::string& errormsg)
  1639. {
  1640. std::string arg = args[i];
  1641. if (this->CheckArgument(arg, "-F")) {
  1642. this->Failover = true;
  1643. }
  1644. if (this->CheckArgument(arg, "-j", "--parallel") && i < args.size() - 1) {
  1645. i++;
  1646. int plevel = atoi(args[i].c_str());
  1647. this->SetParallelLevel(plevel);
  1648. this->ParallelLevelSetInCli = true;
  1649. } else if (arg.find("-j") == 0) {
  1650. int plevel = atoi(arg.substr(2).c_str());
  1651. this->SetParallelLevel(plevel);
  1652. this->ParallelLevelSetInCli = true;
  1653. }
  1654. if (this->CheckArgument(arg, "--repeat-until-fail")) {
  1655. if (i >= args.size() - 1) {
  1656. errormsg = "'--repeat-until-fail' requires an argument";
  1657. return false;
  1658. }
  1659. i++;
  1660. long repeat = 1;
  1661. if (!cmSystemTools::StringToLong(args[i].c_str(), &repeat)) {
  1662. errormsg =
  1663. "'--repeat-until-fail' given non-integer value '" + args[i] + "'";
  1664. return false;
  1665. }
  1666. this->RepeatTests = static_cast<int>(repeat);
  1667. if (repeat > 1) {
  1668. this->RepeatUntilFail = true;
  1669. }
  1670. }
  1671. if (this->CheckArgument(arg, "--test-load") && i < args.size() - 1) {
  1672. i++;
  1673. unsigned long load;
  1674. if (cmSystemTools::StringToULong(args[i].c_str(), &load)) {
  1675. this->SetTestLoad(load);
  1676. } else {
  1677. cmCTestLog(this, WARNING,
  1678. "Invalid value for 'Test Load' : " << args[i] << std::endl);
  1679. }
  1680. }
  1681. if (this->CheckArgument(arg, "--no-compress-output")) {
  1682. this->CompressTestOutput = false;
  1683. }
  1684. if (this->CheckArgument(arg, "--print-labels")) {
  1685. this->PrintLabels = true;
  1686. }
  1687. if (this->CheckArgument(arg, "--http1.0")) {
  1688. this->UseHTTP10 = true;
  1689. }
  1690. if (this->CheckArgument(arg, "--timeout") && i < args.size() - 1) {
  1691. i++;
  1692. auto timeout = cmDuration(atof(args[i].c_str()));
  1693. this->GlobalTimeout = timeout;
  1694. }
  1695. if (this->CheckArgument(arg, "--stop-time") && i < args.size() - 1) {
  1696. i++;
  1697. this->SetStopTime(args[i]);
  1698. }
  1699. if (this->CheckArgument(arg, "-C", "--build-config") &&
  1700. i < args.size() - 1) {
  1701. i++;
  1702. this->SetConfigType(args[i].c_str());
  1703. }
  1704. if (this->CheckArgument(arg, "--debug")) {
  1705. this->Debug = true;
  1706. this->ShowLineNumbers = true;
  1707. }
  1708. if (this->CheckArgument(arg, "--track") && i < args.size() - 1) {
  1709. i++;
  1710. this->SpecificTrack = args[i];
  1711. }
  1712. if (this->CheckArgument(arg, "--show-line-numbers")) {
  1713. this->ShowLineNumbers = true;
  1714. }
  1715. if (this->CheckArgument(arg, "--no-label-summary")) {
  1716. this->LabelSummary = false;
  1717. }
  1718. if (this->CheckArgument(arg, "--no-subproject-summary")) {
  1719. this->SubprojectSummary = false;
  1720. }
  1721. if (this->CheckArgument(arg, "-Q", "--quiet")) {
  1722. this->Quiet = true;
  1723. }
  1724. if (this->CheckArgument(arg, "--progress")) {
  1725. this->TestProgressOutput = true;
  1726. }
  1727. if (this->CheckArgument(arg, "-V", "--verbose")) {
  1728. this->Verbose = true;
  1729. }
  1730. if (this->CheckArgument(arg, "-VV", "--extra-verbose")) {
  1731. this->ExtraVerbose = true;
  1732. this->Verbose = true;
  1733. }
  1734. if (this->CheckArgument(arg, "--output-on-failure")) {
  1735. this->OutputTestOutputOnTestFailure = true;
  1736. }
  1737. if (this->CheckArgument(arg, "--test-output-size-passed") &&
  1738. i < args.size() - 1) {
  1739. i++;
  1740. long outputSize;
  1741. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1742. if (cmCTestTestHandler* pCTestTestHandler =
  1743. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1744. pCTestTestHandler->SetTestOutputSizePassed(int(outputSize));
  1745. }
  1746. } else {
  1747. cmCTestLog(this, WARNING,
  1748. "Invalid value for '--test-output-size-passed': " << args[i]
  1749. << "\n");
  1750. }
  1751. }
  1752. if (this->CheckArgument(arg, "--test-output-size-failed") &&
  1753. i < args.size() - 1) {
  1754. i++;
  1755. long outputSize;
  1756. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1757. if (cmCTestTestHandler* pCTestTestHandler =
  1758. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1759. pCTestTestHandler->SetTestOutputSizeFailed(int(outputSize));
  1760. }
  1761. } else {
  1762. cmCTestLog(this, WARNING,
  1763. "Invalid value for '--test-output-size-failed': " << args[i]
  1764. << "\n");
  1765. }
  1766. }
  1767. if (this->CheckArgument(arg, "-N", "--show-only")) {
  1768. this->ShowOnly = true;
  1769. }
  1770. if (cmSystemTools::StringStartsWith(arg.c_str(), "--show-only=")) {
  1771. this->ShowOnly = true;
  1772. // Check if a specific format is requested. Defaults to human readable
  1773. // text.
  1774. std::string argWithFormat = "--show-only=";
  1775. std::string format = arg.substr(argWithFormat.length());
  1776. if (format == "json-v1") {
  1777. // Force quiet mode so the only output is the json object model.
  1778. this->Quiet = true;
  1779. this->OutputAsJson = true;
  1780. this->OutputAsJsonVersion = 1;
  1781. }
  1782. }
  1783. if (this->CheckArgument(arg, "-O", "--output-log") && i < args.size() - 1) {
  1784. i++;
  1785. this->SetOutputLogFileName(args[i].c_str());
  1786. }
  1787. if (this->CheckArgument(arg, "--tomorrow-tag")) {
  1788. this->TomorrowTag = true;
  1789. }
  1790. if (this->CheckArgument(arg, "--force-new-ctest-process")) {
  1791. this->ForceNewCTestProcess = true;
  1792. }
  1793. if (this->CheckArgument(arg, "-W", "--max-width") && i < args.size() - 1) {
  1794. i++;
  1795. this->MaxTestNameWidth = atoi(args[i].c_str());
  1796. }
  1797. if (this->CheckArgument(arg, "--interactive-debug-mode") &&
  1798. i < args.size() - 1) {
  1799. i++;
  1800. this->InteractiveDebugMode = cmSystemTools::IsOn(args[i]);
  1801. }
  1802. if (this->CheckArgument(arg, "--submit-index") && i < args.size() - 1) {
  1803. i++;
  1804. this->SubmitIndex = atoi(args[i].c_str());
  1805. if (this->SubmitIndex < 0) {
  1806. this->SubmitIndex = 0;
  1807. }
  1808. }
  1809. if (this->CheckArgument(arg, "--overwrite") && i < args.size() - 1) {
  1810. i++;
  1811. this->AddCTestConfigurationOverwrite(args[i]);
  1812. }
  1813. if (this->CheckArgument(arg, "-A", "--add-notes") && i < args.size() - 1) {
  1814. this->ProduceXML = true;
  1815. this->SetTest("Notes");
  1816. i++;
  1817. this->SetNotesFiles(args[i].c_str());
  1818. }
  1819. // options that control what tests are run
  1820. if (this->CheckArgument(arg, "-I", "--tests-information") &&
  1821. i < args.size() - 1) {
  1822. i++;
  1823. this->GetHandler("test")->SetPersistentOption("TestsToRunInformation",
  1824. args[i].c_str());
  1825. this->GetHandler("memcheck")
  1826. ->SetPersistentOption("TestsToRunInformation", args[i].c_str());
  1827. }
  1828. if (this->CheckArgument(arg, "-U", "--union")) {
  1829. this->GetHandler("test")->SetPersistentOption("UseUnion", "true");
  1830. this->GetHandler("memcheck")->SetPersistentOption("UseUnion", "true");
  1831. }
  1832. if (this->CheckArgument(arg, "-R", "--tests-regex") && i < args.size() - 1) {
  1833. i++;
  1834. this->GetHandler("test")->SetPersistentOption("IncludeRegularExpression",
  1835. args[i].c_str());
  1836. this->GetHandler("memcheck")
  1837. ->SetPersistentOption("IncludeRegularExpression", args[i].c_str());
  1838. }
  1839. if (this->CheckArgument(arg, "-L", "--label-regex") && i < args.size() - 1) {
  1840. i++;
  1841. this->GetHandler("test")->SetPersistentOption("LabelRegularExpression",
  1842. args[i].c_str());
  1843. this->GetHandler("memcheck")
  1844. ->SetPersistentOption("LabelRegularExpression", args[i].c_str());
  1845. }
  1846. if (this->CheckArgument(arg, "-LE", "--label-exclude") &&
  1847. i < args.size() - 1) {
  1848. i++;
  1849. this->GetHandler("test")->SetPersistentOption(
  1850. "ExcludeLabelRegularExpression", args[i].c_str());
  1851. this->GetHandler("memcheck")
  1852. ->SetPersistentOption("ExcludeLabelRegularExpression", args[i].c_str());
  1853. }
  1854. if (this->CheckArgument(arg, "-E", "--exclude-regex") &&
  1855. i < args.size() - 1) {
  1856. i++;
  1857. this->GetHandler("test")->SetPersistentOption("ExcludeRegularExpression",
  1858. args[i].c_str());
  1859. this->GetHandler("memcheck")
  1860. ->SetPersistentOption("ExcludeRegularExpression", args[i].c_str());
  1861. }
  1862. if (this->CheckArgument(arg, "-FA", "--fixture-exclude-any") &&
  1863. i < args.size() - 1) {
  1864. i++;
  1865. this->GetHandler("test")->SetPersistentOption(
  1866. "ExcludeFixtureRegularExpression", args[i].c_str());
  1867. this->GetHandler("memcheck")
  1868. ->SetPersistentOption("ExcludeFixtureRegularExpression",
  1869. args[i].c_str());
  1870. }
  1871. if (this->CheckArgument(arg, "-FS", "--fixture-exclude-setup") &&
  1872. i < args.size() - 1) {
  1873. i++;
  1874. this->GetHandler("test")->SetPersistentOption(
  1875. "ExcludeFixtureSetupRegularExpression", args[i].c_str());
  1876. this->GetHandler("memcheck")
  1877. ->SetPersistentOption("ExcludeFixtureSetupRegularExpression",
  1878. args[i].c_str());
  1879. }
  1880. if (this->CheckArgument(arg, "-FC", "--fixture-exclude-cleanup") &&
  1881. i < args.size() - 1) {
  1882. i++;
  1883. this->GetHandler("test")->SetPersistentOption(
  1884. "ExcludeFixtureCleanupRegularExpression", args[i].c_str());
  1885. this->GetHandler("memcheck")
  1886. ->SetPersistentOption("ExcludeFixtureCleanupRegularExpression",
  1887. args[i].c_str());
  1888. }
  1889. if (this->CheckArgument(arg, "--rerun-failed")) {
  1890. this->GetHandler("test")->SetPersistentOption("RerunFailed", "true");
  1891. this->GetHandler("memcheck")->SetPersistentOption("RerunFailed", "true");
  1892. }
  1893. return true;
  1894. }
  1895. #if !defined(_WIN32)
  1896. bool cmCTest::ConsoleIsNotDumb()
  1897. {
  1898. std::string term_env_variable;
  1899. if (cmSystemTools::GetEnv("TERM", term_env_variable)) {
  1900. return isatty(1) && term_env_variable != "dumb";
  1901. }
  1902. return false;
  1903. }
  1904. #endif
  1905. bool cmCTest::ProgressOutputSupportedByConsole()
  1906. {
  1907. #if defined(_WIN32)
  1908. // On Windows we need a console buffer.
  1909. void* console = GetStdHandle(STD_OUTPUT_HANDLE);
  1910. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1911. return GetConsoleScreenBufferInfo(console, &csbi);
  1912. #else
  1913. // On UNIX we need a non-dumb tty.
  1914. return ConsoleIsNotDumb();
  1915. #endif
  1916. }
  1917. bool cmCTest::ColoredOutputSupportedByConsole()
  1918. {
  1919. #if defined(_WIN32)
  1920. // Not supported on Windows
  1921. return false;
  1922. #else
  1923. // On UNIX we need a non-dumb tty.
  1924. return ConsoleIsNotDumb();
  1925. #endif
  1926. }
  1927. // handle the -S -SR and -SP arguments
  1928. void cmCTest::HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  1929. bool& SRArgumentSpecified)
  1930. {
  1931. std::string arg = args[i];
  1932. if (this->CheckArgument(arg, "-SP", "--script-new-process") &&
  1933. i < args.size() - 1) {
  1934. this->RunConfigurationScript = true;
  1935. i++;
  1936. cmCTestScriptHandler* ch =
  1937. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1938. // -SR is an internal argument, -SP should be ignored when it is passed
  1939. if (!SRArgumentSpecified) {
  1940. ch->AddConfigurationScript(args[i].c_str(), false);
  1941. }
  1942. }
  1943. if (this->CheckArgument(arg, "-SR", "--script-run") && i < args.size() - 1) {
  1944. SRArgumentSpecified = true;
  1945. this->RunConfigurationScript = true;
  1946. i++;
  1947. cmCTestScriptHandler* ch =
  1948. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1949. ch->AddConfigurationScript(args[i].c_str(), true);
  1950. }
  1951. if (this->CheckArgument(arg, "-S", "--script") && i < args.size() - 1) {
  1952. this->RunConfigurationScript = true;
  1953. i++;
  1954. cmCTestScriptHandler* ch =
  1955. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1956. // -SR is an internal argument, -S should be ignored when it is passed
  1957. if (!SRArgumentSpecified) {
  1958. ch->AddConfigurationScript(args[i].c_str(), true);
  1959. }
  1960. }
  1961. }
  1962. bool cmCTest::AddVariableDefinition(const std::string& arg)
  1963. {
  1964. std::string name;
  1965. std::string value;
  1966. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  1967. if (cmake::ParseCacheEntry(arg, name, value, type)) {
  1968. this->Definitions[name] = value;
  1969. return true;
  1970. }
  1971. return false;
  1972. }
  1973. // the main entry point of ctest, called from main
  1974. int cmCTest::Run(std::vector<std::string>& args, std::string* output)
  1975. {
  1976. const char* ctestExec = "ctest";
  1977. bool cmakeAndTest = false;
  1978. bool executeTests = true;
  1979. bool SRArgumentSpecified = false;
  1980. // copy the command line
  1981. this->InitialCommandLineArguments.insert(
  1982. this->InitialCommandLineArguments.end(), args.begin(), args.end());
  1983. // process the command line arguments
  1984. for (size_t i = 1; i < args.size(); ++i) {
  1985. // handle the simple commandline arguments
  1986. std::string errormsg;
  1987. if (!this->HandleCommandLineArguments(i, args, errormsg)) {
  1988. cmSystemTools::Error(errormsg.c_str());
  1989. return 1;
  1990. }
  1991. // handle the script arguments -S -SR -SP
  1992. this->HandleScriptArguments(i, args, SRArgumentSpecified);
  1993. // --dashboard: handle a request for a dashboard
  1994. std::string arg = args[i];
  1995. if (this->CheckArgument(arg, "-D", "--dashboard") && i < args.size() - 1) {
  1996. this->ProduceXML = true;
  1997. i++;
  1998. std::string targ = args[i];
  1999. // AddTestsForDashboard parses the dashboard type and converts it
  2000. // into the separate stages
  2001. if (!this->AddTestsForDashboardType(targ)) {
  2002. if (!this->AddVariableDefinition(targ)) {
  2003. this->ErrorMessageUnknownDashDValue(targ);
  2004. executeTests = false;
  2005. }
  2006. }
  2007. }
  2008. // If it's not exactly -D, but it starts with -D, then try to parse out
  2009. // a variable definition from it, same as CMake does. Unsuccessful
  2010. // attempts are simply ignored since previous ctest versions ignore
  2011. // this too. (As well as many other unknown command line args.)
  2012. //
  2013. if (arg != "-D" && cmSystemTools::StringStartsWith(arg.c_str(), "-D")) {
  2014. std::string input = arg.substr(2);
  2015. this->AddVariableDefinition(input);
  2016. }
  2017. // --test-action: calls SetTest(<stage>, /*report=*/ false) to enable
  2018. // the corresponding stage
  2019. if (!this->HandleTestActionArgument(ctestExec, i, args)) {
  2020. executeTests = false;
  2021. }
  2022. // --test-model: what type of test model
  2023. if (!this->HandleTestModelArgument(ctestExec, i, args)) {
  2024. executeTests = false;
  2025. }
  2026. // --extra-submit
  2027. if (this->CheckArgument(arg, "--extra-submit") && i < args.size() - 1) {
  2028. this->ProduceXML = true;
  2029. this->SetTest("Submit");
  2030. i++;
  2031. if (!this->SubmitExtraFiles(args[i].c_str())) {
  2032. return 0;
  2033. }
  2034. }
  2035. // --build-and-test options
  2036. if (this->CheckArgument(arg, "--build-and-test") && i < args.size() - 1) {
  2037. cmakeAndTest = true;
  2038. }
  2039. // --schedule-random
  2040. if (this->CheckArgument(arg, "--schedule-random")) {
  2041. this->ScheduleType = "Random";
  2042. }
  2043. // pass the argument to all the handlers as well, but i may no longer be
  2044. // set to what it was originally so I'm not sure this is working as
  2045. // intended
  2046. for (auto& handler : this->TestingHandlers) {
  2047. if (!handler.second->ProcessCommandLineArguments(arg, i, args)) {
  2048. cmCTestLog(this, ERROR_MESSAGE,
  2049. "Problem parsing command line arguments within a handler");
  2050. return 0;
  2051. }
  2052. }
  2053. } // the close of the for argument loop
  2054. // handle CTEST_PARALLEL_LEVEL environment variable
  2055. if (!this->ParallelLevelSetInCli) {
  2056. std::string parallel;
  2057. if (cmSystemTools::GetEnv("CTEST_PARALLEL_LEVEL", parallel)) {
  2058. int plevel = atoi(parallel.c_str());
  2059. this->SetParallelLevel(plevel);
  2060. }
  2061. }
  2062. // TestProgressOutput only supported if console supports it and not logging
  2063. // to a file
  2064. this->TestProgressOutput = this->TestProgressOutput &&
  2065. !this->OutputLogFile && this->ProgressOutputSupportedByConsole();
  2066. #ifdef _WIN32
  2067. if (this->TestProgressOutput) {
  2068. // Disable output line buffering so we can print content without
  2069. // a newline.
  2070. std::setvbuf(stdout, nullptr, _IONBF, 0);
  2071. }
  2072. #endif
  2073. // now what should cmake do? if --build-and-test was specified then
  2074. // we run the build and test handler and return
  2075. if (cmakeAndTest) {
  2076. return this->RunCMakeAndTest(output);
  2077. }
  2078. if (executeTests) {
  2079. return this->ExecuteTests();
  2080. }
  2081. return 1;
  2082. }
  2083. bool cmCTest::HandleTestActionArgument(const char* ctestExec, size_t& i,
  2084. const std::vector<std::string>& args)
  2085. {
  2086. bool success = true;
  2087. std::string arg = args[i];
  2088. if (this->CheckArgument(arg, "-T", "--test-action") &&
  2089. (i < args.size() - 1)) {
  2090. this->ProduceXML = true;
  2091. i++;
  2092. if (!this->SetTest(args[i].c_str(), false)) {
  2093. success = false;
  2094. cmCTestLog(this, ERROR_MESSAGE,
  2095. "CTest -T called with incorrect option: " << args[i]
  2096. << std::endl);
  2097. cmCTestLog(this, ERROR_MESSAGE,
  2098. "Available options are:"
  2099. << std::endl
  2100. << " " << ctestExec << " -T all" << std::endl
  2101. << " " << ctestExec << " -T start" << std::endl
  2102. << " " << ctestExec << " -T update" << std::endl
  2103. << " " << ctestExec << " -T configure" << std::endl
  2104. << " " << ctestExec << " -T build" << std::endl
  2105. << " " << ctestExec << " -T test" << std::endl
  2106. << " " << ctestExec << " -T coverage" << std::endl
  2107. << " " << ctestExec << " -T memcheck" << std::endl
  2108. << " " << ctestExec << " -T notes" << std::endl
  2109. << " " << ctestExec << " -T submit" << std::endl);
  2110. }
  2111. }
  2112. return success;
  2113. }
  2114. bool cmCTest::HandleTestModelArgument(const char* ctestExec, size_t& i,
  2115. const std::vector<std::string>& args)
  2116. {
  2117. bool success = true;
  2118. std::string arg = args[i];
  2119. if (this->CheckArgument(arg, "-M", "--test-model") &&
  2120. (i < args.size() - 1)) {
  2121. i++;
  2122. std::string const& str = args[i];
  2123. if (cmSystemTools::LowerCase(str) == "nightly") {
  2124. this->SetTestModel(cmCTest::NIGHTLY);
  2125. } else if (cmSystemTools::LowerCase(str) == "continuous") {
  2126. this->SetTestModel(cmCTest::CONTINUOUS);
  2127. } else if (cmSystemTools::LowerCase(str) == "experimental") {
  2128. this->SetTestModel(cmCTest::EXPERIMENTAL);
  2129. } else {
  2130. success = false;
  2131. cmCTestLog(this, ERROR_MESSAGE,
  2132. "CTest -M called with incorrect option: " << str
  2133. << std::endl);
  2134. cmCTestLog(this, ERROR_MESSAGE,
  2135. "Available options are:"
  2136. << std::endl
  2137. << " " << ctestExec << " -M Continuous" << std::endl
  2138. << " " << ctestExec << " -M Experimental" << std::endl
  2139. << " " << ctestExec << " -M Nightly" << std::endl);
  2140. }
  2141. }
  2142. return success;
  2143. }
  2144. int cmCTest::ExecuteTests()
  2145. {
  2146. int res;
  2147. // call process directory
  2148. if (this->RunConfigurationScript) {
  2149. if (this->ExtraVerbose) {
  2150. cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
  2151. }
  2152. for (auto& handler : this->TestingHandlers) {
  2153. handler.second->SetVerbose(this->ExtraVerbose);
  2154. handler.second->SetSubmitIndex(this->SubmitIndex);
  2155. }
  2156. this->GetHandler("script")->SetVerbose(this->Verbose);
  2157. res = this->GetHandler("script")->ProcessHandler();
  2158. if (res != 0) {
  2159. cmCTestLog(this, DEBUG,
  2160. "running script failing returning: " << res << std::endl);
  2161. }
  2162. } else {
  2163. // What is this? -V seems to be the same as -VV,
  2164. // and Verbose is always on in this case
  2165. this->ExtraVerbose = this->Verbose;
  2166. this->Verbose = true;
  2167. for (auto& handler : this->TestingHandlers) {
  2168. handler.second->SetVerbose(this->Verbose);
  2169. handler.second->SetSubmitIndex(this->SubmitIndex);
  2170. }
  2171. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2172. if (!this->Initialize(cwd.c_str(), nullptr)) {
  2173. res = 12;
  2174. cmCTestLog(this, ERROR_MESSAGE,
  2175. "Problem initializing the dashboard." << std::endl);
  2176. } else {
  2177. res = this->ProcessSteps();
  2178. }
  2179. this->Finalize();
  2180. }
  2181. if (res != 0) {
  2182. cmCTestLog(this, DEBUG,
  2183. "Running a test(s) failed returning : " << res << std::endl);
  2184. }
  2185. return res;
  2186. }
  2187. int cmCTest::RunCMakeAndTest(std::string* output)
  2188. {
  2189. this->Verbose = true;
  2190. cmCTestBuildAndTestHandler* handler =
  2191. static_cast<cmCTestBuildAndTestHandler*>(this->GetHandler("buildtest"));
  2192. int retv = handler->ProcessHandler();
  2193. *output = handler->GetOutput();
  2194. #ifdef CMAKE_BUILD_WITH_CMAKE
  2195. cmDynamicLoader::FlushCache();
  2196. #endif
  2197. if (retv != 0) {
  2198. cmCTestLog(this, DEBUG,
  2199. "build and test failing returning: " << retv << std::endl);
  2200. }
  2201. return retv;
  2202. }
  2203. void cmCTest::SetNotesFiles(const char* notes)
  2204. {
  2205. if (!notes) {
  2206. return;
  2207. }
  2208. this->NotesFiles = notes;
  2209. }
  2210. void cmCTest::SetStopTime(std::string const& time_str)
  2211. {
  2212. struct tm* lctime;
  2213. time_t current_time = time(nullptr);
  2214. lctime = gmtime(&current_time);
  2215. int gm_hour = lctime->tm_hour;
  2216. time_t gm_time = mktime(lctime);
  2217. lctime = localtime(&current_time);
  2218. int local_hour = lctime->tm_hour;
  2219. int tzone_offset = local_hour - gm_hour;
  2220. if (gm_time > current_time && gm_hour < local_hour) {
  2221. // this means gm_time is on the next day
  2222. tzone_offset -= 24;
  2223. } else if (gm_time < current_time && gm_hour > local_hour) {
  2224. // this means gm_time is on the previous day
  2225. tzone_offset += 24;
  2226. }
  2227. tzone_offset *= 100;
  2228. char buf[1024];
  2229. sprintf(buf, "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  2230. lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(), tzone_offset);
  2231. time_t stop_time = curl_getdate(buf, &current_time);
  2232. if (stop_time == -1) {
  2233. this->StopTime = std::chrono::system_clock::time_point();
  2234. return;
  2235. }
  2236. this->StopTime = std::chrono::system_clock::from_time_t(stop_time);
  2237. if (stop_time < current_time) {
  2238. this->StopTime += std::chrono::hours(24);
  2239. }
  2240. }
  2241. int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf)
  2242. {
  2243. bool found = false;
  2244. VectorOfStrings dirs;
  2245. VectorOfStrings ndirs;
  2246. cmCTestLog(this, DEBUG,
  2247. "* Read custom CTest configuration directory: " << dir
  2248. << std::endl);
  2249. std::string fname = dir;
  2250. fname += "/CTestCustom.cmake";
  2251. cmCTestLog(this, DEBUG, "* Check for file: " << fname << std::endl);
  2252. if (cmSystemTools::FileExists(fname)) {
  2253. cmCTestLog(this, DEBUG,
  2254. "* Read custom CTest configuration file: " << fname
  2255. << std::endl);
  2256. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  2257. cmSystemTools::ResetErrorOccuredFlag();
  2258. if (!mf->ReadListFile(fname) || cmSystemTools::GetErrorOccuredFlag()) {
  2259. cmCTestLog(this, ERROR_MESSAGE,
  2260. "Problem reading custom configuration: " << fname
  2261. << std::endl);
  2262. }
  2263. found = true;
  2264. if (erroroc) {
  2265. cmSystemTools::SetErrorOccured();
  2266. }
  2267. }
  2268. std::string rexpr = dir;
  2269. rexpr += "/CTestCustom.ctest";
  2270. cmCTestLog(this, DEBUG, "* Check for file: " << rexpr << std::endl);
  2271. if (!found && cmSystemTools::FileExists(rexpr)) {
  2272. cmsys::Glob gl;
  2273. gl.RecurseOn();
  2274. gl.FindFiles(rexpr);
  2275. std::vector<std::string>& files = gl.GetFiles();
  2276. for (const std::string& file : files) {
  2277. cmCTestLog(this, DEBUG,
  2278. "* Read custom CTest configuration file: " << file
  2279. << std::endl);
  2280. if (!mf->ReadListFile(file) || cmSystemTools::GetErrorOccuredFlag()) {
  2281. cmCTestLog(this, ERROR_MESSAGE,
  2282. "Problem reading custom configuration: " << file
  2283. << std::endl);
  2284. }
  2285. }
  2286. found = true;
  2287. }
  2288. if (found) {
  2289. for (auto& handler : this->TestingHandlers) {
  2290. cmCTestLog(this, DEBUG,
  2291. "* Read custom CTest configuration vectors for handler: "
  2292. << handler.first << " (" << handler.second << ")"
  2293. << std::endl);
  2294. handler.second->PopulateCustomVectors(mf);
  2295. }
  2296. }
  2297. return 1;
  2298. }
  2299. void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def,
  2300. std::vector<std::string>& vec)
  2301. {
  2302. const char* dval = mf->GetDefinition(def);
  2303. if (!dval) {
  2304. return;
  2305. }
  2306. cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl);
  2307. vec.clear();
  2308. cmSystemTools::ExpandListArgument(dval, vec);
  2309. for (std::string const& it : vec) {
  2310. cmCTestLog(this, DEBUG, " -- " << it << std::endl);
  2311. }
  2312. }
  2313. void cmCTest::PopulateCustomInteger(cmMakefile* mf, const std::string& def,
  2314. int& val)
  2315. {
  2316. const char* dval = mf->GetDefinition(def);
  2317. if (!dval) {
  2318. return;
  2319. }
  2320. val = atoi(dval);
  2321. }
  2322. std::string cmCTest::GetShortPathToFile(const char* cfname)
  2323. {
  2324. const std::string& sourceDir = cmSystemTools::CollapseFullPath(
  2325. this->GetCTestConfiguration("SourceDirectory"));
  2326. const std::string& buildDir = cmSystemTools::CollapseFullPath(
  2327. this->GetCTestConfiguration("BuildDirectory"));
  2328. std::string fname = cmSystemTools::CollapseFullPath(cfname);
  2329. // Find relative paths to both directories
  2330. std::string srcRelpath = cmSystemTools::RelativePath(sourceDir, fname);
  2331. std::string bldRelpath = cmSystemTools::RelativePath(buildDir, fname);
  2332. // If any contains "." it is not parent directory
  2333. bool inSrc = srcRelpath.find("..") == std::string::npos;
  2334. bool inBld = bldRelpath.find("..") == std::string::npos;
  2335. // TODO: Handle files with .. in their name
  2336. std::string* res = nullptr;
  2337. if (inSrc && inBld) {
  2338. // If both have relative path with no dots, pick the shorter one
  2339. if (srcRelpath.size() < bldRelpath.size()) {
  2340. res = &srcRelpath;
  2341. } else {
  2342. res = &bldRelpath;
  2343. }
  2344. } else if (inSrc) {
  2345. res = &srcRelpath;
  2346. } else if (inBld) {
  2347. res = &bldRelpath;
  2348. }
  2349. std::string path;
  2350. if (!res) {
  2351. path = fname;
  2352. } else {
  2353. cmSystemTools::ConvertToUnixSlashes(*res);
  2354. path = "./" + *res;
  2355. if (path.back() == '/') {
  2356. path = path.substr(0, path.size() - 1);
  2357. }
  2358. }
  2359. cmsys::SystemTools::ReplaceString(path, ":", "_");
  2360. cmsys::SystemTools::ReplaceString(path, " ", "_");
  2361. return path;
  2362. }
  2363. std::string cmCTest::GetCTestConfiguration(const std::string& name)
  2364. {
  2365. if (this->CTestConfigurationOverwrites.find(name) !=
  2366. this->CTestConfigurationOverwrites.end()) {
  2367. return this->CTestConfigurationOverwrites[name];
  2368. }
  2369. return this->CTestConfiguration[name];
  2370. }
  2371. void cmCTest::EmptyCTestConfiguration()
  2372. {
  2373. this->CTestConfiguration.clear();
  2374. }
  2375. void cmCTest::SetCTestConfiguration(const char* name, const char* value,
  2376. bool suppress)
  2377. {
  2378. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2379. "SetCTestConfiguration:"
  2380. << name << ":" << (value ? value : "(null)") << "\n",
  2381. suppress);
  2382. if (!name) {
  2383. return;
  2384. }
  2385. if (!value) {
  2386. this->CTestConfiguration.erase(name);
  2387. return;
  2388. }
  2389. this->CTestConfiguration[name] = value;
  2390. }
  2391. std::string cmCTest::GetCurrentTag()
  2392. {
  2393. return this->CurrentTag;
  2394. }
  2395. std::string cmCTest::GetBinaryDir()
  2396. {
  2397. return this->BinaryDir;
  2398. }
  2399. std::string const& cmCTest::GetConfigType()
  2400. {
  2401. return this->ConfigType;
  2402. }
  2403. bool cmCTest::GetShowOnly()
  2404. {
  2405. return this->ShowOnly;
  2406. }
  2407. bool cmCTest::GetOutputAsJson()
  2408. {
  2409. return this->OutputAsJson;
  2410. }
  2411. int cmCTest::GetOutputAsJsonVersion()
  2412. {
  2413. return this->OutputAsJsonVersion;
  2414. }
  2415. int cmCTest::GetMaxTestNameWidth() const
  2416. {
  2417. return this->MaxTestNameWidth;
  2418. }
  2419. void cmCTest::SetProduceXML(bool v)
  2420. {
  2421. this->ProduceXML = v;
  2422. }
  2423. bool cmCTest::GetProduceXML()
  2424. {
  2425. return this->ProduceXML;
  2426. }
  2427. const char* cmCTest::GetSpecificTrack()
  2428. {
  2429. if (this->SpecificTrack.empty()) {
  2430. return nullptr;
  2431. }
  2432. return this->SpecificTrack.c_str();
  2433. }
  2434. void cmCTest::SetSpecificTrack(const char* track)
  2435. {
  2436. if (!track) {
  2437. this->SpecificTrack.clear();
  2438. return;
  2439. }
  2440. this->SpecificTrack = track;
  2441. }
  2442. void cmCTest::AddSubmitFile(Part part, const char* name)
  2443. {
  2444. this->Parts[part].SubmitFiles.push_back(name);
  2445. }
  2446. void cmCTest::AddCTestConfigurationOverwrite(const std::string& overStr)
  2447. {
  2448. size_t epos = overStr.find('=');
  2449. if (epos == std::string::npos) {
  2450. cmCTestLog(this, ERROR_MESSAGE,
  2451. "CTest configuration overwrite specified in the wrong format."
  2452. << std::endl
  2453. << "Valid format is: --overwrite key=value" << std::endl
  2454. << "The specified was: --overwrite " << overStr << std::endl);
  2455. return;
  2456. }
  2457. std::string key = overStr.substr(0, epos);
  2458. std::string value = overStr.substr(epos + 1);
  2459. this->CTestConfigurationOverwrites[key] = value;
  2460. }
  2461. void cmCTest::SetConfigType(const char* ct)
  2462. {
  2463. this->ConfigType = ct ? ct : "";
  2464. cmSystemTools::ReplaceString(this->ConfigType, ".\\", "");
  2465. std::string confTypeEnv = "CMAKE_CONFIG_TYPE=" + this->ConfigType;
  2466. cmSystemTools::PutEnv(confTypeEnv);
  2467. }
  2468. bool cmCTest::SetCTestConfigurationFromCMakeVariable(
  2469. cmMakefile* mf, const char* dconfig, const std::string& cmake_var,
  2470. bool suppress)
  2471. {
  2472. const char* ctvar;
  2473. ctvar = mf->GetDefinition(cmake_var);
  2474. if (!ctvar) {
  2475. return false;
  2476. }
  2477. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2478. "SetCTestConfigurationFromCMakeVariable:"
  2479. << dconfig << ":" << cmake_var << std::endl,
  2480. suppress);
  2481. this->SetCTestConfiguration(dconfig, ctvar, suppress);
  2482. return true;
  2483. }
  2484. bool cmCTest::RunCommand(std::vector<std::string> const& args,
  2485. std::string* stdOut, std::string* stdErr, int* retVal,
  2486. const char* dir, cmDuration timeout,
  2487. Encoding encoding)
  2488. {
  2489. std::vector<const char*> argv;
  2490. argv.reserve(args.size() + 1);
  2491. for (std::string const& a : args) {
  2492. argv.push_back(a.c_str());
  2493. }
  2494. argv.push_back(nullptr);
  2495. stdOut->clear();
  2496. stdErr->clear();
  2497. cmsysProcess* cp = cmsysProcess_New();
  2498. cmsysProcess_SetCommand(cp, &*argv.begin());
  2499. cmsysProcess_SetWorkingDirectory(cp, dir);
  2500. if (cmSystemTools::GetRunCommandHideConsole()) {
  2501. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  2502. }
  2503. cmsysProcess_SetTimeout(cp, timeout.count());
  2504. cmsysProcess_Execute(cp);
  2505. std::vector<char> tempOutput;
  2506. std::vector<char> tempError;
  2507. char* data;
  2508. int length;
  2509. cmProcessOutput processOutput(encoding);
  2510. std::string strdata;
  2511. int res;
  2512. bool done = false;
  2513. while (!done) {
  2514. res = cmsysProcess_WaitForData(cp, &data, &length, nullptr);
  2515. switch (res) {
  2516. case cmsysProcess_Pipe_STDOUT:
  2517. tempOutput.insert(tempOutput.end(), data, data + length);
  2518. break;
  2519. case cmsysProcess_Pipe_STDERR:
  2520. tempError.insert(tempError.end(), data, data + length);
  2521. break;
  2522. default:
  2523. done = true;
  2524. }
  2525. if ((res == cmsysProcess_Pipe_STDOUT || res == cmsysProcess_Pipe_STDERR) &&
  2526. this->ExtraVerbose) {
  2527. processOutput.DecodeText(data, length, strdata);
  2528. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2529. }
  2530. }
  2531. if (this->ExtraVerbose) {
  2532. processOutput.DecodeText(std::string(), strdata);
  2533. if (!strdata.empty()) {
  2534. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2535. }
  2536. }
  2537. cmsysProcess_WaitForExit(cp, nullptr);
  2538. if (!tempOutput.empty()) {
  2539. processOutput.DecodeText(tempOutput, tempOutput);
  2540. stdOut->append(&*tempOutput.begin(), tempOutput.size());
  2541. }
  2542. if (!tempError.empty()) {
  2543. processOutput.DecodeText(tempError, tempError);
  2544. stdErr->append(&*tempError.begin(), tempError.size());
  2545. }
  2546. bool result = true;
  2547. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  2548. if (retVal) {
  2549. *retVal = cmsysProcess_GetExitValue(cp);
  2550. } else {
  2551. if (cmsysProcess_GetExitValue(cp) != 0) {
  2552. result = false;
  2553. }
  2554. }
  2555. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  2556. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  2557. cmCTestLog(this, ERROR_MESSAGE, exception_str << std::endl);
  2558. stdErr->append(exception_str, strlen(exception_str));
  2559. result = false;
  2560. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  2561. const char* error_str = cmsysProcess_GetErrorString(cp);
  2562. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2563. stdErr->append(error_str, strlen(error_str));
  2564. result = false;
  2565. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  2566. const char* error_str = "Process terminated due to timeout\n";
  2567. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2568. stdErr->append(error_str, strlen(error_str));
  2569. result = false;
  2570. }
  2571. cmsysProcess_Delete(cp);
  2572. return result;
  2573. }
  2574. void cmCTest::SetOutputLogFileName(const char* name)
  2575. {
  2576. if (this->OutputLogFile) {
  2577. delete this->OutputLogFile;
  2578. this->OutputLogFile = nullptr;
  2579. }
  2580. if (name) {
  2581. this->OutputLogFile = new cmGeneratedFileStream(name);
  2582. }
  2583. }
  2584. static const char* cmCTestStringLogType[] = { "DEBUG",
  2585. "OUTPUT",
  2586. "HANDLER_OUTPUT",
  2587. "HANDLER_PROGRESS_OUTPUT",
  2588. "HANDLER_TEST_PROGRESS_OUTPUT",
  2589. "HANDLER_VERBOSE_OUTPUT",
  2590. "WARNING",
  2591. "ERROR_MESSAGE",
  2592. nullptr };
  2593. #define cmCTestLogOutputFileLine(stream) \
  2594. do { \
  2595. if (this->ShowLineNumbers) { \
  2596. (stream) << std::endl << file << ":" << line << " "; \
  2597. } \
  2598. } while (false)
  2599. void cmCTest::InitStreams()
  2600. {
  2601. // By default we write output to the process output streams.
  2602. this->StreamOut = &std::cout;
  2603. this->StreamErr = &std::cerr;
  2604. }
  2605. void cmCTest::Log(int logType, const char* file, int line, const char* msg,
  2606. bool suppress)
  2607. {
  2608. if (!msg || !*msg) {
  2609. return;
  2610. }
  2611. if (suppress && logType != cmCTest::ERROR_MESSAGE) {
  2612. return;
  2613. }
  2614. if (logType == cmCTest::HANDLER_PROGRESS_OUTPUT &&
  2615. (this->Debug || this->ExtraVerbose)) {
  2616. return;
  2617. }
  2618. if (this->OutputLogFile) {
  2619. bool display = true;
  2620. if (logType == cmCTest::DEBUG && !this->Debug) {
  2621. display = false;
  2622. }
  2623. if (logType == cmCTest::HANDLER_VERBOSE_OUTPUT && !this->Debug &&
  2624. !this->ExtraVerbose) {
  2625. display = false;
  2626. }
  2627. if (display) {
  2628. cmCTestLogOutputFileLine(*this->OutputLogFile);
  2629. if (logType != this->OutputLogFileLastTag) {
  2630. *this->OutputLogFile << "[";
  2631. if (logType >= OTHER || logType < 0) {
  2632. *this->OutputLogFile << "OTHER";
  2633. } else {
  2634. *this->OutputLogFile << cmCTestStringLogType[logType];
  2635. }
  2636. *this->OutputLogFile << "] " << std::endl << std::flush;
  2637. }
  2638. *this->OutputLogFile << msg << std::flush;
  2639. if (logType != this->OutputLogFileLastTag) {
  2640. *this->OutputLogFile << std::endl << std::flush;
  2641. this->OutputLogFileLastTag = logType;
  2642. }
  2643. }
  2644. }
  2645. if (!this->Quiet) {
  2646. std::ostream& out = *this->StreamOut;
  2647. std::ostream& err = *this->StreamErr;
  2648. if (logType == HANDLER_TEST_PROGRESS_OUTPUT) {
  2649. if (this->TestProgressOutput) {
  2650. cmCTestLogOutputFileLine(out);
  2651. if (this->FlushTestProgressLine) {
  2652. printf("\r");
  2653. this->FlushTestProgressLine = false;
  2654. out.flush();
  2655. }
  2656. std::string msg_str{ msg };
  2657. auto const lineBreakIt = msg_str.find('\n');
  2658. if (lineBreakIt != std::string::npos) {
  2659. this->FlushTestProgressLine = true;
  2660. msg_str.erase(std::remove(msg_str.begin(), msg_str.end(), '\n'),
  2661. msg_str.end());
  2662. }
  2663. out << msg_str;
  2664. #ifndef _WIN32
  2665. printf("\x1B[K"); // move caret to end
  2666. #endif
  2667. out.flush();
  2668. return;
  2669. }
  2670. logType = HANDLER_OUTPUT;
  2671. }
  2672. switch (logType) {
  2673. case DEBUG:
  2674. if (this->Debug) {
  2675. cmCTestLogOutputFileLine(out);
  2676. out << msg;
  2677. out.flush();
  2678. }
  2679. break;
  2680. case OUTPUT:
  2681. case HANDLER_OUTPUT:
  2682. if (this->Debug || this->Verbose) {
  2683. cmCTestLogOutputFileLine(out);
  2684. out << msg;
  2685. out.flush();
  2686. }
  2687. break;
  2688. case HANDLER_VERBOSE_OUTPUT:
  2689. if (this->Debug || this->ExtraVerbose) {
  2690. cmCTestLogOutputFileLine(out);
  2691. out << msg;
  2692. out.flush();
  2693. }
  2694. break;
  2695. case WARNING:
  2696. cmCTestLogOutputFileLine(err);
  2697. err << msg;
  2698. err.flush();
  2699. break;
  2700. case ERROR_MESSAGE:
  2701. cmCTestLogOutputFileLine(err);
  2702. err << msg;
  2703. err.flush();
  2704. cmSystemTools::SetErrorOccured();
  2705. break;
  2706. default:
  2707. cmCTestLogOutputFileLine(out);
  2708. out << msg;
  2709. out.flush();
  2710. }
  2711. }
  2712. }
  2713. std::string cmCTest::GetColorCode(Color color) const
  2714. {
  2715. if (this->OutputColorCode) {
  2716. #if defined(_WIN32)
  2717. // Not supported on Windows
  2718. static_cast<void>(color);
  2719. #else
  2720. return "\033[0;" + std::to_string(static_cast<int>(color)) + "m";
  2721. #endif
  2722. }
  2723. return "";
  2724. }
  2725. cmDuration cmCTest::GetRemainingTimeAllowed()
  2726. {
  2727. if (!this->GetHandler("script")) {
  2728. return cmCTest::MaxDuration();
  2729. }
  2730. cmCTestScriptHandler* ch =
  2731. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  2732. return ch->GetRemainingTimeAllowed();
  2733. }
  2734. cmDuration cmCTest::MaxDuration()
  2735. {
  2736. return cmDuration(1.0e7);
  2737. }
  2738. void cmCTest::SetRunCurrentScript(bool value)
  2739. {
  2740. cmCTestScriptHandler* ch =
  2741. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  2742. ch->SetRunCurrentScript(value);
  2743. }
  2744. void cmCTest::OutputTestErrors(std::vector<char> const& process_output)
  2745. {
  2746. std::string test_outputs("\n*** Test Failed:\n");
  2747. if (!process_output.empty()) {
  2748. test_outputs.append(&*process_output.begin(), process_output.size());
  2749. }
  2750. cmCTestLog(this, HANDLER_OUTPUT, test_outputs << std::endl << std::flush);
  2751. }
  2752. bool cmCTest::CompressString(std::string& str)
  2753. {
  2754. int ret;
  2755. z_stream strm;
  2756. strm.zalloc = Z_NULL;
  2757. strm.zfree = Z_NULL;
  2758. strm.opaque = Z_NULL;
  2759. ret = deflateInit(&strm, -1); // default compression level
  2760. if (ret != Z_OK) {
  2761. return false;
  2762. }
  2763. unsigned char* in =
  2764. reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
  2765. // zlib makes the guarantee that this is the maximum output size
  2766. int outSize =
  2767. static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
  2768. std::vector<unsigned char> out(outSize);
  2769. strm.avail_in = static_cast<uInt>(str.size());
  2770. strm.next_in = in;
  2771. strm.avail_out = outSize;
  2772. strm.next_out = &out[0];
  2773. ret = deflate(&strm, Z_FINISH);
  2774. if (ret != Z_STREAM_END) {
  2775. cmCTestLog(this, ERROR_MESSAGE,
  2776. "Error during gzip compression." << std::endl);
  2777. return false;
  2778. }
  2779. (void)deflateEnd(&strm);
  2780. // Now base64 encode the resulting binary string
  2781. std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
  2782. size_t rlen =
  2783. cmsysBase64_Encode(&out[0], strm.total_out, &base64EncodedBuffer[0], 1);
  2784. str.assign(reinterpret_cast<char*>(&base64EncodedBuffer[0]), rlen);
  2785. return true;
  2786. }