cmCTest.cxx 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmCTest.h"
  4. #include <algorithm>
  5. #include <cctype>
  6. #include <chrono>
  7. #include <cstdint>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <ctime>
  12. #include <initializer_list>
  13. #include <iostream>
  14. #include <map>
  15. #include <ratio>
  16. #include <sstream>
  17. #include <string>
  18. #include <utility>
  19. #include <vector>
  20. #include <cm/memory>
  21. #include <cm/optional>
  22. #include <cm/string_view>
  23. #include <cmext/algorithm>
  24. #include <cmext/string_view>
  25. #include <cm3p/json/value.h>
  26. #include <cm3p/uv.h>
  27. #include <cm3p/zlib.h>
  28. #include "cmsys/Base64.h"
  29. #include "cmsys/Directory.hxx"
  30. #include "cmsys/FStream.hxx"
  31. #include "cmsys/RegularExpression.hxx"
  32. #include "cmsys/SystemInformation.hxx"
  33. #ifndef _WIN32
  34. # include <unistd.h> // IWYU pragma: keep
  35. #endif
  36. #include "cm_get_date.h"
  37. #include "cmCMakePresetsGraph.h"
  38. #include "cmCTestBuildAndTest.h"
  39. #include "cmCTestScriptHandler.h"
  40. #include "cmCTestTestHandler.h"
  41. #include "cmCTestTypes.h"
  42. #include "cmCommandLineArgument.h"
  43. #include "cmExecutionStatus.h"
  44. #include "cmGeneratedFileStream.h"
  45. #include "cmGlobalGenerator.h"
  46. #include "cmInstrumentation.h"
  47. #include "cmInstrumentationQuery.h"
  48. #include "cmJSONState.h"
  49. #include "cmList.h"
  50. #include "cmListFileCache.h"
  51. #include "cmMakefile.h"
  52. #include "cmProcessOutput.h"
  53. #include "cmState.h"
  54. #include "cmStateSnapshot.h"
  55. #include "cmStateTypes.h"
  56. #include "cmStdIoStream.h"
  57. #include "cmStringAlgorithms.h"
  58. #include "cmSystemTools.h"
  59. #include "cmUVHandlePtr.h"
  60. #include "cmUVProcessChain.h"
  61. #include "cmUVStream.h"
  62. #include "cmValue.h"
  63. #include "cmVersion.h"
  64. #include "cmVersionConfig.h"
  65. #include "cmWorkingDirectory.h"
  66. #include "cmXMLWriter.h"
  67. #include "cmake.h"
  68. #if defined(__BEOS__) || defined(__HAIKU__)
  69. # include <be/kernel/OS.h> /* disable_debugger() API. */
  70. #endif
  71. struct cmCTest::Private
  72. {
  73. Private(cmCTest* ctest)
  74. : BuildAndTest(ctest)
  75. {
  76. }
  77. /** Representation of one part. */
  78. struct PartInfo
  79. {
  80. void SetName(std::string const& name) { this->Name = name; }
  81. std::string const& GetName() const { return this->Name; }
  82. void Enable() { this->Enabled = true; }
  83. explicit operator bool() const { return this->Enabled; }
  84. std::vector<std::string> SubmitFiles;
  85. private:
  86. bool Enabled = false;
  87. std::string Name;
  88. };
  89. int RepeatCount = 1; // default to run each test once
  90. cmCTest::Repeat RepeatMode = cmCTest::Repeat::Never;
  91. std::string ConfigType;
  92. std::string ScheduleType;
  93. std::chrono::system_clock::time_point StopTime;
  94. bool StopOnFailure = false;
  95. bool TestProgressOutput = false;
  96. bool Verbose = false;
  97. bool ExtraVerbose = false;
  98. bool ProduceXML = false;
  99. bool LabelSummary = true;
  100. bool SubprojectSummary = true;
  101. bool UseHTTP10 = false;
  102. bool PrintLabels = false;
  103. bool Failover = false;
  104. cmJSONState parseState;
  105. bool FlushTestProgressLine = false;
  106. // these are helper classes
  107. cmCTestBuildAndTest BuildAndTest;
  108. bool ShowOnly = false;
  109. bool OutputAsJson = false;
  110. int OutputAsJsonVersion = 1;
  111. // TODO: The ctest configuration should be a hierarchy of
  112. // configuration option sources: command-line, script, ini file.
  113. // Then the ini file can get re-loaded whenever it changes without
  114. // affecting any higher-precedence settings.
  115. std::map<std::string, std::string> CTestConfiguration;
  116. std::map<std::string, std::string> CTestConfigurationOverwrites;
  117. PartInfo Parts[PartCount];
  118. std::map<std::string, Part> PartMap;
  119. std::string CurrentTag;
  120. bool TomorrowTag = false;
  121. int TestModel = cmCTest::EXPERIMENTAL;
  122. std::string SpecificGroup;
  123. cmDuration TimeOut = cmDuration::zero();
  124. cmDuration GlobalTimeout = cmDuration::zero();
  125. std::chrono::steady_clock::time_point StartTime =
  126. std::chrono::steady_clock::now();
  127. cmDuration TimeLimit = cmCTest::MaxDuration();
  128. int MaxTestNameWidth = 30;
  129. cm::optional<size_t> ParallelLevel = 1;
  130. bool ParallelLevelSetInCli = false;
  131. unsigned long TestLoad = 0;
  132. int CompatibilityMode;
  133. // information for the --build-and-test options
  134. std::string BinaryDir;
  135. std::string TestDir;
  136. std::string NotesFiles;
  137. bool InteractiveDebugMode = true;
  138. bool ShortDateFormat = true;
  139. bool CompressXMLFiles = false;
  140. bool CompressTestOutput = true;
  141. bool Debug = false;
  142. bool Quiet = false;
  143. std::string BuildID;
  144. std::vector<std::string> InitialCommandLineArguments;
  145. int SubmitIndex = 0;
  146. std::unique_ptr<cmGeneratedFileStream> OutputLogFile;
  147. cm::optional<cmCTest::LogType> OutputLogFileLastTag;
  148. bool OutputTestOutputOnTestFailure = false;
  149. bool OutputColorCode = cmCTest::ColoredOutputSupportedByConsole();
  150. std::map<std::string, std::string> Definitions;
  151. cmCTest::NoTests NoTestsMode = cmCTest::NoTests::Legacy;
  152. bool NoTestsModeSetInCli = false;
  153. cmCTestTestOptions TestOptions;
  154. std::vector<std::string> CommandLineHttpHeaders;
  155. std::unique_ptr<cmInstrumentation> Instrumentation;
  156. };
  157. struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
  158. {
  159. struct tm* lctime;
  160. time_t tctime = time(nullptr);
  161. lctime = gmtime(&tctime);
  162. cmCTestLog(this, OUTPUT,
  163. "Determine Nightly Start Time" << std::endl
  164. << " Specified time: " << str
  165. << std::endl);
  166. // Convert the nightly start time to seconds. The current date of
  167. // the local machine is assumed. Consequently, nightlySeconds
  168. // is the time at which the nightly dashboard was opened or
  169. // will be opened on the date of the current client machine.
  170. // As such, this time may be in the past or in the future.
  171. char buf[1024];
  172. std::snprintf(buf, sizeof(buf), "%d%02d%02d %s", lctime->tm_year + 1900,
  173. lctime->tm_mon + 1, lctime->tm_mday, str.c_str());
  174. time_t ntime = cm_get_date(tctime, buf);
  175. cmCTestLog(this, DEBUG,
  176. " Get the nightly start time: " << ntime << std::endl);
  177. tctime = time(nullptr);
  178. cmCTestLog(this, DEBUG, " Get the current time: " << tctime << std::endl);
  179. int const dayLength = 24 * 60 * 60;
  180. cmCTestLog(this, DEBUG, "Seconds: " << tctime << std::endl);
  181. while (ntime > tctime) {
  182. // If nightlySeconds is in the past, this is the current
  183. // open dashboard, then return nightlySeconds. If
  184. // nightlySeconds is in the future, this is the next
  185. // dashboard to be opened, so subtract 24 hours to get the
  186. // time of the current open dashboard
  187. ntime -= dayLength;
  188. cmCTestLog(this, DEBUG, "Pick yesterday" << std::endl);
  189. cmCTestLog(this, DEBUG,
  190. " Future time, subtract day: " << ntime << std::endl);
  191. }
  192. while (tctime > (ntime + dayLength)) {
  193. ntime += dayLength;
  194. cmCTestLog(this, DEBUG, " Past time, add day: " << ntime << std::endl);
  195. }
  196. cmCTestLog(this, DEBUG, "nightlySeconds: " << ntime << std::endl);
  197. cmCTestLog(this, DEBUG,
  198. " Current time: " << tctime << " Nightly time: " << ntime
  199. << std::endl);
  200. if (tomorrowtag) {
  201. cmCTestLog(this, OUTPUT, " Use future tag, Add a day" << std::endl);
  202. ntime += dayLength;
  203. }
  204. lctime = gmtime(&ntime);
  205. return lctime;
  206. }
  207. bool cmCTest::GetTomorrowTag() const
  208. {
  209. return this->Impl->TomorrowTag;
  210. }
  211. std::string cmCTest::CleanString(std::string const& str,
  212. std::string::size_type spos)
  213. {
  214. spos = str.find_first_not_of(" \n\t\r\f\v", spos);
  215. std::string::size_type epos = str.find_last_not_of(" \n\t\r\f\v");
  216. if (spos == std::string::npos) {
  217. return std::string();
  218. }
  219. if (epos != std::string::npos) {
  220. epos = epos - spos + 1;
  221. }
  222. return str.substr(spos, epos);
  223. }
  224. std::string cmCTest::CurrentTime()
  225. {
  226. time_t currenttime = time(nullptr);
  227. struct tm* t = localtime(&currenttime);
  228. // return ::CleanString(ctime(&currenttime));
  229. char current_time[1024];
  230. if (this->Impl->ShortDateFormat) {
  231. strftime(current_time, 1000, "%b %d %H:%M %Z", t);
  232. } else {
  233. strftime(current_time, 1000, "%a %b %d %H:%M:%S %Z %Y", t);
  234. }
  235. cmCTestLog(this, DEBUG, " Current_Time: " << current_time << std::endl);
  236. return cmCTest::CleanString(current_time);
  237. }
  238. std::string cmCTest::GetCostDataFile()
  239. {
  240. std::string fname = this->GetCTestConfiguration("CostDataFile");
  241. if (fname.empty()) {
  242. fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt";
  243. }
  244. return fname;
  245. }
  246. std::string cmCTest::DecodeURL(std::string const& in)
  247. {
  248. std::string out;
  249. for (char const* c = in.c_str(); *c; ++c) {
  250. if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
  251. char buf[3] = { *(c + 1), *(c + 2), 0 };
  252. out.append(1, static_cast<char>(strtoul(buf, nullptr, 16)));
  253. c += 2;
  254. } else {
  255. out.append(1, *c);
  256. }
  257. }
  258. return out;
  259. }
  260. cmCTest::cmCTest()
  261. : Impl(cm::make_unique<Private>(this))
  262. {
  263. std::string envValue;
  264. if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", envValue)) {
  265. this->Impl->OutputTestOutputOnTestFailure = !cmIsOff(envValue);
  266. }
  267. envValue.clear();
  268. if (cmSystemTools::GetEnv("CTEST_PROGRESS_OUTPUT", envValue)) {
  269. this->Impl->TestProgressOutput = !cmIsOff(envValue);
  270. }
  271. envValue.clear();
  272. this->Impl->Parts[PartStart].SetName("Start");
  273. this->Impl->Parts[PartUpdate].SetName("Update");
  274. this->Impl->Parts[PartConfigure].SetName("Configure");
  275. this->Impl->Parts[PartBuild].SetName("Build");
  276. this->Impl->Parts[PartTest].SetName("Test");
  277. this->Impl->Parts[PartCoverage].SetName("Coverage");
  278. this->Impl->Parts[PartMemCheck].SetName("MemCheck");
  279. this->Impl->Parts[PartSubmit].SetName("Submit");
  280. this->Impl->Parts[PartNotes].SetName("Notes");
  281. this->Impl->Parts[PartExtraFiles].SetName("ExtraFiles");
  282. this->Impl->Parts[PartUpload].SetName("Upload");
  283. this->Impl->Parts[PartDone].SetName("Done");
  284. // Fill the part name-to-id map.
  285. for (Part p = PartStart; p != PartCount; p = static_cast<Part>(p + 1)) {
  286. this->Impl
  287. ->PartMap[cmSystemTools::LowerCase(this->Impl->Parts[p].GetName())] = p;
  288. }
  289. // Make sure we can capture the build tool output.
  290. cmSystemTools::EnableVSConsoleOutput();
  291. }
  292. cmCTest::~cmCTest() = default;
  293. cm::optional<size_t> cmCTest::GetParallelLevel() const
  294. {
  295. return this->Impl->ParallelLevel;
  296. }
  297. void cmCTest::SetParallelLevel(cm::optional<size_t> level)
  298. {
  299. this->Impl->ParallelLevel = level;
  300. }
  301. unsigned long cmCTest::GetTestLoad() const
  302. {
  303. return this->Impl->TestLoad;
  304. }
  305. void cmCTest::SetTestLoad(unsigned long load)
  306. {
  307. this->Impl->TestLoad = load;
  308. }
  309. bool cmCTest::ShouldCompressTestOutput()
  310. {
  311. return this->Impl->CompressTestOutput;
  312. }
  313. cmCTest::Part cmCTest::GetPartFromName(std::string const& name)
  314. {
  315. // Look up by lower-case to make names case-insensitive.
  316. std::string lower_name = cmSystemTools::LowerCase(name);
  317. auto const i = this->Impl->PartMap.find(lower_name);
  318. if (i != this->Impl->PartMap.end()) {
  319. return i->second;
  320. }
  321. // The string does not name a valid part.
  322. return PartCount;
  323. }
  324. void cmCTest::Initialize(std::string const& binary_dir)
  325. {
  326. this->Impl->BuildID = "";
  327. for (Part p = PartStart; p != PartCount; p = static_cast<Part>(p + 1)) {
  328. this->Impl->Parts[p].SubmitFiles.clear();
  329. }
  330. if (!this->Impl->InteractiveDebugMode) {
  331. this->BlockTestErrorDiagnostics();
  332. } else {
  333. cmSystemTools::PutEnv("CTEST_INTERACTIVE_DEBUG_MODE=1");
  334. }
  335. this->Impl->BinaryDir = binary_dir;
  336. cmSystemTools::ConvertToUnixSlashes(this->Impl->BinaryDir);
  337. }
  338. bool cmCTest::CreateNewTag(bool quiet)
  339. {
  340. std::string const testingDir = this->Impl->BinaryDir + "/Testing";
  341. std::string const tagfile = testingDir + "/TAG";
  342. auto const result = cmSystemTools::MakeDirectory(testingDir);
  343. if (!result.IsSuccess()) {
  344. cmCTestLog(this, ERROR_MESSAGE,
  345. "Cannot create directory \""
  346. << testingDir << "\": " << result.GetString() << std::endl);
  347. return false;
  348. }
  349. cmCTestOptionalLog(this, DEBUG,
  350. "TestModel: " << this->GetTestGroupString() << std::endl,
  351. quiet);
  352. cmCTestOptionalLog(
  353. this, DEBUG, "TestModel: " << this->Impl->TestModel << std::endl, quiet);
  354. struct tm* lctime = [this]() -> tm* {
  355. if (this->Impl->TestModel == cmCTest::NIGHTLY) {
  356. return this->GetNightlyTime(
  357. this->GetCTestConfiguration("NightlyStartTime"),
  358. this->Impl->TomorrowTag);
  359. }
  360. time_t tctime = time(nullptr);
  361. if (this->Impl->TomorrowTag) {
  362. tctime += (24 * 60 * 60);
  363. }
  364. return gmtime(&tctime);
  365. }();
  366. char datestring[100];
  367. snprintf(datestring, sizeof(datestring), "%04d%02d%02d-%02d%02d",
  368. lctime->tm_year + 1900, lctime->tm_mon + 1, lctime->tm_mday,
  369. lctime->tm_hour, lctime->tm_min);
  370. this->Impl->CurrentTag = datestring;
  371. cmsys::ofstream ofs(tagfile.c_str());
  372. ofs << this->Impl->CurrentTag << std::endl;
  373. ofs << this->GetTestGroupString() << std::endl;
  374. ofs << this->GetTestModelString() << std::endl;
  375. return true;
  376. }
  377. bool cmCTest::ReadExistingTag(bool quiet)
  378. {
  379. std::string const testingDir = this->Impl->BinaryDir + "/Testing";
  380. std::string const tagfile = testingDir + "/TAG";
  381. std::string tag;
  382. std::string group;
  383. std::string modelStr;
  384. int model = cmCTest::UNKNOWN;
  385. cmsys::ifstream tfin(tagfile.c_str());
  386. if (tfin) {
  387. cmSystemTools::GetLineFromStream(tfin, tag);
  388. cmSystemTools::GetLineFromStream(tfin, group);
  389. if (cmSystemTools::GetLineFromStream(tfin, modelStr)) {
  390. model = GetTestModelFromString(modelStr);
  391. }
  392. tfin.close();
  393. }
  394. if (tag.empty()) {
  395. if (!quiet) {
  396. cmCTestLog(this, ERROR_MESSAGE,
  397. "Cannot read existing TAG file in " << testingDir
  398. << std::endl);
  399. }
  400. return false;
  401. }
  402. if (this->Impl->TestModel == cmCTest::UNKNOWN) {
  403. if (model == cmCTest::UNKNOWN) {
  404. cmCTestLog(this, ERROR_MESSAGE,
  405. "TAG file does not contain model and "
  406. "no model specified in start command"
  407. << std::endl);
  408. return false;
  409. }
  410. this->SetTestModel(model);
  411. }
  412. if (model != this->Impl->TestModel && model != cmCTest::UNKNOWN &&
  413. this->Impl->TestModel != cmCTest::UNKNOWN) {
  414. cmCTestOptionalLog(this, WARNING,
  415. "Model given in TAG does not match "
  416. "model given in ctest_start()"
  417. << std::endl,
  418. quiet);
  419. }
  420. if (!this->Impl->SpecificGroup.empty() &&
  421. group != this->Impl->SpecificGroup) {
  422. cmCTestOptionalLog(this, WARNING,
  423. "Group given in TAG does not match "
  424. "group given in ctest_start()"
  425. << std::endl,
  426. quiet);
  427. } else {
  428. this->Impl->SpecificGroup = group;
  429. }
  430. cmCTestOptionalLog(this, OUTPUT,
  431. " Use existing tag: " << tag << " - "
  432. << this->GetTestGroupString()
  433. << std::endl,
  434. quiet);
  435. this->Impl->CurrentTag = tag;
  436. return true;
  437. }
  438. bool cmCTest::UpdateCTestConfiguration()
  439. {
  440. std::string fileName = this->Impl->BinaryDir + "/CTestConfiguration.ini";
  441. if (!cmSystemTools::FileExists(fileName)) {
  442. fileName = this->Impl->BinaryDir + "/DartConfiguration.tcl";
  443. }
  444. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  445. "UpdateCTestConfiguration from :" << fileName << "\n");
  446. if (!cmSystemTools::FileExists(fileName)) {
  447. // No need to exit if we are not producing XML
  448. if (this->Impl->ProduceXML) {
  449. cmCTestLog(this, WARNING, "Cannot find file: " << fileName << std::endl);
  450. return false;
  451. }
  452. } else {
  453. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  454. "Parse Config file:" << fileName << "\n");
  455. // parse the dart test file
  456. cmsys::ifstream fin(fileName.c_str());
  457. if (!fin) {
  458. return false;
  459. }
  460. char buffer[1024];
  461. while (fin) {
  462. buffer[0] = 0;
  463. fin.getline(buffer, 1023);
  464. buffer[1023] = 0;
  465. std::string line = cmCTest::CleanString(buffer);
  466. if (line.empty()) {
  467. continue;
  468. }
  469. while (fin && (line.back() == '\\')) {
  470. line.resize(line.size() - 1);
  471. buffer[0] = 0;
  472. fin.getline(buffer, 1023);
  473. buffer[1023] = 0;
  474. line += cmCTest::CleanString(buffer);
  475. }
  476. if (line[0] == '#') {
  477. continue;
  478. }
  479. std::string::size_type cpos = line.find_first_of(':');
  480. if (cpos == std::string::npos) {
  481. continue;
  482. }
  483. std::string key = line.substr(0, cpos);
  484. std::string value = cmCTest::CleanString(line, cpos + 1);
  485. this->Impl->CTestConfiguration[key] = value;
  486. }
  487. fin.close();
  488. }
  489. if (!this->GetCTestConfiguration("BuildDirectory").empty()) {
  490. this->Impl->BinaryDir = this->GetCTestConfiguration("BuildDirectory");
  491. if (this->Impl->TestDir.empty()) {
  492. cmSystemTools::SetLogicalWorkingDirectory(this->Impl->BinaryDir);
  493. }
  494. }
  495. this->Impl->TimeOut =
  496. std::chrono::seconds(atoi(this->GetCTestConfiguration("TimeOut").c_str()));
  497. std::string const& testLoad = this->GetCTestConfiguration("TestLoad");
  498. if (!testLoad.empty()) {
  499. unsigned long load;
  500. if (cmStrToULong(testLoad, &load)) {
  501. this->SetTestLoad(load);
  502. } else {
  503. cmCTestLog(this, WARNING,
  504. "Invalid value for 'Test Load' : " << testLoad << std::endl);
  505. }
  506. }
  507. if (this->Impl->ProduceXML) {
  508. this->Impl->CompressXMLFiles =
  509. cmIsOn(this->GetCTestConfiguration("CompressSubmission"));
  510. }
  511. return true;
  512. }
  513. void cmCTest::BlockTestErrorDiagnostics()
  514. {
  515. cmSystemTools::PutEnv("DART_TEST_FROM_DART=1");
  516. cmSystemTools::PutEnv("DASHBOARD_TEST_FROM_CTEST=" CMake_VERSION);
  517. #if defined(_WIN32)
  518. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  519. #elif defined(__BEOS__) || defined(__HAIKU__)
  520. disable_debugger(1);
  521. #endif
  522. }
  523. void cmCTest::SetTestModel(int mode)
  524. {
  525. this->Impl->InteractiveDebugMode = false;
  526. this->Impl->TestModel = mode;
  527. }
  528. int cmCTest::GetTestModel() const
  529. {
  530. return this->Impl->TestModel;
  531. }
  532. bool cmCTest::SetTest(std::string const& ttype, bool report)
  533. {
  534. if (cmSystemTools::LowerCase(ttype) == "all") {
  535. for (Part p = PartStart; p != PartCount; p = static_cast<Part>(p + 1)) {
  536. this->Impl->Parts[p].Enable();
  537. }
  538. return true;
  539. }
  540. Part p = this->GetPartFromName(ttype);
  541. if (p != PartCount) {
  542. this->Impl->Parts[p].Enable();
  543. return true;
  544. }
  545. if (report) {
  546. cmCTestLog(this, ERROR_MESSAGE,
  547. "Don't know about test \"" << ttype << "\" yet..."
  548. << std::endl);
  549. }
  550. return false;
  551. }
  552. bool cmCTest::OpenOutputFile(std::string const& path, std::string const& name,
  553. cmGeneratedFileStream& stream, bool compress)
  554. {
  555. std::string testingDir = this->Impl->BinaryDir + "/Testing";
  556. if (!path.empty()) {
  557. testingDir += "/" + path;
  558. }
  559. if (cmSystemTools::FileExists(testingDir)) {
  560. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  561. cmCTestLog(this, ERROR_MESSAGE,
  562. "File " << testingDir
  563. << " is in the place of the testing directory"
  564. << std::endl);
  565. return false;
  566. }
  567. } else {
  568. if (!cmSystemTools::MakeDirectory(testingDir)) {
  569. cmCTestLog(this, ERROR_MESSAGE,
  570. "Cannot create directory " << testingDir << std::endl);
  571. return false;
  572. }
  573. }
  574. std::string filename = testingDir + "/" + name;
  575. stream.Open(filename);
  576. if (!stream) {
  577. cmCTestLog(this, ERROR_MESSAGE,
  578. "Problem opening file: " << filename << std::endl);
  579. return false;
  580. }
  581. if (compress) {
  582. if (this->Impl->CompressXMLFiles) {
  583. stream.SetCompression(true);
  584. }
  585. }
  586. return true;
  587. }
  588. bool cmCTest::AddIfExists(Part part, std::string const& file)
  589. {
  590. if (this->CTestFileExists(file)) {
  591. this->AddSubmitFile(part, file);
  592. } else {
  593. std::string name = cmStrCat(file, ".gz");
  594. if (this->CTestFileExists(name)) {
  595. this->AddSubmitFile(part, file);
  596. } else {
  597. return false;
  598. }
  599. }
  600. return true;
  601. }
  602. bool cmCTest::CTestFileExists(std::string const& filename)
  603. {
  604. std::string testingDir = this->Impl->BinaryDir + "/Testing/" +
  605. this->Impl->CurrentTag + "/" + filename;
  606. return cmSystemTools::FileExists(testingDir);
  607. }
  608. int cmCTest::ProcessSteps()
  609. {
  610. this->Impl->ExtraVerbose = this->Impl->Verbose;
  611. this->Impl->Verbose = true;
  612. this->Impl->ProduceXML = true;
  613. // Minimal dashboard client script configuration.
  614. this->SetCTestConfiguration("BuildDirectory", this->Impl->BinaryDir);
  615. this->UpdateCTestConfiguration();
  616. this->BlockTestErrorDiagnostics();
  617. int res = 0;
  618. cmCTestScriptHandler script(this);
  619. script.CreateCMake();
  620. cmMakefile& mf = *script.GetMakefile();
  621. this->ReadCustomConfigurationFileTree(this->Impl->BinaryDir, &mf);
  622. this->SetTimeLimit(mf.GetDefinition("CTEST_TIME_LIMIT"));
  623. this->SetCMakeVariables(mf);
  624. std::vector<cmListFileArgument> args{
  625. cmListFileArgument("RETURN_VALUE", cmListFileArgument::Unquoted, 0),
  626. cmListFileArgument("return_value", cmListFileArgument::Unquoted, 0),
  627. };
  628. if (this->Impl->Parts[PartStart]) {
  629. auto const func = cmListFileFunction(
  630. "ctest_start", 0, 0,
  631. {
  632. { this->GetTestModelString(), cmListFileArgument::Unquoted, 0 },
  633. { "GROUP", cmListFileArgument::Unquoted, 0 },
  634. { this->GetTestGroupString(), cmListFileArgument::Unquoted, 0 },
  635. });
  636. auto status = cmExecutionStatus(mf);
  637. if (!mf.ExecuteCommand(func, status)) {
  638. return 12;
  639. }
  640. } else if (!this->ReadExistingTag(true) && !this->CreateNewTag(false)) {
  641. cmCTestLog(this, ERROR_MESSAGE,
  642. "Problem initializing the dashboard." << std::endl);
  643. return 12;
  644. }
  645. if (this->Impl->Parts[PartUpdate] &&
  646. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  647. auto const func = cmListFileFunction("ctest_update", 0, 0, args);
  648. auto status = cmExecutionStatus(mf);
  649. if (!mf.ExecuteCommand(func, status)) {
  650. res |= cmCTest::UPDATE_ERRORS;
  651. }
  652. }
  653. if (this->Impl->TestModel == cmCTest::CONTINUOUS &&
  654. mf.GetDefinition("return_value").IsOff()) {
  655. return 0;
  656. }
  657. if (this->Impl->Parts[PartConfigure] &&
  658. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  659. auto const func = cmListFileFunction("ctest_configure", 0, 0, args);
  660. auto status = cmExecutionStatus(mf);
  661. if (!mf.ExecuteCommand(func, status) ||
  662. std::stoi(mf.GetDefinition("return_value")) < 0) {
  663. res |= cmCTest::CONFIGURE_ERRORS;
  664. }
  665. }
  666. if (this->Impl->Parts[PartBuild] &&
  667. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  668. this->UpdateCTestConfiguration();
  669. this->SetCMakeVariables(mf);
  670. auto const func = cmListFileFunction("ctest_build", 0, 0, args);
  671. auto status = cmExecutionStatus(mf);
  672. if (!mf.ExecuteCommand(func, status) ||
  673. std::stoi(mf.GetDefinition("return_value")) < 0) {
  674. res |= cmCTest::BUILD_ERRORS;
  675. }
  676. }
  677. if (this->Impl->Parts[PartTest] &&
  678. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  679. this->UpdateCTestConfiguration();
  680. this->SetCMakeVariables(mf);
  681. auto const func = cmListFileFunction("ctest_test", 0, 0, args);
  682. auto status = cmExecutionStatus(mf);
  683. if (!mf.ExecuteCommand(func, status) ||
  684. std::stoi(mf.GetDefinition("return_value")) < 0) {
  685. res |= cmCTest::TEST_ERRORS;
  686. }
  687. }
  688. if (this->Impl->Parts[PartCoverage] &&
  689. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  690. this->UpdateCTestConfiguration();
  691. this->SetCMakeVariables(mf);
  692. auto const func = cmListFileFunction("ctest_coverage", 0, 0, args);
  693. auto status = cmExecutionStatus(mf);
  694. if (!mf.ExecuteCommand(func, status) ||
  695. std::stoi(mf.GetDefinition("return_value")) < 0) {
  696. res |= cmCTest::COVERAGE_ERRORS;
  697. }
  698. }
  699. if (this->Impl->Parts[PartMemCheck] &&
  700. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  701. this->UpdateCTestConfiguration();
  702. this->SetCMakeVariables(mf);
  703. auto const func = cmListFileFunction("ctest_memcheck", 0, 0, args);
  704. auto status = cmExecutionStatus(mf);
  705. if (!mf.ExecuteCommand(func, status) ||
  706. std::stoi(mf.GetDefinition("return_value")) < 0) {
  707. res |= cmCTest::MEMORY_ERRORS;
  708. }
  709. }
  710. std::string notes_dir = this->Impl->BinaryDir + "/Testing/Notes";
  711. if (cmSystemTools::FileIsDirectory(notes_dir)) {
  712. cmsys::Directory d;
  713. d.Load(notes_dir);
  714. unsigned long kk;
  715. for (kk = 0; kk < d.GetNumberOfFiles(); kk++) {
  716. char const* file = d.GetFile(kk);
  717. std::string fullname = notes_dir + "/" + file;
  718. if (cmSystemTools::FileExists(fullname, true)) {
  719. if (!this->Impl->NotesFiles.empty()) {
  720. this->Impl->NotesFiles += ";";
  721. }
  722. this->Impl->NotesFiles += fullname;
  723. this->Impl->Parts[PartNotes].Enable();
  724. }
  725. }
  726. }
  727. if (this->Impl->Parts[PartNotes]) {
  728. this->UpdateCTestConfiguration();
  729. if (!this->Impl->NotesFiles.empty()) {
  730. this->GenerateNotesFile(script.GetCMake(), this->Impl->NotesFiles);
  731. }
  732. }
  733. if (this->Impl->Parts[PartSubmit]) {
  734. this->UpdateCTestConfiguration();
  735. this->SetCMakeVariables(mf);
  736. std::string count = this->GetCTestConfiguration("CTestSubmitRetryCount");
  737. std::string delay = this->GetCTestConfiguration("CTestSubmitRetryDelay");
  738. auto const func = cmListFileFunction(
  739. "ctest_submit", 0, 0,
  740. {
  741. cmListFileArgument("RETRY_COUNT", cmListFileArgument::Unquoted, 0),
  742. cmListFileArgument(count, cmListFileArgument::Quoted, 0),
  743. cmListFileArgument("RETRY_DELAY", cmListFileArgument::Unquoted, 0),
  744. cmListFileArgument(delay, cmListFileArgument::Quoted, 0),
  745. cmListFileArgument("RETURN_VALUE", cmListFileArgument::Unquoted, 0),
  746. cmListFileArgument("return_value", cmListFileArgument::Unquoted, 0),
  747. });
  748. auto status = cmExecutionStatus(mf);
  749. if (!mf.ExecuteCommand(func, status) ||
  750. std::stoi(mf.GetDefinition("return_value")) < 0) {
  751. res |= cmCTest::SUBMIT_ERRORS;
  752. }
  753. }
  754. return res;
  755. }
  756. std::string cmCTest::GetTestModelString() const
  757. {
  758. switch (this->Impl->TestModel) {
  759. case cmCTest::NIGHTLY:
  760. return "Nightly";
  761. case cmCTest::CONTINUOUS:
  762. return "Continuous";
  763. }
  764. return "Experimental";
  765. }
  766. std::string cmCTest::GetTestGroupString() const
  767. {
  768. if (!this->Impl->SpecificGroup.empty()) {
  769. return this->Impl->SpecificGroup;
  770. }
  771. return this->GetTestModelString();
  772. }
  773. int cmCTest::GetTestModelFromString(std::string const& str)
  774. {
  775. if (str.empty()) {
  776. return cmCTest::EXPERIMENTAL;
  777. }
  778. std::string rstr = cmSystemTools::LowerCase(str);
  779. if (cmHasLiteralPrefix(rstr, "cont")) {
  780. return cmCTest::CONTINUOUS;
  781. }
  782. if (cmHasLiteralPrefix(rstr, "nigh")) {
  783. return cmCTest::NIGHTLY;
  784. }
  785. return cmCTest::EXPERIMENTAL;
  786. }
  787. bool cmCTest::RunMakeCommand(std::string const& command, std::string& output,
  788. int* retVal, char const* dir, cmDuration timeout,
  789. std::ostream& ofs, Encoding encoding)
  790. {
  791. // First generate the command and arguments
  792. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  793. if (args.empty()) {
  794. return false;
  795. }
  796. output.clear();
  797. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
  798. for (auto const& arg : args) {
  799. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
  800. }
  801. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
  802. // Now create process object
  803. cmUVProcessChainBuilder builder;
  804. builder.AddCommand(args).SetMergedBuiltinStreams();
  805. if (dir) {
  806. builder.SetWorkingDirectory(dir);
  807. }
  808. auto chain = builder.Start();
  809. cm::uv_pipe_ptr outputStream;
  810. outputStream.init(chain.GetLoop(), 0);
  811. uv_pipe_open(outputStream, chain.OutputStream());
  812. // Initialize tick's
  813. std::string::size_type tick = 0;
  814. std::string::size_type tick_len = 1024;
  815. std::string::size_type tick_line_len = 50;
  816. cmProcessOutput processOutput(encoding);
  817. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  818. " Each . represents " << tick_len
  819. << " bytes of output\n"
  820. " "
  821. << std::flush);
  822. auto outputHandle = cmUVStreamRead(
  823. outputStream,
  824. [this, &processOutput, &output, &tick, &tick_len, &tick_line_len,
  825. &ofs](std::vector<char> data) {
  826. std::string strdata;
  827. processOutput.DecodeText(data.data(), data.size(), strdata);
  828. for (char& cc : strdata) {
  829. if (cc == 0) {
  830. cc = '\n';
  831. }
  832. }
  833. output.append(strdata);
  834. while (output.size() > (tick * tick_len)) {
  835. tick++;
  836. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
  837. if (tick % tick_line_len == 0 && tick > 0) {
  838. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  839. " Size: " << int((double(output.size()) / 1024.0) + 1)
  840. << "K\n " << std::flush);
  841. }
  842. }
  843. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, strdata);
  844. if (ofs) {
  845. ofs << strdata;
  846. }
  847. },
  848. [this, &processOutput, &output, &ofs]() {
  849. std::string strdata;
  850. processOutput.DecodeText(std::string(), strdata);
  851. if (!strdata.empty()) {
  852. output.append(strdata);
  853. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, strdata);
  854. if (ofs) {
  855. ofs << strdata;
  856. }
  857. }
  858. });
  859. bool finished = chain.Wait(static_cast<uint64_t>(timeout.count() * 1000.0));
  860. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  861. " Size of output: " << int(double(output.size()) / 1024.0) << "K"
  862. << std::endl);
  863. if (finished) {
  864. auto const& status = chain.GetStatus(0);
  865. auto exception = status.GetException();
  866. switch (exception.first) {
  867. case cmUVProcessChain::ExceptionCode::None:
  868. *retVal = static_cast<int>(status.ExitStatus);
  869. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  870. "Command exited with the value: " << *retVal << std::endl);
  871. break;
  872. case cmUVProcessChain::ExceptionCode::Spawn:
  873. output += "\n*** ERROR executing: ";
  874. output += exception.second;
  875. output += "\n***The build process failed.";
  876. cmCTestLog(this, ERROR_MESSAGE,
  877. "There was an error: " << exception.second << std::endl);
  878. break;
  879. default:
  880. *retVal = static_cast<int>(exception.first);
  881. cmCTestLog(this, WARNING,
  882. "There was an exception: " << *retVal << std::endl);
  883. break;
  884. }
  885. } else {
  886. cmCTestLog(this, WARNING, "There was a timeout" << std::endl);
  887. }
  888. return true;
  889. }
  890. std::string cmCTest::SafeBuildIdField(std::string const& value)
  891. {
  892. return value.empty() ? "(empty)" : value;
  893. }
  894. void cmCTest::StartXML(cmXMLWriter& xml, cmake* cm, bool append)
  895. {
  896. if (this->Impl->CurrentTag.empty()) {
  897. cmCTestLog(this, ERROR_MESSAGE,
  898. "Current Tag empty, this may mean"
  899. " NightlStartTime was not set correctly."
  900. << std::endl);
  901. cmSystemTools::SetFatalErrorOccurred();
  902. }
  903. // find out about the system
  904. cmsys::SystemInformation info;
  905. info.RunCPUCheck();
  906. info.RunOSCheck();
  907. info.RunMemoryCheck();
  908. std::string buildname =
  909. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  910. std::string stamp = cmCTest::SafeBuildIdField(this->Impl->CurrentTag + "-" +
  911. this->GetTestGroupString());
  912. std::string site =
  913. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("Site"));
  914. xml.StartDocument();
  915. xml.StartElement("Site");
  916. xml.Attribute("BuildName", buildname);
  917. xml.BreakAttributes();
  918. xml.Attribute("BuildStamp", stamp);
  919. xml.Attribute("Name", site);
  920. xml.Attribute("Generator",
  921. std::string("ctest-") + cmVersion::GetCMakeVersion());
  922. if (append) {
  923. xml.Attribute("Append", "true");
  924. }
  925. xml.Attribute("CompilerName", this->GetCTestConfiguration("Compiler"));
  926. xml.Attribute("CompilerVersion",
  927. this->GetCTestConfiguration("CompilerVersion"));
  928. xml.Attribute("OSName", info.GetOSName());
  929. xml.Attribute("Hostname", info.GetHostname());
  930. xml.Attribute("OSRelease", info.GetOSRelease());
  931. xml.Attribute("OSVersion", info.GetOSVersion());
  932. xml.Attribute("OSPlatform", info.GetOSPlatform());
  933. xml.Attribute("Is64Bits", info.Is64Bits());
  934. xml.Attribute("VendorString", info.GetVendorString());
  935. xml.Attribute("VendorID", info.GetVendorID());
  936. xml.Attribute("FamilyID", info.GetFamilyID());
  937. xml.Attribute("ModelID", info.GetModelID());
  938. xml.Attribute("ModelName", info.GetModelName());
  939. xml.Attribute("ProcessorCacheSize", info.GetProcessorCacheSize());
  940. xml.Attribute("NumberOfLogicalCPU", info.GetNumberOfLogicalCPU());
  941. xml.Attribute("NumberOfPhysicalCPU", info.GetNumberOfPhysicalCPU());
  942. xml.Attribute("TotalVirtualMemory", info.GetTotalVirtualMemory());
  943. xml.Attribute("TotalPhysicalMemory", info.GetTotalPhysicalMemory());
  944. xml.Attribute("LogicalProcessorsPerPhysical",
  945. info.GetLogicalProcessorsPerPhysical());
  946. xml.Attribute("ProcessorClockFrequency", info.GetProcessorClockFrequency());
  947. std::string changeId = this->GetCTestConfiguration("ChangeId");
  948. if (!changeId.empty()) {
  949. xml.Attribute("ChangeId", changeId);
  950. }
  951. this->AddSiteProperties(xml, cm);
  952. }
  953. void cmCTest::AddSiteProperties(cmXMLWriter& xml, cmake* cm)
  954. {
  955. // This code should go when cdash is changed to use labels only
  956. cmValue subproject = cm->GetState()->GetGlobalProperty("SubProject");
  957. if (subproject) {
  958. xml.StartElement("Subproject");
  959. xml.Attribute("name", *subproject);
  960. cmValue labels = cm->GetState()->GetGlobalProperty("SubProjectLabels");
  961. if (labels) {
  962. xml.StartElement("Labels");
  963. cmList args{ *labels };
  964. for (std::string const& i : args) {
  965. xml.Element("Label", i);
  966. }
  967. xml.EndElement();
  968. }
  969. xml.EndElement();
  970. }
  971. // This code should stay when cdash only does label based sub-projects
  972. cmValue label = cm->GetState()->GetGlobalProperty("Label");
  973. if (label) {
  974. xml.StartElement("Labels");
  975. xml.Element("Label", *label);
  976. xml.EndElement();
  977. }
  978. }
  979. void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
  980. {
  981. for (std::string const& subproj : this->GetLabelsForSubprojects()) {
  982. xml.StartElement("Subproject");
  983. xml.Attribute("name", subproj);
  984. xml.Element("Label", subproj);
  985. xml.EndElement(); // Subproject
  986. }
  987. }
  988. std::vector<std::string> cmCTest::GetLabelsForSubprojects()
  989. {
  990. std::string labelsForSubprojects =
  991. this->GetCTestConfiguration("LabelsForSubprojects");
  992. cmList subprojects{ labelsForSubprojects };
  993. // sort the array
  994. std::sort(subprojects.begin(), subprojects.end());
  995. // remove duplicates
  996. auto new_end = std::unique(subprojects.begin(), subprojects.end());
  997. subprojects.erase(new_end, subprojects.end());
  998. return std::move(subprojects.data());
  999. }
  1000. void cmCTest::EndXML(cmXMLWriter& xml)
  1001. {
  1002. xml.EndElement(); // Site
  1003. xml.EndDocument();
  1004. }
  1005. int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml, cmake* cm,
  1006. std::vector<std::string> const& files)
  1007. {
  1008. std::string buildname =
  1009. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1010. xml.StartDocument();
  1011. xml.ProcessingInstruction("xml-stylesheet",
  1012. "type=\"text/xsl\" "
  1013. "href=\"Dart/Source/Server/XSL/Build.xsl "
  1014. "<file:///Dart/Source/Server/XSL/Build.xsl> \"");
  1015. xml.StartElement("Site");
  1016. xml.Attribute("BuildName", buildname);
  1017. xml.Attribute("BuildStamp",
  1018. this->Impl->CurrentTag + "-" + this->GetTestGroupString());
  1019. xml.Attribute("Name", this->GetCTestConfiguration("Site"));
  1020. xml.Attribute("Generator",
  1021. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1022. this->AddSiteProperties(xml, cm);
  1023. xml.StartElement("Notes");
  1024. for (std::string const& file : files) {
  1025. cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
  1026. std::string note_time = this->CurrentTime();
  1027. xml.StartElement("Note");
  1028. xml.Attribute("Name", file);
  1029. xml.Element("Time", std::chrono::system_clock::now());
  1030. xml.Element("DateTime", note_time);
  1031. xml.StartElement("Text");
  1032. cmsys::ifstream ifs(file.c_str());
  1033. if (ifs) {
  1034. std::string line;
  1035. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1036. xml.Content(line);
  1037. xml.Content("\n");
  1038. }
  1039. ifs.close();
  1040. } else {
  1041. xml.Content("Problem reading file: " + file + "\n");
  1042. cmCTestLog(this, ERROR_MESSAGE,
  1043. "Problem reading file: " << file << " while creating notes"
  1044. << std::endl);
  1045. }
  1046. xml.EndElement(); // Text
  1047. xml.EndElement(); // Note
  1048. }
  1049. xml.EndElement(); // Notes
  1050. xml.EndElement(); // Site
  1051. xml.EndDocument();
  1052. return 1;
  1053. }
  1054. int cmCTest::GenerateNotesFile(cmake* cm,
  1055. std::vector<std::string> const& files)
  1056. {
  1057. cmGeneratedFileStream ofs;
  1058. if (!this->OpenOutputFile(this->Impl->CurrentTag, "Notes.xml", ofs)) {
  1059. cmCTestLog(this, ERROR_MESSAGE, "Cannot open notes file" << std::endl);
  1060. return 1;
  1061. }
  1062. cmXMLWriter xml(ofs);
  1063. this->GenerateCTestNotesOutput(xml, cm, files);
  1064. return 0;
  1065. }
  1066. int cmCTest::GenerateNotesFile(cmake* cm, std::string const& cfiles)
  1067. {
  1068. if (cfiles.empty()) {
  1069. return 1;
  1070. }
  1071. cmCTestLog(this, OUTPUT, "Create notes file" << std::endl);
  1072. std::vector<std::string> const files =
  1073. cmSystemTools::SplitString(cfiles, ';');
  1074. if (files.empty()) {
  1075. return 1;
  1076. }
  1077. return this->GenerateNotesFile(cm, files);
  1078. }
  1079. int cmCTest::GenerateDoneFile()
  1080. {
  1081. cmGeneratedFileStream ofs;
  1082. if (!this->OpenOutputFile(this->Impl->CurrentTag, "Done.xml", ofs)) {
  1083. cmCTestLog(this, ERROR_MESSAGE, "Cannot open done file" << std::endl);
  1084. return 1;
  1085. }
  1086. cmXMLWriter xml(ofs);
  1087. xml.StartDocument();
  1088. xml.StartElement("Done");
  1089. xml.Element("buildId", this->Impl->BuildID);
  1090. xml.Element("time", std::chrono::system_clock::now());
  1091. xml.EndElement(); // Done
  1092. xml.EndDocument();
  1093. return 0;
  1094. }
  1095. std::string cmCTest::Base64GzipEncodeFile(std::string const& file)
  1096. {
  1097. // Temporarily change to the file's directory so the tar gets created
  1098. // with a flat directory structure.
  1099. cmWorkingDirectory workdir(cmSystemTools::GetParentDirectory(file));
  1100. if (workdir.Failed()) {
  1101. cmCTestLog(this, ERROR_MESSAGE, workdir.GetError() << std::endl);
  1102. return "";
  1103. }
  1104. std::string tarFile = file + "_temp.tar.gz";
  1105. std::vector<std::string> files;
  1106. files.push_back(file);
  1107. if (!cmSystemTools::CreateTar(tarFile, files, {},
  1108. cmSystemTools::TarCompressGZip, false)) {
  1109. cmCTestLog(this, ERROR_MESSAGE,
  1110. "Error creating tar while "
  1111. "encoding file: "
  1112. << file << std::endl);
  1113. return "";
  1114. }
  1115. std::string base64 = this->Base64EncodeFile(tarFile);
  1116. cmSystemTools::RemoveFile(tarFile);
  1117. return base64;
  1118. }
  1119. std::string cmCTest::Base64EncodeFile(std::string const& file)
  1120. {
  1121. size_t const len = cmSystemTools::FileLength(file);
  1122. cmsys::ifstream ifs(file.c_str(),
  1123. std::ios::in
  1124. #ifdef _WIN32
  1125. | std::ios::binary
  1126. #endif
  1127. );
  1128. std::vector<char> file_buffer(len + 1);
  1129. ifs.read(file_buffer.data(), len);
  1130. ifs.close();
  1131. std::vector<char> encoded_buffer((len * 3) / 2 + 5);
  1132. size_t const rlen = cmsysBase64_Encode(
  1133. reinterpret_cast<unsigned char*>(file_buffer.data()), len,
  1134. reinterpret_cast<unsigned char*>(encoded_buffer.data()), 1);
  1135. return std::string(encoded_buffer.data(), rlen);
  1136. }
  1137. bool cmCTest::SubmitExtraFiles(std::vector<std::string> const& files)
  1138. {
  1139. for (std::string const& file : files) {
  1140. if (!cmSystemTools::FileExists(file)) {
  1141. cmCTestLog(this, ERROR_MESSAGE,
  1142. "Cannot find extra file: " << file << " to submit."
  1143. << std::endl);
  1144. return false;
  1145. }
  1146. this->AddSubmitFile(PartExtraFiles, file);
  1147. }
  1148. return true;
  1149. }
  1150. bool cmCTest::SubmitExtraFiles(std::string const& cfiles)
  1151. {
  1152. if (cfiles.empty()) {
  1153. return true;
  1154. }
  1155. cmCTestLog(this, OUTPUT, "Submit extra files" << std::endl);
  1156. std::vector<std::string> const files =
  1157. cmSystemTools::SplitString(cfiles, ';');
  1158. if (files.empty()) {
  1159. return true;
  1160. }
  1161. return this->SubmitExtraFiles(files);
  1162. }
  1163. // for a -D argument convert the next argument into
  1164. // the proper list of dashboard steps via SetTest
  1165. bool cmCTest::AddTestsForDashboardType(std::string const& targ)
  1166. {
  1167. if (targ == "Experimental") {
  1168. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1169. this->SetTest("Start");
  1170. this->SetTest("Configure");
  1171. this->SetTest("Build");
  1172. this->SetTest("Test");
  1173. this->SetTest("Coverage");
  1174. this->SetTest("Submit");
  1175. } else if (targ == "ExperimentalStart") {
  1176. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1177. this->SetTest("Start");
  1178. } else if (targ == "ExperimentalUpdate") {
  1179. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1180. this->SetTest("Update");
  1181. } else if (targ == "ExperimentalConfigure") {
  1182. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1183. this->SetTest("Configure");
  1184. } else if (targ == "ExperimentalBuild") {
  1185. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1186. this->SetTest("Build");
  1187. } else if (targ == "ExperimentalTest") {
  1188. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1189. this->SetTest("Test");
  1190. } else if (targ == "ExperimentalMemCheck" || targ == "ExperimentalPurify") {
  1191. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1192. this->SetTest("MemCheck");
  1193. } else if (targ == "ExperimentalCoverage") {
  1194. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1195. this->SetTest("Coverage");
  1196. } else if (targ == "ExperimentalSubmit") {
  1197. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1198. this->SetTest("Submit");
  1199. } else if (targ == "Continuous") {
  1200. this->SetTestModel(cmCTest::CONTINUOUS);
  1201. this->SetTest("Start");
  1202. this->SetTest("Update");
  1203. this->SetTest("Configure");
  1204. this->SetTest("Build");
  1205. this->SetTest("Test");
  1206. this->SetTest("Coverage");
  1207. this->SetTest("Submit");
  1208. } else if (targ == "ContinuousStart") {
  1209. this->SetTestModel(cmCTest::CONTINUOUS);
  1210. this->SetTest("Start");
  1211. } else if (targ == "ContinuousUpdate") {
  1212. this->SetTestModel(cmCTest::CONTINUOUS);
  1213. this->SetTest("Update");
  1214. } else if (targ == "ContinuousConfigure") {
  1215. this->SetTestModel(cmCTest::CONTINUOUS);
  1216. this->SetTest("Configure");
  1217. } else if (targ == "ContinuousBuild") {
  1218. this->SetTestModel(cmCTest::CONTINUOUS);
  1219. this->SetTest("Build");
  1220. } else if (targ == "ContinuousTest") {
  1221. this->SetTestModel(cmCTest::CONTINUOUS);
  1222. this->SetTest("Test");
  1223. } else if (targ == "ContinuousMemCheck" || targ == "ContinuousPurify") {
  1224. this->SetTestModel(cmCTest::CONTINUOUS);
  1225. this->SetTest("MemCheck");
  1226. } else if (targ == "ContinuousCoverage") {
  1227. this->SetTestModel(cmCTest::CONTINUOUS);
  1228. this->SetTest("Coverage");
  1229. } else if (targ == "ContinuousSubmit") {
  1230. this->SetTestModel(cmCTest::CONTINUOUS);
  1231. this->SetTest("Submit");
  1232. } else if (targ == "Nightly") {
  1233. this->SetTestModel(cmCTest::NIGHTLY);
  1234. this->SetTest("Start");
  1235. this->SetTest("Update");
  1236. this->SetTest("Configure");
  1237. this->SetTest("Build");
  1238. this->SetTest("Test");
  1239. this->SetTest("Coverage");
  1240. this->SetTest("Submit");
  1241. } else if (targ == "NightlyStart") {
  1242. this->SetTestModel(cmCTest::NIGHTLY);
  1243. this->SetTest("Start");
  1244. } else if (targ == "NightlyUpdate") {
  1245. this->SetTestModel(cmCTest::NIGHTLY);
  1246. this->SetTest("Update");
  1247. } else if (targ == "NightlyConfigure") {
  1248. this->SetTestModel(cmCTest::NIGHTLY);
  1249. this->SetTest("Configure");
  1250. } else if (targ == "NightlyBuild") {
  1251. this->SetTestModel(cmCTest::NIGHTLY);
  1252. this->SetTest("Build");
  1253. } else if (targ == "NightlyTest") {
  1254. this->SetTestModel(cmCTest::NIGHTLY);
  1255. this->SetTest("Test");
  1256. } else if (targ == "NightlyMemCheck" || targ == "NightlyPurify") {
  1257. this->SetTestModel(cmCTest::NIGHTLY);
  1258. this->SetTest("MemCheck");
  1259. } else if (targ == "NightlyCoverage") {
  1260. this->SetTestModel(cmCTest::NIGHTLY);
  1261. this->SetTest("Coverage");
  1262. } else if (targ == "NightlySubmit") {
  1263. this->SetTestModel(cmCTest::NIGHTLY);
  1264. this->SetTest("Submit");
  1265. } else if (targ == "MemoryCheck") {
  1266. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1267. this->SetTest("Start");
  1268. this->SetTest("Configure");
  1269. this->SetTest("Build");
  1270. this->SetTest("MemCheck");
  1271. this->SetTest("Coverage");
  1272. this->SetTest("Submit");
  1273. } else if (targ == "NightlyMemoryCheck") {
  1274. this->SetTestModel(cmCTest::NIGHTLY);
  1275. this->SetTest("Start");
  1276. this->SetTest("Update");
  1277. this->SetTest("Configure");
  1278. this->SetTest("Build");
  1279. this->SetTest("MemCheck");
  1280. this->SetTest("Coverage");
  1281. this->SetTest("Submit");
  1282. } else {
  1283. return false;
  1284. }
  1285. return true;
  1286. }
  1287. void cmCTest::ErrorMessageUnknownDashDValue(std::string const& val)
  1288. {
  1289. cmCTestLog(this, ERROR_MESSAGE,
  1290. "CTest -D called with incorrect option: " << val << '\n');
  1291. cmCTestLog(this, ERROR_MESSAGE,
  1292. "Available options are:\n"
  1293. " ctest -D Continuous\n"
  1294. " ctest -D Continuous(Start|Update|Configure|Build)\n"
  1295. " ctest -D Continuous(Test|Coverage|MemCheck|Submit)\n"
  1296. " ctest -D Experimental\n"
  1297. " ctest -D Experimental(Start|Update|Configure|Build)\n"
  1298. " ctest -D Experimental(Test|Coverage|MemCheck|Submit)\n"
  1299. " ctest -D Nightly\n"
  1300. " ctest -D Nightly(Start|Update|Configure|Build)\n"
  1301. " ctest -D Nightly(Test|Coverage|MemCheck|Submit)\n"
  1302. " ctest -D NightlyMemoryCheck\n");
  1303. }
  1304. bool cmCTest::CheckArgument(std::string const& arg, cm::string_view varg1,
  1305. char const* varg2)
  1306. {
  1307. return (arg == varg1) || (varg2 && arg == varg2);
  1308. }
  1309. bool cmCTest::ProgressOutputSupportedByConsole()
  1310. {
  1311. return cm::StdIo::Out().Kind() == cm::StdIo::TermKind::VT100;
  1312. }
  1313. bool cmCTest::ColoredOutputSupportedByConsole()
  1314. {
  1315. std::string clicolor_force;
  1316. if (cmSystemTools::GetEnv("CLICOLOR_FORCE", clicolor_force) &&
  1317. !clicolor_force.empty() && clicolor_force != "0") {
  1318. return true;
  1319. }
  1320. std::string clicolor;
  1321. if (cmSystemTools::GetEnv("CLICOLOR", clicolor) && clicolor == "0") {
  1322. return false;
  1323. }
  1324. return cm::StdIo::Out().Kind() == cm::StdIo::TermKind::VT100;
  1325. }
  1326. bool cmCTest::AddVariableDefinition(std::string const& arg)
  1327. {
  1328. std::string name;
  1329. std::string value;
  1330. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  1331. if (cmake::ParseCacheEntry(arg, name, value, type)) {
  1332. this->Impl->Definitions[name] = value;
  1333. return true;
  1334. }
  1335. return false;
  1336. }
  1337. bool cmCTest::SetArgsFromPreset(std::string const& presetName,
  1338. bool listPresets)
  1339. {
  1340. auto const workingDirectory = cmSystemTools::GetLogicalWorkingDirectory();
  1341. cmCMakePresetsGraph settingsFile;
  1342. auto result = settingsFile.ReadProjectPresets(workingDirectory);
  1343. if (result != true) {
  1344. cmSystemTools::Error(cmStrCat("Could not read presets from ",
  1345. workingDirectory, ":\n",
  1346. settingsFile.parseState.GetErrorMessage()));
  1347. return false;
  1348. }
  1349. if (listPresets) {
  1350. settingsFile.PrintTestPresetList();
  1351. return true;
  1352. }
  1353. auto presetPair = settingsFile.TestPresets.find(presetName);
  1354. if (presetPair == settingsFile.TestPresets.end()) {
  1355. cmSystemTools::Error(cmStrCat("No such test preset in ", workingDirectory,
  1356. ": \"", presetName, '"'));
  1357. settingsFile.PrintTestPresetList();
  1358. return false;
  1359. }
  1360. if (presetPair->second.Unexpanded.Hidden) {
  1361. cmSystemTools::Error(cmStrCat("Cannot use hidden test preset in ",
  1362. workingDirectory, ": \"", presetName, '"'));
  1363. settingsFile.PrintTestPresetList();
  1364. return false;
  1365. }
  1366. auto const& expandedPreset = presetPair->second.Expanded;
  1367. if (!expandedPreset) {
  1368. cmSystemTools::Error(cmStrCat("Could not evaluate test preset \"",
  1369. presetName, "\": Invalid macro expansion"));
  1370. settingsFile.PrintTestPresetList();
  1371. return false;
  1372. }
  1373. if (!expandedPreset->ConditionResult) {
  1374. cmSystemTools::Error(cmStrCat("Cannot use disabled test preset in ",
  1375. workingDirectory, ": \"", presetName, '"'));
  1376. settingsFile.PrintTestPresetList();
  1377. return false;
  1378. }
  1379. auto configurePresetPair =
  1380. settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
  1381. if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
  1382. cmSystemTools::Error(cmStrCat("No such configure preset in ",
  1383. workingDirectory, ": \"",
  1384. expandedPreset->ConfigurePreset, '"'));
  1385. settingsFile.PrintConfigurePresetList();
  1386. return false;
  1387. }
  1388. if (configurePresetPair->second.Unexpanded.Hidden) {
  1389. cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
  1390. workingDirectory, ": \"",
  1391. expandedPreset->ConfigurePreset, '"'));
  1392. settingsFile.PrintConfigurePresetList();
  1393. return false;
  1394. }
  1395. auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
  1396. if (!expandedConfigurePreset) {
  1397. cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
  1398. expandedPreset->ConfigurePreset,
  1399. "\": Invalid macro expansion"));
  1400. return false;
  1401. }
  1402. auto presetEnvironment = expandedPreset->Environment;
  1403. for (auto const& var : presetEnvironment) {
  1404. if (var.second) {
  1405. cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
  1406. }
  1407. }
  1408. if (!expandedPreset->Configuration.empty()) {
  1409. this->SetConfigType(expandedPreset->Configuration);
  1410. }
  1411. // Set build directory to value specified by the configure preset.
  1412. this->AddCTestConfigurationOverwrite(
  1413. cmStrCat("BuildDirectory=", expandedConfigurePreset->BinaryDir));
  1414. for (auto const& kvp : expandedPreset->OverwriteConfigurationFile) {
  1415. this->AddCTestConfigurationOverwrite(kvp);
  1416. }
  1417. if (expandedPreset->Output) {
  1418. this->Impl->TestProgressOutput =
  1419. expandedPreset->Output->ShortProgress.value_or(false);
  1420. if (expandedPreset->Output->Verbosity) {
  1421. auto const& verbosity = *expandedPreset->Output->Verbosity;
  1422. switch (verbosity) {
  1423. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1424. Extra:
  1425. this->Impl->ExtraVerbose = true;
  1426. CM_FALLTHROUGH;
  1427. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1428. Verbose:
  1429. this->Impl->Verbose = true;
  1430. break;
  1431. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1432. Default:
  1433. default:
  1434. // leave default settings
  1435. break;
  1436. }
  1437. }
  1438. this->Impl->Debug = expandedPreset->Output->Debug.value_or(false);
  1439. this->Impl->OutputTestOutputOnTestFailure =
  1440. expandedPreset->Output->OutputOnFailure.value_or(false);
  1441. this->Impl->Quiet = expandedPreset->Output->Quiet.value_or(false);
  1442. if (!expandedPreset->Output->OutputLogFile.empty()) {
  1443. this->SetOutputLogFileName(expandedPreset->Output->OutputLogFile);
  1444. }
  1445. if (!expandedPreset->Output->OutputJUnitFile.empty()) {
  1446. this->SetOutputJUnitFileName(expandedPreset->Output->OutputJUnitFile);
  1447. }
  1448. this->Impl->LabelSummary =
  1449. expandedPreset->Output->LabelSummary.value_or(true);
  1450. this->Impl->SubprojectSummary =
  1451. expandedPreset->Output->SubprojectSummary.value_or(true);
  1452. if (expandedPreset->Output->MaxPassedTestOutputSize) {
  1453. this->Impl->TestOptions.OutputSizePassed =
  1454. *expandedPreset->Output->MaxPassedTestOutputSize;
  1455. }
  1456. if (expandedPreset->Output->MaxFailedTestOutputSize) {
  1457. this->Impl->TestOptions.OutputSizeFailed =
  1458. *expandedPreset->Output->MaxFailedTestOutputSize;
  1459. }
  1460. if (expandedPreset->Output->TestOutputTruncation) {
  1461. this->Impl->TestOptions.OutputTruncation =
  1462. *expandedPreset->Output->TestOutputTruncation;
  1463. }
  1464. if (expandedPreset->Output->MaxTestNameWidth) {
  1465. this->Impl->MaxTestNameWidth = *expandedPreset->Output->MaxTestNameWidth;
  1466. }
  1467. }
  1468. if (expandedPreset->Filter) {
  1469. if (expandedPreset->Filter->Include) {
  1470. this->Impl->TestOptions.IncludeRegularExpression =
  1471. expandedPreset->Filter->Include->Name;
  1472. if (!expandedPreset->Filter->Include->Label.empty()) {
  1473. this->Impl->TestOptions.LabelRegularExpression.push_back(
  1474. expandedPreset->Filter->Include->Label);
  1475. }
  1476. if (expandedPreset->Filter->Include->Index) {
  1477. if (expandedPreset->Filter->Include->Index->IndexFile.empty()) {
  1478. auto const& start = expandedPreset->Filter->Include->Index->Start;
  1479. auto const& end = expandedPreset->Filter->Include->Index->End;
  1480. auto const& stride = expandedPreset->Filter->Include->Index->Stride;
  1481. std::string indexOptions;
  1482. indexOptions += (start ? std::to_string(*start) : "") + ",";
  1483. indexOptions += (end ? std::to_string(*end) : "") + ",";
  1484. indexOptions += (stride ? std::to_string(*stride) : "") + ",";
  1485. indexOptions +=
  1486. cmJoin(expandedPreset->Filter->Include->Index->SpecificTests, ",");
  1487. this->Impl->TestOptions.TestsToRunInformation = indexOptions;
  1488. } else {
  1489. this->Impl->TestOptions.TestsToRunInformation =
  1490. expandedPreset->Filter->Include->Index->IndexFile;
  1491. }
  1492. }
  1493. this->Impl->TestOptions.UseUnion =
  1494. expandedPreset->Filter->Include->UseUnion.value_or(false);
  1495. }
  1496. if (expandedPreset->Filter->Exclude) {
  1497. this->Impl->TestOptions.ExcludeRegularExpression =
  1498. expandedPreset->Filter->Exclude->Name;
  1499. if (!expandedPreset->Filter->Exclude->Label.empty()) {
  1500. this->Impl->TestOptions.ExcludeLabelRegularExpression.push_back(
  1501. expandedPreset->Filter->Exclude->Label);
  1502. }
  1503. if (expandedPreset->Filter->Exclude->Fixtures) {
  1504. this->Impl->TestOptions.ExcludeFixtureRegularExpression =
  1505. expandedPreset->Filter->Exclude->Fixtures->Any;
  1506. this->Impl->TestOptions.ExcludeFixtureSetupRegularExpression =
  1507. expandedPreset->Filter->Exclude->Fixtures->Setup;
  1508. this->Impl->TestOptions.ExcludeFixtureCleanupRegularExpression =
  1509. expandedPreset->Filter->Exclude->Fixtures->Cleanup;
  1510. }
  1511. }
  1512. }
  1513. if (expandedPreset->Execution) {
  1514. this->Impl->StopOnFailure =
  1515. expandedPreset->Execution->StopOnFailure.value_or(false);
  1516. this->Impl->Failover =
  1517. expandedPreset->Execution->EnableFailover.value_or(false);
  1518. if (expandedPreset->Execution->Jobs) {
  1519. auto jobs = *expandedPreset->Execution->Jobs;
  1520. this->SetParallelLevel(jobs);
  1521. this->Impl->ParallelLevelSetInCli = true;
  1522. }
  1523. this->Impl->TestOptions.ResourceSpecFile =
  1524. expandedPreset->Execution->ResourceSpecFile;
  1525. if (expandedPreset->Execution->TestLoad) {
  1526. auto testLoad = *expandedPreset->Execution->TestLoad;
  1527. this->SetTestLoad(testLoad);
  1528. }
  1529. if (expandedPreset->Execution->ShowOnly) {
  1530. this->Impl->ShowOnly = true;
  1531. switch (*expandedPreset->Execution->ShowOnly) {
  1532. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::ShowOnlyEnum::
  1533. JsonV1:
  1534. this->Impl->Quiet = true;
  1535. this->Impl->OutputAsJson = true;
  1536. this->Impl->OutputAsJsonVersion = 1;
  1537. break;
  1538. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::ShowOnlyEnum::
  1539. Human:
  1540. // intentional fallthrough (human is the default)
  1541. default:
  1542. break;
  1543. }
  1544. }
  1545. if (expandedPreset->Execution->Repeat) {
  1546. this->Impl->RepeatCount = expandedPreset->Execution->Repeat->Count;
  1547. switch (expandedPreset->Execution->Repeat->Mode) {
  1548. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1549. ModeEnum::UntilFail:
  1550. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  1551. break;
  1552. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1553. ModeEnum::UntilPass:
  1554. this->Impl->RepeatMode = cmCTest::Repeat::UntilPass;
  1555. break;
  1556. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1557. ModeEnum::AfterTimeout:
  1558. this->Impl->RepeatMode = cmCTest::Repeat::AfterTimeout;
  1559. break;
  1560. default:
  1561. // should never default since mode is required
  1562. return false;
  1563. }
  1564. }
  1565. if (expandedPreset->Execution->InteractiveDebugging) {
  1566. this->Impl->InteractiveDebugMode =
  1567. *expandedPreset->Execution->InteractiveDebugging;
  1568. }
  1569. if (expandedPreset->Execution->ScheduleRandom.value_or(false)) {
  1570. this->Impl->ScheduleType = "Random";
  1571. }
  1572. if (expandedPreset->Execution->Timeout) {
  1573. this->Impl->GlobalTimeout =
  1574. cmDuration(*expandedPreset->Execution->Timeout);
  1575. }
  1576. if (expandedPreset->Execution->NoTestsAction) {
  1577. switch (*expandedPreset->Execution->NoTestsAction) {
  1578. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1579. NoTestsActionEnum::Error:
  1580. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  1581. break;
  1582. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1583. NoTestsActionEnum::Ignore:
  1584. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  1585. break;
  1586. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1587. NoTestsActionEnum::Default:
  1588. break;
  1589. default:
  1590. // should never default
  1591. return false;
  1592. }
  1593. }
  1594. }
  1595. return true;
  1596. }
  1597. // the main entry point of ctest, called from main
  1598. int cmCTest::Run(std::vector<std::string> const& args)
  1599. {
  1600. char const* ctestExec = "ctest";
  1601. bool cmakeAndTest = false;
  1602. bool processSteps = false;
  1603. bool SRArgumentSpecified = false;
  1604. std::vector<std::pair<std::string, bool>> runScripts;
  1605. // copy the command line
  1606. cm::append(this->Impl->InitialCommandLineArguments, args);
  1607. // check if a test preset was specified
  1608. bool listPresets =
  1609. find(args.begin(), args.end(), "--list-presets") != args.end();
  1610. auto it =
  1611. std::find_if(args.begin(), args.end(), [](std::string const& arg) -> bool {
  1612. return arg == "--preset" || cmHasLiteralPrefix(arg, "--preset=");
  1613. });
  1614. if (listPresets || it != args.end()) {
  1615. std::string errormsg;
  1616. bool success;
  1617. if (listPresets) {
  1618. // If listing presets we don't need a presetName
  1619. success = this->SetArgsFromPreset("", listPresets);
  1620. } else {
  1621. if (cmHasLiteralPrefix(*it, "--preset=")) {
  1622. auto const& presetName = it->substr(9);
  1623. success = this->SetArgsFromPreset(presetName, listPresets);
  1624. } else if (++it != args.end()) {
  1625. auto const& presetName = *it;
  1626. success = this->SetArgsFromPreset(presetName, listPresets);
  1627. } else {
  1628. cmSystemTools::Error("'--preset' requires an argument");
  1629. success = false;
  1630. }
  1631. }
  1632. if (listPresets) {
  1633. return success ? 0 : 1;
  1634. }
  1635. if (!success) {
  1636. return 1;
  1637. }
  1638. }
  1639. auto const dashD = [this, &processSteps](std::string const& targ) -> bool {
  1640. // AddTestsForDashboard parses the dashboard type and converts it
  1641. // into the separate stages
  1642. if (this->AddTestsForDashboardType(targ)) {
  1643. processSteps = true;
  1644. return true;
  1645. }
  1646. if (this->AddVariableDefinition(targ)) {
  1647. return true;
  1648. }
  1649. this->ErrorMessageUnknownDashDValue(targ);
  1650. return false;
  1651. };
  1652. auto const dashT = [this, &processSteps,
  1653. ctestExec](std::string const& action) -> bool {
  1654. if (!this->SetTest(action, false)) {
  1655. cmCTestLog(this, ERROR_MESSAGE,
  1656. "CTest -T called with incorrect option: " << action << '\n');
  1657. /* clang-format off */
  1658. cmCTestLog(this, ERROR_MESSAGE,
  1659. "Available options are:\n"
  1660. " " << ctestExec << " -T all\n"
  1661. " " << ctestExec << " -T start\n"
  1662. " " << ctestExec << " -T update\n"
  1663. " " << ctestExec << " -T configure\n"
  1664. " " << ctestExec << " -T build\n"
  1665. " " << ctestExec << " -T test\n"
  1666. " " << ctestExec << " -T coverage\n"
  1667. " " << ctestExec << " -T memcheck\n"
  1668. " " << ctestExec << " -T notes\n"
  1669. " " << ctestExec << " -T submit\n");
  1670. /* clang-format on */
  1671. return false;
  1672. }
  1673. processSteps = true;
  1674. return true;
  1675. };
  1676. auto const dashM = [this, &processSteps,
  1677. ctestExec](std::string const& model) -> bool {
  1678. if (cmSystemTools::LowerCase(model) == "nightly"_s) {
  1679. this->SetTestModel(cmCTest::NIGHTLY);
  1680. } else if (cmSystemTools::LowerCase(model) == "continuous"_s) {
  1681. this->SetTestModel(cmCTest::CONTINUOUS);
  1682. } else if (cmSystemTools::LowerCase(model) == "experimental"_s) {
  1683. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1684. } else {
  1685. cmCTestLog(this, ERROR_MESSAGE,
  1686. "CTest -M called with incorrect option: " << model << '\n');
  1687. /* clang-format off */
  1688. cmCTestLog(this, ERROR_MESSAGE,
  1689. "Available options are:\n"
  1690. " " << ctestExec << " -M Continuous\n"
  1691. " " << ctestExec << " -M Experimental\n"
  1692. " " << ctestExec << " -M Nightly\n");
  1693. /* clang-format on */
  1694. return false;
  1695. }
  1696. processSteps = true;
  1697. return true;
  1698. };
  1699. auto const dashSP =
  1700. [&runScripts, &SRArgumentSpecified](std::string const& script) -> bool {
  1701. // -SR is an internal argument, -SP should be ignored when it is passed
  1702. if (!SRArgumentSpecified) {
  1703. runScripts.emplace_back(cmSystemTools::ToNormalizedPathOnDisk(script),
  1704. false);
  1705. }
  1706. return true;
  1707. };
  1708. auto const dashSR =
  1709. [&runScripts, &SRArgumentSpecified](std::string const& script) -> bool {
  1710. // -SR should be processed only once
  1711. if (!SRArgumentSpecified) {
  1712. SRArgumentSpecified = true;
  1713. runScripts.emplace_back(cmSystemTools::ToNormalizedPathOnDisk(script),
  1714. true);
  1715. }
  1716. return true;
  1717. };
  1718. auto const dash_S =
  1719. [&runScripts, &SRArgumentSpecified](std::string const& script) -> bool {
  1720. // -SR is an internal argument, -S should be ignored when it is passed
  1721. if (!SRArgumentSpecified) {
  1722. runScripts.emplace_back(cmSystemTools::ToNormalizedPathOnDisk(script),
  1723. true);
  1724. }
  1725. return true;
  1726. };
  1727. auto const dashJ = [this](cm::string_view arg,
  1728. std::string const& j) -> bool {
  1729. cm::optional<size_t> parallelLevel;
  1730. // No value or an empty value tells ctest to choose a default.
  1731. if (!j.empty()) {
  1732. // A non-empty value must be a non-negative integer.
  1733. unsigned long plevel = 0;
  1734. if (!cmStrToULong(j, &plevel)) {
  1735. cmSystemTools::Error(
  1736. cmStrCat('\'', arg, "' given invalid value '", j, '\''));
  1737. return false;
  1738. }
  1739. parallelLevel = plevel;
  1740. }
  1741. this->SetParallelLevel(parallelLevel);
  1742. this->Impl->ParallelLevelSetInCli = true;
  1743. return true;
  1744. };
  1745. auto const dashC = [this](std::string const& config) -> bool {
  1746. this->SetConfigType(config);
  1747. return true;
  1748. };
  1749. auto const dashGroup = [this](std::string const& group) -> bool {
  1750. this->Impl->SpecificGroup = group;
  1751. return true;
  1752. };
  1753. auto const dashQ = [this](std::string const&) -> bool {
  1754. this->Impl->Quiet = true;
  1755. return true;
  1756. };
  1757. auto const dashV = [this](std::string const&) -> bool {
  1758. this->Impl->Verbose = true;
  1759. return true;
  1760. };
  1761. auto const dashVV = [this](std::string const&) -> bool {
  1762. this->Impl->ExtraVerbose = true;
  1763. this->Impl->Verbose = true;
  1764. return true;
  1765. };
  1766. auto const dashO = [this](std::string const& log) -> bool {
  1767. this->SetOutputLogFileName(log);
  1768. return true;
  1769. };
  1770. auto const dashW = [this](std::string const& width) -> bool {
  1771. this->Impl->MaxTestNameWidth = atoi(width.c_str());
  1772. return true;
  1773. };
  1774. auto const dashA = [this, &processSteps](std::string const& notes) -> bool {
  1775. processSteps = true;
  1776. this->SetTest("Notes");
  1777. this->SetNotesFiles(notes);
  1778. return true;
  1779. };
  1780. auto const dashI = [this](std::string const& tests) -> bool {
  1781. this->Impl->TestOptions.TestsToRunInformation = tests;
  1782. return true;
  1783. };
  1784. auto const dashU = [this](std::string const&) -> bool {
  1785. this->Impl->TestOptions.UseUnion = true;
  1786. return true;
  1787. };
  1788. auto const dashR = [this](std::string const& expr) -> bool {
  1789. this->Impl->TestOptions.IncludeRegularExpression = expr;
  1790. return true;
  1791. };
  1792. auto const dashE = [this](std::string const& expr) -> bool {
  1793. this->Impl->TestOptions.ExcludeRegularExpression = expr;
  1794. return true;
  1795. };
  1796. auto const dashL = [this](std::string const& expr) -> bool {
  1797. this->Impl->TestOptions.LabelRegularExpression.push_back(expr);
  1798. return true;
  1799. };
  1800. auto const dashLE = [this](std::string const& expr) -> bool {
  1801. this->Impl->TestOptions.ExcludeLabelRegularExpression.push_back(expr);
  1802. return true;
  1803. };
  1804. auto const dashFA = [this](std::string const& expr) -> bool {
  1805. this->Impl->TestOptions.ExcludeFixtureRegularExpression = expr;
  1806. return true;
  1807. };
  1808. auto const dashFS = [this](std::string const& expr) -> bool {
  1809. this->Impl->TestOptions.ExcludeFixtureSetupRegularExpression = expr;
  1810. return true;
  1811. };
  1812. auto const dashFC = [this](std::string const& expr) -> bool {
  1813. this->Impl->TestOptions.ExcludeFixtureCleanupRegularExpression = expr;
  1814. return true;
  1815. };
  1816. using CommandArgument =
  1817. cmCommandLineArgument<bool(std::string const& value)>;
  1818. auto const arguments = std::vector<CommandArgument>{
  1819. CommandArgument{ "--dashboard", CommandArgument::Values::One, dashD },
  1820. CommandArgument{ "-D",
  1821. "-D must be followed by dashboard mode or VAR=VALUE.",
  1822. CommandArgument::Values::One, dashD },
  1823. CommandArgument{
  1824. "-D", "-D must be followed by dashboard mode or VAR=VALUE.",
  1825. CommandArgument::Values::One, CommandArgument::RequiresSeparator::No,
  1826. [this](std::string const& def) -> bool {
  1827. // Unsuccessful parsing of VAR=VALUE has historically
  1828. // been ignored.
  1829. this->AddVariableDefinition(def);
  1830. return true;
  1831. } },
  1832. CommandArgument{ "-T", CommandArgument::Values::One, dashT },
  1833. CommandArgument{ "--test-action", CommandArgument::Values::One, dashT },
  1834. CommandArgument{ "-M", CommandArgument::Values::One, dashM },
  1835. CommandArgument{ "--test-model", CommandArgument::Values::One, dashM },
  1836. CommandArgument{ "--extra-submit", CommandArgument::Values::One,
  1837. [this, &processSteps](std::string const& extra) -> bool {
  1838. processSteps = true;
  1839. this->SetTest("Submit");
  1840. return this->SubmitExtraFiles(extra);
  1841. } },
  1842. CommandArgument{
  1843. "--build-and-test", "--build-and-test must have source and binary dir",
  1844. CommandArgument::Values::Two,
  1845. [this, &cmakeAndTest](std::string const& dirs) -> bool {
  1846. cmakeAndTest = true;
  1847. cmList dirList{ dirs };
  1848. if (dirList.size() != 2) {
  1849. return false;
  1850. }
  1851. this->Impl->BuildAndTest.SourceDir =
  1852. cmSystemTools::ToNormalizedPathOnDisk(dirList[0]);
  1853. this->Impl->BuildAndTest.BinaryDir =
  1854. cmSystemTools::ToNormalizedPathOnDisk(dirList[1]);
  1855. cmSystemTools::MakeDirectory(this->Impl->BuildAndTest.BinaryDir);
  1856. return true;
  1857. } },
  1858. CommandArgument{ "--build-target", CommandArgument::Values::One,
  1859. [this](std::string const& t) -> bool {
  1860. this->Impl->BuildAndTest.BuildTargets.emplace_back(t);
  1861. return true;
  1862. } },
  1863. CommandArgument{ "--build-noclean", CommandArgument::Values::Zero,
  1864. [this](std::string const&) -> bool {
  1865. this->Impl->BuildAndTest.BuildNoClean = true;
  1866. return true;
  1867. } },
  1868. CommandArgument{ "--build-nocmake", CommandArgument::Values::Zero,
  1869. [this](std::string const&) -> bool {
  1870. this->Impl->BuildAndTest.BuildNoCMake = true;
  1871. return true;
  1872. } },
  1873. CommandArgument{ "--build-two-config", CommandArgument::Values::Zero,
  1874. [this](std::string const&) -> bool {
  1875. this->Impl->BuildAndTest.BuildTwoConfig = true;
  1876. return true;
  1877. } },
  1878. CommandArgument{ "--build-run-dir", CommandArgument::Values::One,
  1879. [this](std::string const& dir) -> bool {
  1880. this->Impl->BuildAndTest.BuildRunDir = dir;
  1881. return true;
  1882. } },
  1883. CommandArgument{ "--build-exe-dir", CommandArgument::Values::One,
  1884. [this](std::string const& dir) -> bool {
  1885. this->Impl->BuildAndTest.ExecutableDirectory = dir;
  1886. return true;
  1887. } },
  1888. CommandArgument{ "--test-timeout", CommandArgument::Values::One,
  1889. [this](std::string const& t) -> bool {
  1890. this->Impl->BuildAndTest.Timeout =
  1891. cmDuration(atof(t.c_str()));
  1892. return true;
  1893. } },
  1894. CommandArgument{ "--build-generator", CommandArgument::Values::One,
  1895. [this](std::string const& g) -> bool {
  1896. this->Impl->BuildAndTest.BuildGenerator = g;
  1897. return true;
  1898. } },
  1899. CommandArgument{ "--build-generator-platform",
  1900. CommandArgument::Values::One,
  1901. [this](std::string const& p) -> bool {
  1902. this->Impl->BuildAndTest.BuildGeneratorPlatform = p;
  1903. return true;
  1904. } },
  1905. CommandArgument{ "--build-generator-toolset", CommandArgument::Values::One,
  1906. [this](std::string const& t) -> bool {
  1907. this->Impl->BuildAndTest.BuildGeneratorToolset = t;
  1908. return true;
  1909. } },
  1910. CommandArgument{ "--build-project", CommandArgument::Values::One,
  1911. [this](std::string const& p) -> bool {
  1912. this->Impl->BuildAndTest.BuildProject = p;
  1913. return true;
  1914. } },
  1915. CommandArgument{ "--build-makeprogram", CommandArgument::Values::One,
  1916. [this](std::string const& p) -> bool {
  1917. this->Impl->BuildAndTest.BuildMakeProgram = p;
  1918. return true;
  1919. } },
  1920. CommandArgument{ "--build-config-sample", CommandArgument::Values::One,
  1921. [this](std::string const& s) -> bool {
  1922. this->Impl->BuildAndTest.ConfigSample = s;
  1923. return true;
  1924. } },
  1925. CommandArgument{ "-SP", CommandArgument::Values::One, dashSP },
  1926. CommandArgument{ "--script-new-process", CommandArgument::Values::One,
  1927. dashSP },
  1928. CommandArgument{ "-SR", CommandArgument::Values::One, dashSR },
  1929. CommandArgument{ "--script-run", CommandArgument::Values::One, dashSR },
  1930. CommandArgument{ "-S", CommandArgument::Values::One, dash_S },
  1931. CommandArgument{ "--script", CommandArgument::Values::One, dash_S },
  1932. CommandArgument{ "-F", CommandArgument::Values::Zero,
  1933. [this](std::string const&) -> bool {
  1934. this->Impl->Failover = true;
  1935. return true;
  1936. } },
  1937. CommandArgument{
  1938. "-j", CommandArgument::Values::ZeroOrOne,
  1939. [&dashJ](std::string const& j) -> bool { return dashJ("-j"_s, j); } },
  1940. CommandArgument{ "--parallel", CommandArgument::Values::ZeroOrOne,
  1941. [&dashJ](std::string const& j) -> bool {
  1942. return dashJ("--parallel"_s, j);
  1943. } },
  1944. CommandArgument{ "-j", CommandArgument::Values::One,
  1945. CommandArgument::RequiresSeparator::No,
  1946. [this](std::string const& j) -> bool {
  1947. // The value must be a non-negative integer.
  1948. unsigned long plevel = 0;
  1949. if (!cmStrToULong(j, &plevel)) {
  1950. cmSystemTools::Error(
  1951. cmStrCat("'-j' given invalid value '", j, '\''));
  1952. return false;
  1953. }
  1954. this->SetParallelLevel(plevel);
  1955. this->Impl->ParallelLevelSetInCli = true;
  1956. return true;
  1957. } },
  1958. CommandArgument{
  1959. "--repeat-until-fail", "'--repeat-until-fail' requires an argument",
  1960. CommandArgument::Values::One,
  1961. [this](std::string const& r) -> bool {
  1962. if (this->Impl->RepeatMode != cmCTest::Repeat::Never) {
  1963. cmSystemTools::Error("At most one '--repeat' option may be used.");
  1964. return false;
  1965. }
  1966. long repeat = 1;
  1967. if (!cmStrToLong(r, &repeat)) {
  1968. cmSystemTools::Error(cmStrCat(
  1969. "'--repeat-until-fail' given non-integer value '", r, '\''));
  1970. return false;
  1971. }
  1972. this->Impl->RepeatCount = static_cast<int>(repeat);
  1973. if (repeat > 1) {
  1974. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  1975. }
  1976. return true;
  1977. } },
  1978. CommandArgument{
  1979. "--repeat", CommandArgument::Values::One,
  1980. [this](std::string const& r) -> bool {
  1981. if (this->Impl->RepeatMode != cmCTest::Repeat::Never) {
  1982. cmSystemTools::Error("At most one '--repeat' option may be used.");
  1983. return false;
  1984. }
  1985. cmsys::RegularExpression repeatRegex(
  1986. "^(until-fail|until-pass|after-timeout):([0-9]+)$");
  1987. if (repeatRegex.find(r)) {
  1988. std::string const& count = repeatRegex.match(2);
  1989. unsigned long n = 1;
  1990. cmStrToULong(count, &n); // regex guarantees success
  1991. this->Impl->RepeatCount = static_cast<int>(n);
  1992. if (this->Impl->RepeatCount > 1) {
  1993. std::string const& mode = repeatRegex.match(1);
  1994. if (mode == "until-fail") {
  1995. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  1996. } else if (mode == "until-pass") {
  1997. this->Impl->RepeatMode = cmCTest::Repeat::UntilPass;
  1998. } else if (mode == "after-timeout") {
  1999. this->Impl->RepeatMode = cmCTest::Repeat::AfterTimeout;
  2000. }
  2001. }
  2002. } else {
  2003. cmSystemTools::Error(
  2004. cmStrCat("'--repeat' given invalid value '", r, '\''));
  2005. return false;
  2006. }
  2007. return true;
  2008. } },
  2009. CommandArgument{ "--test-load", CommandArgument::Values::One,
  2010. [this](std::string const& l) -> bool {
  2011. unsigned long load;
  2012. if (cmStrToULong(l, &load)) {
  2013. this->SetTestLoad(load);
  2014. } else {
  2015. cmCTestLog(
  2016. this, WARNING,
  2017. "Invalid value for 'Test Load' : " << l << '\n');
  2018. }
  2019. return true;
  2020. } },
  2021. CommandArgument{ "--no-compress-output", CommandArgument::Values::Zero,
  2022. [this](std::string const&) -> bool {
  2023. this->Impl->CompressTestOutput = false;
  2024. return true;
  2025. } },
  2026. CommandArgument{ "--print-labels", CommandArgument::Values::Zero,
  2027. [this](std::string const&) -> bool {
  2028. this->Impl->PrintLabels = true;
  2029. return true;
  2030. } },
  2031. CommandArgument{ "--http1.0", CommandArgument::Values::Zero,
  2032. [this](std::string const&) -> bool {
  2033. this->Impl->UseHTTP10 = true;
  2034. return true;
  2035. } },
  2036. CommandArgument{ "--timeout", CommandArgument::Values::One,
  2037. [this](std::string const& t) -> bool {
  2038. auto timeout = cmDuration(atof(t.c_str()));
  2039. this->Impl->GlobalTimeout = timeout;
  2040. return true;
  2041. } },
  2042. CommandArgument{ "--stop-time", CommandArgument::Values::One,
  2043. [this](std::string const& t) -> bool {
  2044. this->SetStopTime(t);
  2045. return true;
  2046. } },
  2047. CommandArgument{ "--stop-on-failure", CommandArgument::Values::Zero,
  2048. [this](std::string const&) -> bool {
  2049. this->Impl->StopOnFailure = true;
  2050. return true;
  2051. } },
  2052. CommandArgument{ "-C", CommandArgument::Values::One, dashC },
  2053. CommandArgument{ "--build-config", CommandArgument::Values::One, dashC },
  2054. CommandArgument{ "--debug", CommandArgument::Values::Zero,
  2055. [this](std::string const&) -> bool {
  2056. this->Impl->Debug = true;
  2057. return true;
  2058. } },
  2059. CommandArgument{ "--group", CommandArgument::Values::One, dashGroup },
  2060. // This is an undocumented / deprecated option.
  2061. // "Track" has been renamed to "Group".
  2062. CommandArgument{ "--track", CommandArgument::Values::One, dashGroup },
  2063. CommandArgument{ "--show-line-numbers", CommandArgument::Values::Zero,
  2064. [](std::string const&) -> bool {
  2065. // Silently ignore this never-documented and now-removed
  2066. // option.
  2067. return true;
  2068. } },
  2069. CommandArgument{ "--no-label-summary", CommandArgument::Values::Zero,
  2070. [this](std::string const&) -> bool {
  2071. this->Impl->LabelSummary = false;
  2072. return true;
  2073. } },
  2074. CommandArgument{ "--no-subproject-summary", CommandArgument::Values::Zero,
  2075. [this](std::string const&) -> bool {
  2076. this->Impl->SubprojectSummary = false;
  2077. return true;
  2078. } },
  2079. CommandArgument{ "--progress", CommandArgument::Values::Zero,
  2080. [this](std::string const&) -> bool {
  2081. this->Impl->TestProgressOutput = true;
  2082. return true;
  2083. } },
  2084. CommandArgument{ "-Q", CommandArgument::Values::Zero, dashQ },
  2085. CommandArgument{ "--quiet", CommandArgument::Values::Zero, dashQ },
  2086. CommandArgument{ "-V", CommandArgument::Values::Zero, dashV },
  2087. CommandArgument{ "--verbose", CommandArgument::Values::Zero, dashV },
  2088. CommandArgument{ "-VV", CommandArgument::Values::Zero, dashVV },
  2089. CommandArgument{ "--extra-verbose", CommandArgument::Values::Zero,
  2090. dashVV },
  2091. CommandArgument{ "--output-on-failure", CommandArgument::Values::Zero,
  2092. [this](std::string const&) -> bool {
  2093. this->Impl->OutputTestOutputOnTestFailure = true;
  2094. return true;
  2095. } },
  2096. CommandArgument{ "--test-output-size-passed", CommandArgument::Values::One,
  2097. [this](std::string const& sz) -> bool {
  2098. long outputSize;
  2099. if (cmStrToLong(sz, &outputSize)) {
  2100. this->Impl->TestOptions.OutputSizePassed =
  2101. static_cast<int>(outputSize);
  2102. } else {
  2103. cmCTestLog(
  2104. this, WARNING,
  2105. "Invalid value for '--test-output-size-passed': "
  2106. << sz << "\n");
  2107. }
  2108. return true;
  2109. } },
  2110. CommandArgument{ "--test-output-size-failed", CommandArgument::Values::One,
  2111. [this](std::string const& sz) -> bool {
  2112. long outputSize;
  2113. if (cmStrToLong(sz, &outputSize)) {
  2114. this->Impl->TestOptions.OutputSizeFailed =
  2115. static_cast<int>(outputSize);
  2116. } else {
  2117. cmCTestLog(
  2118. this, WARNING,
  2119. "Invalid value for '--test-output-size-failed': "
  2120. << sz << "\n");
  2121. }
  2122. return true;
  2123. } },
  2124. CommandArgument{
  2125. "--test-output-truncation", CommandArgument::Values::One,
  2126. [this](std::string const& mode) -> bool {
  2127. if (!SetTruncationMode(this->Impl->TestOptions.OutputTruncation,
  2128. mode)) {
  2129. cmSystemTools::Error(
  2130. cmStrCat("Invalid value for '--test-output-truncation': ", mode));
  2131. return false;
  2132. }
  2133. return true;
  2134. } },
  2135. CommandArgument{ "--show-only", CommandArgument::Values::ZeroOrOne,
  2136. [this](std::string const& format) -> bool {
  2137. this->Impl->ShowOnly = true;
  2138. // Check if a specific format is requested.
  2139. // Defaults to human readable text.
  2140. if (format == "json-v1") {
  2141. // Force quiet mode so the only output
  2142. // is the json object model.
  2143. this->Impl->Quiet = true;
  2144. this->Impl->OutputAsJson = true;
  2145. this->Impl->OutputAsJsonVersion = 1;
  2146. } else if (format == "human") {
  2147. } else if (!format.empty()) {
  2148. cmSystemTools::Error(
  2149. cmStrCat("'--show-only=' given unknown value '",
  2150. format, '\''));
  2151. return false;
  2152. }
  2153. return true;
  2154. } },
  2155. CommandArgument{ "-N", CommandArgument::Values::Zero,
  2156. [this](std::string const&) -> bool {
  2157. this->Impl->ShowOnly = true;
  2158. return true;
  2159. } },
  2160. CommandArgument{ "-O", CommandArgument::Values::One, dashO },
  2161. CommandArgument{ "--output-log", CommandArgument::Values::One, dashO },
  2162. CommandArgument{ "--tomorrow-tag", CommandArgument::Values::Zero,
  2163. [this](std::string const&) -> bool {
  2164. this->Impl->TomorrowTag = true;
  2165. return true;
  2166. } },
  2167. CommandArgument{ "--force-new-ctest-process",
  2168. CommandArgument::Values::Zero,
  2169. [](std::string const&) -> bool {
  2170. // Silently ignore now-removed option.
  2171. return true;
  2172. } },
  2173. CommandArgument{ "-W", CommandArgument::Values::One, dashW },
  2174. CommandArgument{ "--max-width", CommandArgument::Values::One, dashW },
  2175. CommandArgument{ "--interactive-debug-mode", CommandArgument::Values::One,
  2176. [this](std::string const& idm) -> bool {
  2177. this->Impl->InteractiveDebugMode = cmIsOn(idm);
  2178. return true;
  2179. } },
  2180. CommandArgument{ "--http-header", CommandArgument::Values::One,
  2181. [this](std::string const& h) -> bool {
  2182. this->Impl->CommandLineHttpHeaders.push_back(h);
  2183. return true;
  2184. } },
  2185. CommandArgument{ "--submit-index", CommandArgument::Values::One,
  2186. [this](std::string const& index) -> bool {
  2187. this->Impl->SubmitIndex = atoi(index.c_str());
  2188. if (this->Impl->SubmitIndex < 0) {
  2189. this->Impl->SubmitIndex = 0;
  2190. }
  2191. return true;
  2192. } },
  2193. CommandArgument{ "--overwrite", CommandArgument::Values::One,
  2194. [this](std::string const& opt) -> bool {
  2195. this->AddCTestConfigurationOverwrite(opt);
  2196. return true;
  2197. } },
  2198. CommandArgument{ "-A", CommandArgument::Values::One, dashA },
  2199. CommandArgument{ "--add-notes", CommandArgument::Values::One, dashA },
  2200. CommandArgument{ "--test-dir", "'--test-dir' requires an argument",
  2201. CommandArgument::Values::One,
  2202. [this](std::string const& dir) -> bool {
  2203. this->Impl->TestDir = dir;
  2204. return true;
  2205. } },
  2206. CommandArgument{ "--output-junit", CommandArgument::Values::One,
  2207. [this](std::string const& file) -> bool {
  2208. this->SetOutputJUnitFileName(file);
  2209. return true;
  2210. } },
  2211. CommandArgument{ "--no-tests", CommandArgument::Values::One,
  2212. [this](std::string const& action) -> bool {
  2213. if (action == "error"_s) {
  2214. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  2215. } else if (action == "ignore"_s) {
  2216. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  2217. } else {
  2218. cmSystemTools::Error(
  2219. cmStrCat("'--no-tests=' given unknown value '",
  2220. action, '\''));
  2221. return false;
  2222. }
  2223. this->Impl->NoTestsModeSetInCli = true;
  2224. return true;
  2225. } },
  2226. CommandArgument{ "-I", CommandArgument::Values::One, dashI },
  2227. CommandArgument{ "--tests-information", CommandArgument::Values::One,
  2228. dashI },
  2229. CommandArgument{ "-U", CommandArgument::Values::One, dashU },
  2230. CommandArgument{ "--union", CommandArgument::Values::One, dashU },
  2231. CommandArgument{ "-R", CommandArgument::Values::One, dashR },
  2232. CommandArgument{ "--tests-regex", CommandArgument::Values::One, dashR },
  2233. CommandArgument{ "-E", CommandArgument::Values::One, dashE },
  2234. CommandArgument{ "--exclude-regex", CommandArgument::Values::One, dashE },
  2235. CommandArgument{ "-L", CommandArgument::Values::One, dashL },
  2236. CommandArgument{ "--label-regex", CommandArgument::Values::One, dashL },
  2237. CommandArgument{ "-LE", CommandArgument::Values::One, dashLE },
  2238. CommandArgument{ "--label-exclude", CommandArgument::Values::One, dashLE },
  2239. CommandArgument{ "-FA", CommandArgument::Values::One, dashFA },
  2240. CommandArgument{ "--fixture-exclude-any", CommandArgument::Values::One,
  2241. dashFA },
  2242. CommandArgument{ "-FS", CommandArgument::Values::One, dashFS },
  2243. CommandArgument{ "--fixture-exclude-setup", CommandArgument::Values::One,
  2244. dashFS },
  2245. CommandArgument{ "-FC", CommandArgument::Values::One, dashFC },
  2246. CommandArgument{ "--fixture-exclude-cleanup", CommandArgument::Values::One,
  2247. dashFC },
  2248. CommandArgument{ "--resource-spec-file", CommandArgument::Values::One,
  2249. [this](std::string const& file) -> bool {
  2250. this->Impl->TestOptions.ResourceSpecFile = file;
  2251. return true;
  2252. } },
  2253. CommandArgument{ "--tests-from-file", CommandArgument::Values::One,
  2254. [this](std::string const& file) -> bool {
  2255. this->Impl->TestOptions.TestListFile = file;
  2256. return true;
  2257. } },
  2258. CommandArgument{ "--exclude-from-file", CommandArgument::Values::One,
  2259. [this](std::string const& file) -> bool {
  2260. this->Impl->TestOptions.ExcludeTestListFile = file;
  2261. return true;
  2262. } },
  2263. CommandArgument{ "--schedule-random", CommandArgument::Values::Zero,
  2264. [this](std::string const&) -> bool {
  2265. this->Impl->TestOptions.ScheduleRandom = true;
  2266. return true;
  2267. } },
  2268. CommandArgument{
  2269. "--schedule-random-seed", CommandArgument::Values::One,
  2270. [this](std::string const& sz) -> bool {
  2271. unsigned long seed_value;
  2272. if (cmStrToULong(sz, &seed_value)) {
  2273. this->Impl->TestOptions.ScheduleRandomSeed =
  2274. static_cast<unsigned int>(seed_value);
  2275. } else {
  2276. cmCTestLog(this, WARNING,
  2277. "Invalid value for '--schedule-random-seed': " << sz
  2278. << "\n");
  2279. }
  2280. return true;
  2281. } },
  2282. CommandArgument{ "--rerun-failed", CommandArgument::Values::Zero,
  2283. [this](std::string const&) -> bool {
  2284. this->Impl->TestOptions.RerunFailed = true;
  2285. return true;
  2286. } },
  2287. };
  2288. // process the command line arguments
  2289. for (size_t i = 1; i < args.size(); ++i) {
  2290. std::string const& arg = args[i];
  2291. bool matched = false;
  2292. for (auto const& m : arguments) {
  2293. if (m.matches(arg)) {
  2294. matched = true;
  2295. if (!m.parse(arg, i, args)) {
  2296. return 1;
  2297. }
  2298. break;
  2299. }
  2300. }
  2301. if (!matched && arg == "--build-options"_s) {
  2302. matched = true;
  2303. while (i + 1 < args.size() && args[i + 1] != "--build-target"_s &&
  2304. args[i + 1] != "--test-command"_s) {
  2305. ++i;
  2306. this->Impl->BuildAndTest.BuildOptions.emplace_back(args[i]);
  2307. }
  2308. }
  2309. if (!matched && arg == "--test-command"_s && i + 1 < args.size()) {
  2310. matched = true;
  2311. ++i;
  2312. this->Impl->BuildAndTest.TestCommand = args[i];
  2313. while (i + 1 < args.size()) {
  2314. ++i;
  2315. this->Impl->BuildAndTest.TestCommandArgs.emplace_back(args[i]);
  2316. }
  2317. }
  2318. if (!matched && cmHasLiteralPrefix(arg, "-") &&
  2319. !cmHasLiteralPrefix(arg, "--preset")) {
  2320. cmSystemTools::Error(cmStrCat("Unknown argument: ", arg));
  2321. cmSystemTools::Error("Run 'ctest --help' for all supported options.");
  2322. return 1;
  2323. }
  2324. }
  2325. // handle CTEST_PARALLEL_LEVEL environment variable
  2326. if (!this->Impl->ParallelLevelSetInCli) {
  2327. if (cm::optional<std::string> parallelEnv =
  2328. cmSystemTools::GetEnvVar("CTEST_PARALLEL_LEVEL")) {
  2329. if (parallelEnv->empty() ||
  2330. parallelEnv->find_first_not_of(" \t") == std::string::npos) {
  2331. // An empty value tells ctest to choose a default.
  2332. this->SetParallelLevel(cm::nullopt);
  2333. } else {
  2334. // A non-empty value must be a non-negative integer.
  2335. // Otherwise, ignore it.
  2336. unsigned long plevel = 0;
  2337. if (cmStrToULong(*parallelEnv, &plevel)) {
  2338. this->SetParallelLevel(plevel);
  2339. }
  2340. }
  2341. }
  2342. }
  2343. // handle CTEST_NO_TESTS_ACTION environment variable
  2344. if (!this->Impl->NoTestsModeSetInCli) {
  2345. std::string action;
  2346. if (cmSystemTools::GetEnv("CTEST_NO_TESTS_ACTION", action) &&
  2347. !action.empty()) {
  2348. if (action == "error"_s) {
  2349. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  2350. } else if (action == "ignore"_s) {
  2351. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  2352. } else {
  2353. cmCTestLog(this, ERROR_MESSAGE,
  2354. "Unknown value for CTEST_NO_TESTS_ACTION: '" << action
  2355. << '\'');
  2356. return 1;
  2357. }
  2358. }
  2359. }
  2360. // TestProgressOutput only supported if console supports it and not logging
  2361. // to a file
  2362. this->Impl->TestProgressOutput = this->Impl->TestProgressOutput &&
  2363. !this->Impl->OutputLogFile && this->ProgressOutputSupportedByConsole();
  2364. #ifdef _WIN32
  2365. if (this->Impl->TestProgressOutput) {
  2366. // Disable output line buffering so we can print content without
  2367. // a newline.
  2368. std::setvbuf(stdout, nullptr, _IONBF, 0);
  2369. }
  2370. #endif
  2371. // now what should cmake do? if --build-and-test was specified then
  2372. // we run the build and test handler and return
  2373. if (cmakeAndTest) {
  2374. return this->RunCMakeAndTest();
  2375. }
  2376. // -S, -SP, and/or -SP was specified
  2377. if (!runScripts.empty()) {
  2378. return this->RunScripts(runScripts);
  2379. }
  2380. // Establish the working directory.
  2381. std::string const currDir = cmSystemTools::GetLogicalWorkingDirectory();
  2382. std::string workDir = currDir;
  2383. if (!this->Impl->TestDir.empty()) {
  2384. workDir = cmSystemTools::ToNormalizedPathOnDisk(this->Impl->TestDir);
  2385. }
  2386. cmWorkingDirectory changeDir(workDir);
  2387. if (changeDir.Failed()) {
  2388. cmCTestLog(this, ERROR_MESSAGE, changeDir.GetError() << std::endl);
  2389. return 1;
  2390. }
  2391. this->Impl->BinaryDir = workDir;
  2392. // -D, -T, and/or -M was specified
  2393. if (processSteps) {
  2394. return this->ProcessSteps();
  2395. }
  2396. return this->ExecuteTests(args);
  2397. }
  2398. int cmCTest::RunScripts(
  2399. std::vector<std::pair<std::string, bool>> const& scripts)
  2400. {
  2401. if (this->Impl->ExtraVerbose) {
  2402. cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
  2403. }
  2404. auto ch = cm::make_unique<cmCTestScriptHandler>(this);
  2405. for (auto const& script : scripts) {
  2406. ch->AddConfigurationScript(script.first, script.second);
  2407. }
  2408. int res = ch->ProcessHandler();
  2409. if (res != 0) {
  2410. cmCTestLog(this, DEBUG,
  2411. "running script failing returning: " << res << std::endl);
  2412. }
  2413. return res;
  2414. }
  2415. int cmCTest::ExecuteTests(std::vector<std::string> const& args)
  2416. {
  2417. this->Impl->ExtraVerbose = this->Impl->Verbose;
  2418. this->Impl->Verbose = true;
  2419. cmCTestLog(this, DEBUG, "Here: " << __LINE__ << std::endl);
  2420. if (!this->Impl->InteractiveDebugMode) {
  2421. this->BlockTestErrorDiagnostics();
  2422. } else {
  2423. cmSystemTools::PutEnv("CTEST_INTERACTIVE_DEBUG_MODE=1");
  2424. }
  2425. this->UpdateCTestConfiguration();
  2426. cmCTestLog(this, DEBUG, "Here: " << __LINE__ << std::endl);
  2427. cmCTestTestHandler handler(this);
  2428. {
  2429. cmake cm(cmake::RoleScript, cmState::CTest);
  2430. cm.SetHomeDirectory("");
  2431. cm.SetHomeOutputDirectory("");
  2432. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  2433. cmGlobalGenerator gg(&cm);
  2434. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  2435. this->ReadCustomConfigurationFileTree(this->Impl->BinaryDir, &mf);
  2436. handler.PopulateCustomVectors(&mf);
  2437. }
  2438. handler.SetVerbose(this->Impl->Verbose);
  2439. cmInstrumentation instrumentation(this->GetBinaryDir());
  2440. auto processHandler = [&handler]() -> int {
  2441. return handler.ProcessHandler();
  2442. };
  2443. int ret = instrumentation.InstrumentCommand("ctest", args, processHandler);
  2444. instrumentation.CollectTimingData(cmInstrumentationQuery::Hook::PostTest);
  2445. if (ret < 0) {
  2446. cmCTestLog(this, ERROR_MESSAGE, "Errors while running CTest\n");
  2447. if (!this->Impl->OutputTestOutputOnTestFailure) {
  2448. std::string const lastTestLog =
  2449. this->GetBinaryDir() + "/Testing/Temporary/LastTest.log";
  2450. cmCTestLog(this, ERROR_MESSAGE,
  2451. "Output from these tests are in: " << lastTestLog << '\n');
  2452. cmCTestLog(this, ERROR_MESSAGE,
  2453. "Use \"--rerun-failed --output-on-failure\" to re-run the "
  2454. "failed cases verbosely.\n");
  2455. }
  2456. return cmCTest::TEST_ERRORS;
  2457. }
  2458. return 0;
  2459. }
  2460. int cmCTest::RunCMakeAndTest()
  2461. {
  2462. return this->Impl->BuildAndTest.Run();
  2463. }
  2464. void cmCTest::SetNotesFiles(std::string const& notes)
  2465. {
  2466. this->Impl->NotesFiles = notes;
  2467. }
  2468. bool cmCTest::GetStopOnFailure() const
  2469. {
  2470. return this->Impl->StopOnFailure;
  2471. }
  2472. void cmCTest::SetStopOnFailure(bool stop)
  2473. {
  2474. this->Impl->StopOnFailure = stop;
  2475. }
  2476. std::chrono::system_clock::time_point cmCTest::GetStopTime() const
  2477. {
  2478. return this->Impl->StopTime;
  2479. }
  2480. void cmCTest::SetStopTime(std::string const& time_str)
  2481. {
  2482. struct tm* lctime;
  2483. time_t current_time = time(nullptr);
  2484. lctime = gmtime(&current_time);
  2485. int gm_hour = lctime->tm_hour;
  2486. time_t gm_time = mktime(lctime);
  2487. lctime = localtime(&current_time);
  2488. int local_hour = lctime->tm_hour;
  2489. int tzone_offset = local_hour - gm_hour;
  2490. if (gm_time > current_time && gm_hour < local_hour) {
  2491. // this means gm_time is on the next day
  2492. tzone_offset -= 24;
  2493. } else if (gm_time < current_time && gm_hour > local_hour) {
  2494. // this means gm_time is on the previous day
  2495. tzone_offset += 24;
  2496. }
  2497. tzone_offset *= 100;
  2498. char buf[1024];
  2499. snprintf(buf, sizeof(buf), "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  2500. lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(),
  2501. tzone_offset);
  2502. time_t stop_time = cm_get_date(current_time, buf);
  2503. if (stop_time == -1) {
  2504. this->Impl->StopTime = std::chrono::system_clock::time_point();
  2505. return;
  2506. }
  2507. this->Impl->StopTime = std::chrono::system_clock::from_time_t(stop_time);
  2508. if (stop_time < current_time) {
  2509. this->Impl->StopTime += std::chrono::hours(24);
  2510. }
  2511. }
  2512. cm::optional<unsigned int> cmCTest::GetRandomSeed() const
  2513. {
  2514. return this->Impl->TestOptions.ScheduleRandomSeed;
  2515. }
  2516. std::string cmCTest::GetScheduleType() const
  2517. {
  2518. return this->Impl->ScheduleType;
  2519. }
  2520. void cmCTest::SetScheduleType(std::string const& type)
  2521. {
  2522. this->Impl->ScheduleType = type;
  2523. }
  2524. void cmCTest::ReadCustomConfigurationFileTree(std::string const& dir,
  2525. cmMakefile* mf)
  2526. {
  2527. cmCTestLog(this, DEBUG,
  2528. "* Read custom CTest configuration directory: " << dir
  2529. << std::endl);
  2530. auto const fname = [this, &dir]() -> std::string {
  2531. for (char const* ext : { ".cmake", ".ctest" }) {
  2532. std::string path = cmStrCat(dir, "/CTestCustom", ext);
  2533. cmCTestLog(this, DEBUG, "* Check for file: " << path << std::endl);
  2534. if (cmSystemTools::FileExists(path)) {
  2535. return path;
  2536. }
  2537. }
  2538. return "";
  2539. }();
  2540. if (!fname.empty()) {
  2541. cmCTestLog(this, DEBUG,
  2542. "* Read custom CTest configuration file: " << fname
  2543. << std::endl);
  2544. bool erroroc = cmSystemTools::GetErrorOccurredFlag();
  2545. cmSystemTools::ResetErrorOccurredFlag();
  2546. if (!mf->ReadListFile(fname) || cmSystemTools::GetErrorOccurredFlag()) {
  2547. cmCTestLog(this, ERROR_MESSAGE,
  2548. "Problem reading custom configuration: " << fname
  2549. << std::endl);
  2550. }
  2551. if (erroroc) {
  2552. cmSystemTools::SetErrorOccurred();
  2553. }
  2554. }
  2555. }
  2556. void cmCTest::PopulateCustomVector(cmMakefile* mf, std::string const& def,
  2557. std::vector<std::string>& vec)
  2558. {
  2559. cmValue dval = mf->GetDefinition(def);
  2560. if (!dval) {
  2561. return;
  2562. }
  2563. cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl);
  2564. cmList::assign(vec, *dval);
  2565. for (std::string const& it : vec) {
  2566. cmCTestLog(this, DEBUG, " -- " << it << std::endl);
  2567. }
  2568. }
  2569. void cmCTest::PopulateCustomInteger(cmMakefile* mf, std::string const& def,
  2570. int& val)
  2571. {
  2572. cmValue dval = mf->GetDefinition(def);
  2573. if (!dval) {
  2574. return;
  2575. }
  2576. val = atoi(dval->c_str());
  2577. }
  2578. std::string cmCTest::GetShortPathToFile(std::string const& cfname)
  2579. {
  2580. std::string const& sourceDir =
  2581. this->GetCTestConfiguration("SourceDirectory");
  2582. std::string const& buildDir = this->GetCTestConfiguration("BuildDirectory");
  2583. std::string fname = cmSystemTools::CollapseFullPath(cfname);
  2584. // Find relative paths to both directories
  2585. std::string srcRelpath = cmSystemTools::RelativePath(sourceDir, fname);
  2586. std::string bldRelpath = cmSystemTools::RelativePath(buildDir, fname);
  2587. // If any contains "." it is not parent directory
  2588. bool inSrc = srcRelpath.find("..") == std::string::npos;
  2589. bool inBld = bldRelpath.find("..") == std::string::npos;
  2590. // TODO: Handle files with .. in their name
  2591. std::string* res = nullptr;
  2592. if (inSrc && inBld) {
  2593. // If both have relative path with no dots, pick the shorter one
  2594. if (srcRelpath.size() < bldRelpath.size()) {
  2595. res = &srcRelpath;
  2596. } else {
  2597. res = &bldRelpath;
  2598. }
  2599. } else if (inSrc) {
  2600. res = &srcRelpath;
  2601. } else if (inBld) {
  2602. res = &bldRelpath;
  2603. }
  2604. std::string path;
  2605. if (!res) {
  2606. path = fname;
  2607. } else {
  2608. cmSystemTools::ConvertToUnixSlashes(*res);
  2609. path = "./" + *res;
  2610. if (path.back() == '/') {
  2611. path.resize(path.size() - 1);
  2612. }
  2613. }
  2614. cmsys::SystemTools::ReplaceString(path, ":", "_");
  2615. cmsys::SystemTools::ReplaceString(path, " ", "_");
  2616. return path;
  2617. }
  2618. std::string cmCTest::GetCTestConfiguration(std::string const& name)
  2619. {
  2620. if (this->Impl->CTestConfigurationOverwrites.find(name) !=
  2621. this->Impl->CTestConfigurationOverwrites.end()) {
  2622. return this->Impl->CTestConfigurationOverwrites[name];
  2623. }
  2624. return this->Impl->CTestConfiguration[name];
  2625. }
  2626. void cmCTest::EmptyCTestConfiguration()
  2627. {
  2628. this->Impl->CTestConfiguration.clear();
  2629. }
  2630. void cmCTest::SetCTestConfiguration(char const* name, std::string const& value,
  2631. bool suppress)
  2632. {
  2633. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2634. "SetCTestConfiguration:" << name << ":" << value << "\n",
  2635. suppress);
  2636. if (!name) {
  2637. return;
  2638. }
  2639. if (value.empty()) {
  2640. this->Impl->CTestConfiguration.erase(name);
  2641. return;
  2642. }
  2643. this->Impl->CTestConfiguration[name] = value;
  2644. }
  2645. std::string cmCTest::GetSubmitURL()
  2646. {
  2647. std::string url = this->GetCTestConfiguration("SubmitURL");
  2648. if (url.empty()) {
  2649. std::string method = this->GetCTestConfiguration("DropMethod");
  2650. std::string user = this->GetCTestConfiguration("DropSiteUser");
  2651. std::string password = this->GetCTestConfiguration("DropSitePassword");
  2652. std::string site = this->GetCTestConfiguration("DropSite");
  2653. std::string location = this->GetCTestConfiguration("DropLocation");
  2654. url = cmStrCat(method.empty() ? "http" : method, "://"_s);
  2655. if (!user.empty()) {
  2656. url += user;
  2657. if (!password.empty()) {
  2658. url += ':';
  2659. url += password;
  2660. }
  2661. url += '@';
  2662. }
  2663. url += site;
  2664. url += location;
  2665. }
  2666. return url;
  2667. }
  2668. std::string cmCTest::GetCurrentTag()
  2669. {
  2670. return this->Impl->CurrentTag;
  2671. }
  2672. std::string cmCTest::GetBinaryDir()
  2673. {
  2674. return this->Impl->BinaryDir;
  2675. }
  2676. std::string const& cmCTest::GetConfigType()
  2677. {
  2678. return this->Impl->ConfigType;
  2679. }
  2680. cmDuration cmCTest::GetTimeOut() const
  2681. {
  2682. return this->Impl->TimeOut;
  2683. }
  2684. void cmCTest::SetTimeOut(cmDuration t)
  2685. {
  2686. this->Impl->TimeOut = t;
  2687. }
  2688. cmDuration cmCTest::GetGlobalTimeout() const
  2689. {
  2690. return this->Impl->GlobalTimeout;
  2691. }
  2692. bool cmCTest::GetShowOnly()
  2693. {
  2694. return this->Impl->ShowOnly;
  2695. }
  2696. bool cmCTest::GetOutputAsJson()
  2697. {
  2698. return this->Impl->OutputAsJson;
  2699. }
  2700. int cmCTest::GetOutputAsJsonVersion()
  2701. {
  2702. return this->Impl->OutputAsJsonVersion;
  2703. }
  2704. bool cmCTest::ShouldUseHTTP10() const
  2705. {
  2706. return this->Impl->UseHTTP10;
  2707. }
  2708. bool cmCTest::ShouldPrintLabels() const
  2709. {
  2710. return this->Impl->PrintLabels;
  2711. }
  2712. int cmCTest::GetMaxTestNameWidth() const
  2713. {
  2714. return this->Impl->MaxTestNameWidth;
  2715. }
  2716. void cmCTest::SetMaxTestNameWidth(int w)
  2717. {
  2718. this->Impl->MaxTestNameWidth = w;
  2719. }
  2720. void cmCTest::SetProduceXML(bool v)
  2721. {
  2722. this->Impl->ProduceXML = v;
  2723. }
  2724. bool cmCTest::GetProduceXML()
  2725. {
  2726. return this->Impl->ProduceXML;
  2727. }
  2728. std::vector<std::string>& cmCTest::GetInitialCommandLineArguments()
  2729. {
  2730. return this->Impl->InitialCommandLineArguments;
  2731. }
  2732. char const* cmCTest::GetSpecificGroup()
  2733. {
  2734. if (this->Impl->SpecificGroup.empty()) {
  2735. return nullptr;
  2736. }
  2737. return this->Impl->SpecificGroup.c_str();
  2738. }
  2739. void cmCTest::SetSpecificGroup(char const* group)
  2740. {
  2741. if (!group) {
  2742. this->Impl->SpecificGroup.clear();
  2743. return;
  2744. }
  2745. this->Impl->SpecificGroup = group;
  2746. }
  2747. void cmCTest::SetFailover(bool failover)
  2748. {
  2749. this->Impl->Failover = failover;
  2750. }
  2751. bool cmCTest::GetFailover() const
  2752. {
  2753. return this->Impl->Failover;
  2754. }
  2755. bool cmCTest::GetTestProgressOutput() const
  2756. {
  2757. return this->Impl->TestProgressOutput && !GetExtraVerbose();
  2758. }
  2759. bool cmCTest::GetVerbose() const
  2760. {
  2761. return this->Impl->Verbose;
  2762. }
  2763. bool cmCTest::GetExtraVerbose() const
  2764. {
  2765. return this->Impl->ExtraVerbose;
  2766. }
  2767. bool cmCTest::GetInteractiveDebugMode() const
  2768. {
  2769. return this->Impl->InteractiveDebugMode;
  2770. }
  2771. bool cmCTest::GetLabelSummary() const
  2772. {
  2773. return this->Impl->LabelSummary;
  2774. }
  2775. bool cmCTest::GetSubprojectSummary() const
  2776. {
  2777. return this->Impl->SubprojectSummary;
  2778. }
  2779. bool cmCTest::GetOutputTestOutputOnTestFailure() const
  2780. {
  2781. return this->Impl->OutputTestOutputOnTestFailure;
  2782. }
  2783. std::map<std::string, std::string> const& cmCTest::GetDefinitions() const
  2784. {
  2785. return this->Impl->Definitions;
  2786. }
  2787. int cmCTest::GetRepeatCount() const
  2788. {
  2789. return this->Impl->RepeatCount;
  2790. }
  2791. cmCTest::Repeat cmCTest::GetRepeatMode() const
  2792. {
  2793. return this->Impl->RepeatMode;
  2794. }
  2795. cmCTest::NoTests cmCTest::GetNoTestsMode() const
  2796. {
  2797. return this->Impl->NoTestsMode;
  2798. }
  2799. void cmCTest::SetBuildID(std::string const& id)
  2800. {
  2801. this->Impl->BuildID = id;
  2802. }
  2803. std::string cmCTest::GetBuildID() const
  2804. {
  2805. return this->Impl->BuildID;
  2806. }
  2807. cmCTestTestOptions const& cmCTest::GetTestOptions() const
  2808. {
  2809. return this->Impl->TestOptions;
  2810. }
  2811. std::vector<std::string> cmCTest::GetCommandLineHttpHeaders() const
  2812. {
  2813. return this->Impl->CommandLineHttpHeaders;
  2814. }
  2815. void cmCTest::AddSubmitFile(Part part, std::string const& name)
  2816. {
  2817. this->Impl->Parts[part].SubmitFiles.emplace_back(name);
  2818. }
  2819. std::vector<std::string> const& cmCTest::GetSubmitFiles(Part part) const
  2820. {
  2821. return this->Impl->Parts[part].SubmitFiles;
  2822. }
  2823. void cmCTest::ClearSubmitFiles(Part part)
  2824. {
  2825. this->Impl->Parts[part].SubmitFiles.clear();
  2826. }
  2827. void cmCTest::AddCTestConfigurationOverwrite(std::string const& overStr)
  2828. {
  2829. size_t epos = overStr.find('=');
  2830. if (epos == std::string::npos) {
  2831. cmCTestLog(this, ERROR_MESSAGE,
  2832. "CTest configuration overwrite specified in the wrong format.\n"
  2833. "Valid format is: --overwrite key=value\n"
  2834. "The specified was: --overwrite "
  2835. << overStr << '\n');
  2836. return;
  2837. }
  2838. std::string key = overStr.substr(0, epos);
  2839. std::string value = overStr.substr(epos + 1);
  2840. this->Impl->CTestConfigurationOverwrites[key] = value;
  2841. }
  2842. void cmCTest::SetConfigType(std::string const& ct)
  2843. {
  2844. this->Impl->ConfigType = ct;
  2845. cmSystemTools::ReplaceString(this->Impl->ConfigType, ".\\", "");
  2846. std::string confTypeEnv = "CMAKE_CONFIG_TYPE=" + this->Impl->ConfigType;
  2847. cmSystemTools::PutEnv(confTypeEnv);
  2848. }
  2849. bool cmCTest::SetCTestConfigurationFromCMakeVariable(
  2850. cmMakefile* mf, char const* dconfig, std::string const& cmake_var,
  2851. bool suppress)
  2852. {
  2853. cmValue ctvar = mf->GetDefinition(cmake_var);
  2854. if (!ctvar) {
  2855. return false;
  2856. }
  2857. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2858. "SetCTestConfigurationFromCMakeVariable:"
  2859. << dconfig << ":" << cmake_var << std::endl,
  2860. suppress);
  2861. this->SetCTestConfiguration(dconfig, *ctvar, suppress);
  2862. return true;
  2863. }
  2864. void cmCTest::SetCMakeVariables(cmMakefile& mf)
  2865. {
  2866. auto set = [&](char const* cmake_var, char const* ctest_opt) {
  2867. std::string val = this->GetCTestConfiguration(ctest_opt);
  2868. if (!val.empty()) {
  2869. cmCTestOptionalLog(
  2870. this, HANDLER_VERBOSE_OUTPUT,
  2871. "SetCMakeVariable:" << cmake_var << ":" << val << std::endl, false);
  2872. mf.AddDefinition(cmake_var, val);
  2873. }
  2874. };
  2875. set("CTEST_SITE", "Site");
  2876. set("CTEST_BUILD_NAME", "BuildName");
  2877. set("CTEST_NIGHTLY_START_TIME", "NightlyStartTime");
  2878. set("CTEST_SOURCE_DIRECTORY", "SourceDirectory");
  2879. set("CTEST_BINARY_DIRECTORY", "BuildDirectory");
  2880. // CTest Update Step
  2881. set("CTEST_UPDATE_COMMAND", "UpdateCommand");
  2882. set("CTEST_UPDATE_OPTIONS", "UpdateOptions");
  2883. set("CTEST_UPDATE_TYPE", "UpdateType");
  2884. set("CTEST_CVS_COMMAND", "CVSCommand");
  2885. set("CTEST_CVS_UPDATE_OPTIONS", "CVSUpdateOptions");
  2886. set("CTEST_SVN_COMMAND", "SVNCommand");
  2887. set("CTEST_SVN_UPDATE_OPTIONS", "SVNUpdateOptions");
  2888. set("CTEST_SVN_OPTIONS", "SVNOptions");
  2889. set("CTEST_BZR_COMMAND", "BZRCommand");
  2890. set("CTEST_BZR_UPDATE_OPTIONS", "BZRUpdateOptions");
  2891. set("CTEST_GIT_COMMAND", "GITCommand");
  2892. set("CTEST_GIT_UPDATE_OPTIONS", "GITUpdateOptions");
  2893. set("CTEST_GIT_INIT_SUBMODULES", "GITInitSubmodules");
  2894. set("CTEST_GIT_UPDATE_CUSTOM", "GITUpdateCustom");
  2895. set("CTEST_UPDATE_VERSION_ONLY", "UpdateVersionOnly");
  2896. set("CTEST_UPDATE_VERSION_OVERRIDE", "UpdateVersionOverride");
  2897. set("CTEST_HG_COMMAND", "HGCommand");
  2898. set("CTEST_HG_UPDATE_OPTIONS", "HGUpdateOptions");
  2899. set("CTEST_P4_COMMAND", "P4Command");
  2900. set("CTEST_P4_UPDATE_CUSTOM", "P4UpdateCustom");
  2901. set("CTEST_P4_UPDATE_OPTIONS", "P4UpdateOptions");
  2902. set("CTEST_P4_CLIENT", "P4Client");
  2903. set("CTEST_P4_OPTIONS", "P4Options");
  2904. // CTest Configure Step
  2905. set("CTEST_CONFIGURE_COMMAND", "ConfigureCommand");
  2906. set("CTEST_LABELS_FOR_SUBPROJECTS", "LabelsForSubprojects");
  2907. // CTest Build Step
  2908. set("CTEST_BUILD_COMMAND", "MakeCommand");
  2909. set("CTEST_USE_LAUNCHERS", "UseLaunchers");
  2910. // CTest Coverage Step
  2911. set("CTEST_COVERAGE_COMMAND", "CoverageCommand");
  2912. set("CTEST_COVERAGE_EXTRA_FLAGS", "CoverageExtraFlags");
  2913. // CTest MemCheck Step
  2914. set("CTEST_MEMORYCHECK_TYPE", "MemoryCheckType");
  2915. set("CTEST_MEMORYCHECK_SANITIZER_OPTIONS", "MemoryCheckSanitizerOptions");
  2916. set("CTEST_MEMORYCHECK_COMMAND", "MemoryCheckCommand");
  2917. set("CTEST_MEMORYCHECK_COMMAND_OPTIONS", "MemoryCheckCommandOptions");
  2918. set("CTEST_MEMORYCHECK_SUPPRESSIONS_FILE", "MemoryCheckSuppressionFile");
  2919. // CTest Submit Step
  2920. set("CTEST_SUBMIT_URL", "SubmitURL");
  2921. set("CTEST_DROP_METHOD", "DropMethod");
  2922. set("CTEST_DROP_SITE_USER", "DropSiteUser");
  2923. set("CTEST_DROP_SITE_PASSWORD", "DropSitePassword");
  2924. set("CTEST_DROP_SITE", "DropSite");
  2925. set("CTEST_DROP_LOCATION", "DropLocation");
  2926. set("CTEST_TLS_VERIFY", "TLSVerify");
  2927. set("CTEST_TLS_VERSION", "TLSVersion");
  2928. set("CTEST_CURL_OPTIONS", "CurlOptions");
  2929. set("CTEST_SUBMIT_INACTIVITY_TIMEOUT", "SubmitInactivityTimeout");
  2930. }
  2931. bool cmCTest::RunCommand(std::vector<std::string> const& args,
  2932. std::string* stdOut, std::string* stdErr, int* retVal,
  2933. char const* dir, cmDuration timeout,
  2934. Encoding encoding)
  2935. {
  2936. std::vector<char const*> argv;
  2937. argv.reserve(args.size() + 1);
  2938. for (std::string const& a : args) {
  2939. argv.push_back(a.c_str());
  2940. }
  2941. argv.push_back(nullptr);
  2942. stdOut->clear();
  2943. stdErr->clear();
  2944. cmUVProcessChainBuilder builder;
  2945. builder.AddCommand(args)
  2946. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  2947. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  2948. if (dir) {
  2949. builder.SetWorkingDirectory(dir);
  2950. }
  2951. auto chain = builder.Start();
  2952. cm::uv_timer_ptr timer;
  2953. bool timedOut = false;
  2954. if (timeout.count()) {
  2955. timer.init(chain.GetLoop(), &timedOut);
  2956. timer.start(
  2957. [](uv_timer_t* t) {
  2958. auto* timedOutPtr = static_cast<bool*>(t->data);
  2959. *timedOutPtr = true;
  2960. },
  2961. static_cast<uint64_t>(timeout.count() * 1000.0), 0);
  2962. }
  2963. std::vector<char> tempOutput;
  2964. bool outFinished = false;
  2965. cm::uv_pipe_ptr outStream;
  2966. std::vector<char> tempError;
  2967. bool errFinished = false;
  2968. cm::uv_pipe_ptr errStream;
  2969. cmProcessOutput processOutput(encoding);
  2970. auto startRead = [this, &chain, &processOutput](
  2971. cm::uv_pipe_ptr& pipe, int stream,
  2972. std::vector<char>& temp,
  2973. bool& finished) -> std::unique_ptr<cmUVStreamReadHandle> {
  2974. pipe.init(chain.GetLoop(), 0);
  2975. uv_pipe_open(pipe, stream);
  2976. return cmUVStreamRead(
  2977. pipe,
  2978. [this, &temp, &processOutput](std::vector<char> data) {
  2979. cm::append(temp, data);
  2980. if (this->Impl->ExtraVerbose) {
  2981. std::string strdata;
  2982. processOutput.DecodeText(data.data(), data.size(), strdata);
  2983. cmSystemTools::Stdout(strdata);
  2984. }
  2985. },
  2986. [&finished]() { finished = true; });
  2987. };
  2988. auto outputHandle =
  2989. startRead(outStream, chain.OutputStream(), tempOutput, outFinished);
  2990. auto errorHandle =
  2991. startRead(errStream, chain.ErrorStream(), tempError, errFinished);
  2992. while (!timedOut && !(outFinished && errFinished)) {
  2993. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  2994. }
  2995. if (this->Impl->ExtraVerbose) {
  2996. std::string strdata;
  2997. processOutput.DecodeText(std::string(), strdata);
  2998. if (!strdata.empty()) {
  2999. cmSystemTools::Stdout(strdata);
  3000. }
  3001. }
  3002. while (!timedOut && !chain.Finished()) {
  3003. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  3004. }
  3005. if (!tempOutput.empty()) {
  3006. processOutput.DecodeText(tempOutput, tempOutput);
  3007. stdOut->append(tempOutput.data(), tempOutput.size());
  3008. }
  3009. if (!tempError.empty()) {
  3010. processOutput.DecodeText(tempError, tempError);
  3011. stdErr->append(tempError.data(), tempError.size());
  3012. }
  3013. bool result = true;
  3014. if (timedOut) {
  3015. char const* error_str = "Process terminated due to timeout\n";
  3016. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  3017. stdErr->append(error_str, strlen(error_str));
  3018. result = false;
  3019. } else {
  3020. auto const& status = chain.GetStatus(0);
  3021. auto exception = status.GetException();
  3022. switch (exception.first) {
  3023. case cmUVProcessChain::ExceptionCode::None:
  3024. if (retVal) {
  3025. *retVal = static_cast<int>(status.ExitStatus);
  3026. } else {
  3027. if (status.ExitStatus != 0) {
  3028. result = false;
  3029. }
  3030. }
  3031. break;
  3032. default: {
  3033. cmCTestLog(this, ERROR_MESSAGE, exception.second << std::endl);
  3034. stdErr->append(exception.second);
  3035. result = false;
  3036. } break;
  3037. }
  3038. }
  3039. return result;
  3040. }
  3041. void cmCTest::SetOutputLogFileName(std::string const& name)
  3042. {
  3043. if (!name.empty()) {
  3044. this->Impl->OutputLogFile = cm::make_unique<cmGeneratedFileStream>(name);
  3045. } else {
  3046. this->Impl->OutputLogFile.reset();
  3047. }
  3048. }
  3049. void cmCTest::SetOutputJUnitFileName(std::string const& name)
  3050. {
  3051. this->Impl->TestOptions.JUnitXMLFileName = name;
  3052. // Turn test output compression off.
  3053. // This makes it easier to include test output in the resulting
  3054. // JUnit XML report.
  3055. this->Impl->CompressTestOutput = false;
  3056. }
  3057. static char const* cmCTestStringLogType[] = { "DEBUG",
  3058. "OUTPUT",
  3059. "HANDLER_OUTPUT",
  3060. "HANDLER_PROGRESS_OUTPUT",
  3061. "HANDLER_TEST_PROGRESS_OUTPUT",
  3062. "HANDLER_VERBOSE_OUTPUT",
  3063. "WARNING",
  3064. "ERROR_MESSAGE" };
  3065. void cmCTest::Log(LogType logType, std::string msg, bool suppress)
  3066. {
  3067. if (msg.empty()) {
  3068. return;
  3069. }
  3070. if (suppress && logType != cmCTest::ERROR_MESSAGE) {
  3071. return;
  3072. }
  3073. if (logType == cmCTest::HANDLER_PROGRESS_OUTPUT &&
  3074. (this->Impl->Debug || this->Impl->ExtraVerbose)) {
  3075. return;
  3076. }
  3077. if (this->Impl->OutputLogFile) {
  3078. bool display = true;
  3079. if (logType == cmCTest::DEBUG && !this->Impl->Debug) {
  3080. display = false;
  3081. }
  3082. if (logType == cmCTest::HANDLER_VERBOSE_OUTPUT && !this->Impl->Debug &&
  3083. !this->Impl->ExtraVerbose) {
  3084. display = false;
  3085. }
  3086. if (display) {
  3087. if (this->Impl->OutputLogFileLastTag &&
  3088. logType != *this->Impl->OutputLogFileLastTag) {
  3089. *this->Impl->OutputLogFile << "[" << cmCTestStringLogType[logType]
  3090. << "] " << std::endl;
  3091. }
  3092. *this->Impl->OutputLogFile << msg << std::flush;
  3093. if (this->Impl->OutputLogFileLastTag &&
  3094. logType != *this->Impl->OutputLogFileLastTag) {
  3095. *this->Impl->OutputLogFile << std::endl;
  3096. this->Impl->OutputLogFileLastTag = logType;
  3097. }
  3098. }
  3099. }
  3100. if (!this->Impl->Quiet) {
  3101. if (logType == HANDLER_TEST_PROGRESS_OUTPUT) {
  3102. if (this->Impl->TestProgressOutput) {
  3103. if (this->Impl->FlushTestProgressLine) {
  3104. printf("\r");
  3105. this->Impl->FlushTestProgressLine = false;
  3106. std::cout.flush();
  3107. }
  3108. if (msg.find('\n') != std::string::npos) {
  3109. this->Impl->FlushTestProgressLine = true;
  3110. msg.erase(std::remove(msg.begin(), msg.end(), '\n'), msg.end());
  3111. }
  3112. std::cout << msg;
  3113. #ifndef _WIN32
  3114. printf("\x1B[K"); // move caret to end
  3115. #endif
  3116. std::cout.flush();
  3117. return;
  3118. }
  3119. logType = HANDLER_OUTPUT;
  3120. }
  3121. switch (logType) {
  3122. case DEBUG:
  3123. if (this->Impl->Debug) {
  3124. std::cout << msg << std::flush;
  3125. }
  3126. break;
  3127. case OUTPUT:
  3128. case HANDLER_OUTPUT:
  3129. if (this->Impl->Debug || this->Impl->Verbose) {
  3130. std::cout << msg << std::flush;
  3131. }
  3132. break;
  3133. case HANDLER_VERBOSE_OUTPUT:
  3134. if (this->Impl->Debug || this->Impl->ExtraVerbose) {
  3135. std::cout << msg << std::flush;
  3136. }
  3137. break;
  3138. case WARNING:
  3139. std::cerr << msg << std::flush;
  3140. break;
  3141. case ERROR_MESSAGE:
  3142. std::cerr << msg << std::flush;
  3143. cmSystemTools::SetErrorOccurred();
  3144. break;
  3145. default:
  3146. std::cout << msg << std::flush;
  3147. }
  3148. }
  3149. }
  3150. std::string cmCTest::GetColorCode(Color color) const
  3151. {
  3152. if (this->Impl->OutputColorCode) {
  3153. return cmStrCat("\033[0;", static_cast<int>(color), 'm');
  3154. }
  3155. return {};
  3156. }
  3157. void cmCTest::SetTimeLimit(cmValue val)
  3158. {
  3159. this->Impl->TimeLimit =
  3160. val ? cmDuration(atof(val->c_str())) : cmCTest::MaxDuration();
  3161. }
  3162. cmDuration cmCTest::GetElapsedTime() const
  3163. {
  3164. return std::chrono::duration_cast<cmDuration>(
  3165. std::chrono::steady_clock::now() - this->Impl->StartTime);
  3166. }
  3167. cmDuration cmCTest::GetRemainingTimeAllowed() const
  3168. {
  3169. return this->Impl->TimeLimit - this->GetElapsedTime();
  3170. }
  3171. cmDuration cmCTest::MaxDuration()
  3172. {
  3173. return cmDuration(1.0e7);
  3174. }
  3175. bool cmCTest::CompressString(std::string& str)
  3176. {
  3177. int ret;
  3178. z_stream strm;
  3179. strm.zalloc = Z_NULL;
  3180. strm.zfree = Z_NULL;
  3181. strm.opaque = Z_NULL;
  3182. ret = deflateInit(&strm, -1); // default compression level
  3183. if (ret != Z_OK) {
  3184. return false;
  3185. }
  3186. unsigned char* in =
  3187. reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
  3188. // zlib makes the guarantee that this is the maximum output size
  3189. int outSize =
  3190. static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
  3191. std::vector<unsigned char> out(outSize);
  3192. strm.avail_in = static_cast<uInt>(str.size());
  3193. strm.next_in = in;
  3194. strm.avail_out = outSize;
  3195. strm.next_out = out.data();
  3196. ret = deflate(&strm, Z_FINISH);
  3197. if (ret != Z_STREAM_END) {
  3198. cmCTestLog(this, ERROR_MESSAGE,
  3199. "Error during gzip compression." << std::endl);
  3200. return false;
  3201. }
  3202. (void)deflateEnd(&strm);
  3203. // Now base64 encode the resulting binary string
  3204. std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
  3205. size_t rlen = cmsysBase64_Encode(out.data(), strm.total_out,
  3206. base64EncodedBuffer.data(), 1);
  3207. str.assign(reinterpret_cast<char*>(base64EncodedBuffer.data()), rlen);
  3208. return true;
  3209. }
  3210. bool cmCTest::StartResultingXML(Part part, char const* name, int submitIndex,
  3211. cmGeneratedFileStream& xofs)
  3212. {
  3213. if (!name) {
  3214. cmCTestLog(
  3215. this, ERROR_MESSAGE,
  3216. "Cannot create resulting XML file without providing the name\n");
  3217. return false;
  3218. }
  3219. if (submitIndex == 0) {
  3220. submitIndex = this->Impl->SubmitIndex;
  3221. }
  3222. std::ostringstream ostr;
  3223. ostr << name;
  3224. if (submitIndex > 0) {
  3225. ostr << "_" << submitIndex;
  3226. }
  3227. ostr << ".xml";
  3228. if (this->Impl->CurrentTag.empty()) {
  3229. cmCTestLog(this, ERROR_MESSAGE,
  3230. "Current Tag empty, this may mean NightlyStartTime / "
  3231. "CTEST_NIGHTLY_START_TIME was not set correctly. Or "
  3232. "maybe you forgot to call ctest_start() before calling "
  3233. "ctest_configure().\n");
  3234. cmSystemTools::SetFatalErrorOccurred();
  3235. return false;
  3236. }
  3237. if (!this->OpenOutputFile(this->Impl->CurrentTag, ostr.str(), xofs, true)) {
  3238. cmCTestLog(this, ERROR_MESSAGE,
  3239. "Cannot create resulting XML file: " << ostr.str() << '\n');
  3240. return false;
  3241. }
  3242. this->AddSubmitFile(part, ostr.str());
  3243. return true;
  3244. }
  3245. bool cmCTest::StartLogFile(char const* name, int submitIndex,
  3246. cmGeneratedFileStream& xofs)
  3247. {
  3248. if (!name) {
  3249. cmCTestLog(this, ERROR_MESSAGE,
  3250. "Cannot create log file without providing the name\n");
  3251. return false;
  3252. }
  3253. if (submitIndex == 0) {
  3254. submitIndex = this->Impl->SubmitIndex;
  3255. }
  3256. std::ostringstream ostr;
  3257. ostr << "Last" << name;
  3258. if (submitIndex > 0) {
  3259. ostr << "_" << submitIndex;
  3260. }
  3261. if (!this->Impl->CurrentTag.empty()) {
  3262. ostr << "_" << this->Impl->CurrentTag;
  3263. }
  3264. ostr << ".log";
  3265. if (!this->OpenOutputFile("Temporary", ostr.str(), xofs)) {
  3266. cmCTestLog(this, ERROR_MESSAGE,
  3267. "Cannot create log file: " << ostr.str() << '\n');
  3268. return false;
  3269. }
  3270. return true;
  3271. }
  3272. cmInstrumentation& cmCTest::GetInstrumentation()
  3273. {
  3274. if (!this->Impl->Instrumentation) {
  3275. this->Impl->Instrumentation =
  3276. cm::make_unique<cmInstrumentation>(this->GetBinaryDir());
  3277. }
  3278. return *this->Impl->Instrumentation;
  3279. }
  3280. void cmCTest::ConvertInstrumentationSnippetsToXML(cmXMLWriter& xml,
  3281. std::string const& subdir)
  3282. {
  3283. std::string data_dir =
  3284. cmStrCat(this->GetInstrumentation().GetCDashDir(), '/', subdir);
  3285. cmsys::Directory d;
  3286. if (!d.Load(data_dir) || d.GetNumberOfFiles() == 0) {
  3287. return;
  3288. }
  3289. xml.StartElement("Commands");
  3290. for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
  3291. std::string fpath = d.GetFilePath(i);
  3292. std::string fname = d.GetFile(i);
  3293. if (fname.rfind('.', 0) == 0) {
  3294. continue;
  3295. }
  3296. this->ConvertInstrumentationJSONFileToXML(fpath, xml);
  3297. }
  3298. xml.EndElement(); // Commands
  3299. }
  3300. bool cmCTest::ConvertInstrumentationJSONFileToXML(std::string const& fpath,
  3301. cmXMLWriter& xml)
  3302. {
  3303. bool verboseCommands = this->GetInstrumentation().HasOption(
  3304. cmInstrumentationQuery::Option::CDashVerbose);
  3305. Json::Value root;
  3306. this->Impl->parseState = cmJSONState(fpath, &root);
  3307. if (!this->Impl->parseState.errors.empty()) {
  3308. cmCTestLog(this, ERROR_MESSAGE,
  3309. this->Impl->parseState.GetErrorMessage(true) << std::endl);
  3310. return false;
  3311. }
  3312. if (root.type() != Json::objectValue) {
  3313. cmCTestLog(this, ERROR_MESSAGE,
  3314. "Expected object, found " << root.type() << " for "
  3315. << root.asString() << std::endl);
  3316. return false;
  3317. }
  3318. std::vector<std::string> required_members = {
  3319. "command",
  3320. "role",
  3321. "dynamicSystemInformation",
  3322. };
  3323. for (std::string const& required_member : required_members) {
  3324. if (!root.isMember(required_member)) {
  3325. cmCTestLog(this, ERROR_MESSAGE,
  3326. fpath << " is missing the '" << required_member << "' key"
  3327. << std::endl);
  3328. return false;
  3329. }
  3330. }
  3331. // Do not record command-level data for Test.xml files because
  3332. // it is redundant with information actually captured by CTest.
  3333. bool generating_test_xml = root["role"] == "test";
  3334. if (!generating_test_xml) {
  3335. std::string element_name = root["role"].asString();
  3336. element_name[0] = static_cast<char>(std::toupper(element_name[0]));
  3337. xml.StartElement(element_name);
  3338. std::vector<std::string> keys = root.getMemberNames();
  3339. for (auto const& key : keys) {
  3340. auto key_type = root[key].type();
  3341. if (key_type == Json::objectValue || key_type == Json::arrayValue) {
  3342. continue;
  3343. }
  3344. if (key == "role" || key == "target" || key == "targetType" ||
  3345. key == "targetLabels") {
  3346. continue;
  3347. }
  3348. // Truncate the full command line if verbose instrumentation
  3349. // was not requested.
  3350. if (key == "command" && !verboseCommands) {
  3351. std::string command_str = root[key].asString();
  3352. std::string truncated = command_str.substr(0, command_str.find(' '));
  3353. if (command_str != truncated) {
  3354. truncated = cmStrCat(truncated, " (truncated)");
  3355. }
  3356. xml.Attribute(key.c_str(), truncated);
  3357. continue;
  3358. }
  3359. xml.Attribute(key.c_str(), root[key].asString());
  3360. }
  3361. }
  3362. // Record dynamicSystemInformation section as XML.
  3363. auto dynamic_information = root["dynamicSystemInformation"];
  3364. std::vector<std::string> keys = dynamic_information.getMemberNames();
  3365. for (auto const& key : keys) {
  3366. std::string measurement_name = key;
  3367. measurement_name[0] = static_cast<char>(std::toupper(measurement_name[0]));
  3368. xml.StartElement("NamedMeasurement");
  3369. xml.Attribute("type", "numeric/double");
  3370. xml.Attribute("name", measurement_name);
  3371. xml.Element("Value", dynamic_information[key].asString());
  3372. xml.EndElement(); // NamedMeasurement
  3373. }
  3374. // Record information about outputs and their sizes if found.
  3375. if (root.isMember("outputs") && root.isMember("outputSizes")) {
  3376. Json::ArrayIndex num_outputs =
  3377. std::min(root["outputs"].size(), root["outputSizes"].size());
  3378. if (num_outputs > 0) {
  3379. xml.StartElement("Outputs");
  3380. for (Json::ArrayIndex i = 0; i < num_outputs; ++i) {
  3381. xml.StartElement("Output");
  3382. xml.Attribute("name", root["outputs"][i].asString());
  3383. xml.Attribute("size", root["outputSizes"][i].asString());
  3384. xml.EndElement(); // Output
  3385. }
  3386. xml.EndElement(); // Outputs
  3387. }
  3388. }
  3389. if (!generating_test_xml) {
  3390. xml.EndElement(); // role
  3391. }
  3392. cmSystemTools::RemoveFile(fpath);
  3393. return true;
  3394. }