cmCTest.cxx 116 KB

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