cmCTest.cxx 124 KB

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