cmCTest.cxx 124 KB

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