cmCTest.cxx 124 KB

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