cmCTest.cxx 124 KB

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