cmCTest.cxx 119 KB

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