cmCTest.cxx 124 KB

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