cmCTest.cxx 124 KB

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