cmCTest.cxx 117 KB

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