cmCTest.cxx 124 KB

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