cmCTest.cxx 128 KB

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