cmCTest.cxx 120 KB

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