cmCTest.cxx 124 KB

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