cmCTest.cxx 119 KB

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