cmCTest.cxx 123 KB

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