cmCTest.cxx 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933
  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 "cmCTestBuildAndTest.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 "cmCommandLineArgument.h"
  52. #include "cmExecutionStatus.h"
  53. #include "cmGeneratedFileStream.h"
  54. #include "cmGlobalGenerator.h"
  55. #include "cmJSONState.h"
  56. #include "cmList.h"
  57. #include "cmListFileCache.h"
  58. #include "cmMakefile.h"
  59. #include "cmProcessOutput.h"
  60. #include "cmState.h"
  61. #include "cmStateSnapshot.h"
  62. #include "cmStateTypes.h"
  63. #include "cmStringAlgorithms.h"
  64. #include "cmSystemTools.h"
  65. #include "cmUVHandlePtr.h"
  66. #include "cmUVProcessChain.h"
  67. #include "cmUVStream.h"
  68. #include "cmValue.h"
  69. #include "cmVersion.h"
  70. #include "cmVersionConfig.h"
  71. #include "cmXMLWriter.h"
  72. #include "cmake.h"
  73. #if defined(__BEOS__) || defined(__HAIKU__)
  74. # include <be/kernel/OS.h> /* disable_debugger() API. */
  75. #endif
  76. struct cmCTest::Private
  77. {
  78. Private(cmCTest* ctest)
  79. : BuildAndTest(ctest)
  80. {
  81. }
  82. /** Representation of one part. */
  83. struct PartInfo
  84. {
  85. void SetName(const std::string& name) { this->Name = name; }
  86. const std::string& GetName() const { return this->Name; }
  87. void Enable() { this->Enabled = true; }
  88. explicit operator bool() const { return this->Enabled; }
  89. std::vector<std::string> SubmitFiles;
  90. private:
  91. bool Enabled = false;
  92. std::string Name;
  93. };
  94. int RepeatCount = 1; // default to run each test once
  95. cmCTest::Repeat RepeatMode = cmCTest::Repeat::Never;
  96. std::string ConfigType;
  97. std::string ScheduleType;
  98. std::chrono::system_clock::time_point StopTime;
  99. bool StopOnFailure = false;
  100. bool TestProgressOutput = false;
  101. bool Verbose = false;
  102. bool ExtraVerbose = false;
  103. bool ProduceXML = false;
  104. bool LabelSummary = true;
  105. bool SubprojectSummary = true;
  106. bool UseHTTP10 = false;
  107. bool PrintLabels = false;
  108. bool Failover = false;
  109. bool FlushTestProgressLine = false;
  110. bool RunConfigurationScript = false;
  111. // these are helper classes
  112. cmCTestBuildHandler BuildHandler;
  113. cmCTestBuildAndTest BuildAndTest;
  114. cmCTestCoverageHandler CoverageHandler;
  115. cmCTestScriptHandler ScriptHandler;
  116. cmCTestTestHandler TestHandler;
  117. cmCTestUpdateHandler UpdateHandler;
  118. cmCTestConfigureHandler ConfigureHandler;
  119. cmCTestMemCheckHandler MemCheckHandler;
  120. cmCTestSubmitHandler SubmitHandler;
  121. cmCTestUploadHandler UploadHandler;
  122. std::vector<cmCTestGenericHandler*> GetTestingHandlers()
  123. {
  124. return { &this->BuildHandler, &this->CoverageHandler,
  125. &this->ScriptHandler, &this->TestHandler,
  126. &this->UpdateHandler, &this->ConfigureHandler,
  127. &this->MemCheckHandler, &this->SubmitHandler,
  128. &this->UploadHandler };
  129. }
  130. std::map<std::string, cmCTestGenericHandler*> GetNamedTestingHandlers()
  131. {
  132. return { { "build", &this->BuildHandler },
  133. { "coverage", &this->CoverageHandler },
  134. { "script", &this->ScriptHandler },
  135. { "test", &this->TestHandler },
  136. { "update", &this->UpdateHandler },
  137. { "configure", &this->ConfigureHandler },
  138. { "memcheck", &this->MemCheckHandler },
  139. { "submit", &this->SubmitHandler },
  140. { "upload", &this->UploadHandler } };
  141. }
  142. bool ShowOnly = false;
  143. bool OutputAsJson = false;
  144. int OutputAsJsonVersion = 1;
  145. // TODO: The ctest configuration should be a hierarchy of
  146. // configuration option sources: command-line, script, ini file.
  147. // Then the ini file can get re-loaded whenever it changes without
  148. // affecting any higher-precedence settings.
  149. std::map<std::string, std::string> CTestConfiguration;
  150. std::map<std::string, std::string> CTestConfigurationOverwrites;
  151. PartInfo Parts[PartCount];
  152. std::map<std::string, Part> PartMap;
  153. std::string CurrentTag;
  154. bool TomorrowTag = false;
  155. int TestModel = cmCTest::EXPERIMENTAL;
  156. std::string SpecificGroup;
  157. cmDuration TimeOut = cmDuration::zero();
  158. cmDuration GlobalTimeout = cmDuration::zero();
  159. int MaxTestNameWidth = 30;
  160. cm::optional<size_t> ParallelLevel = 1;
  161. bool ParallelLevelSetInCli = false;
  162. unsigned long TestLoad = 0;
  163. int CompatibilityMode;
  164. // information for the --build-and-test options
  165. std::string BinaryDir;
  166. std::string TestDir;
  167. std::string NotesFiles;
  168. bool InteractiveDebugMode = true;
  169. bool ShortDateFormat = true;
  170. bool CompressXMLFiles = false;
  171. bool CompressTestOutput = true;
  172. bool SuppressUpdatingCTestConfiguration = false;
  173. bool Debug = 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. cm::optional<cmCTest::LogType> OutputLogFileLastTag;
  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(cm::make_unique<Private>(this))
  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. cmCTestCoverageHandler* cmCTest::GetCoverageHandler()
  795. {
  796. return &this->Impl->CoverageHandler;
  797. }
  798. cmCTestScriptHandler* cmCTest::GetScriptHandler()
  799. {
  800. return &this->Impl->ScriptHandler;
  801. }
  802. cmCTestTestHandler* cmCTest::GetTestHandler()
  803. {
  804. return &this->Impl->TestHandler;
  805. }
  806. cmCTestUpdateHandler* cmCTest::GetUpdateHandler()
  807. {
  808. return &this->Impl->UpdateHandler;
  809. }
  810. cmCTestConfigureHandler* cmCTest::GetConfigureHandler()
  811. {
  812. return &this->Impl->ConfigureHandler;
  813. }
  814. cmCTestMemCheckHandler* cmCTest::GetMemCheckHandler()
  815. {
  816. return &this->Impl->MemCheckHandler;
  817. }
  818. cmCTestSubmitHandler* cmCTest::GetSubmitHandler()
  819. {
  820. return &this->Impl->SubmitHandler;
  821. }
  822. cmCTestUploadHandler* cmCTest::GetUploadHandler()
  823. {
  824. return &this->Impl->UploadHandler;
  825. }
  826. int cmCTest::ProcessSteps()
  827. {
  828. int res = 0;
  829. bool notest = true;
  830. for (Part p = PartStart; notest && p != PartCount;
  831. p = static_cast<Part>(p + 1)) {
  832. notest = !this->Impl->Parts[p];
  833. }
  834. if (notest) {
  835. if (this->GetTestHandler()->ProcessHandler() < 0) {
  836. cmCTestLog(this, ERROR_MESSAGE, "Errors while running CTest\n");
  837. if (!this->Impl->OutputTestOutputOnTestFailure) {
  838. const std::string lastTestLog =
  839. this->GetBinaryDir() + "/Testing/Temporary/LastTest.log";
  840. cmCTestLog(this, ERROR_MESSAGE,
  841. "Output from these tests are in: " << lastTestLog << '\n');
  842. cmCTestLog(this, ERROR_MESSAGE,
  843. "Use \"--rerun-failed --output-on-failure\" to re-run the "
  844. "failed cases verbosely.\n");
  845. }
  846. return cmCTest::TEST_ERRORS;
  847. }
  848. return 0;
  849. }
  850. cmCTestScriptHandler script;
  851. script.SetCTestInstance(this);
  852. script.CreateCMake();
  853. cmMakefile& mf = *script.GetMakefile();
  854. this->SetCMakeVariables(mf);
  855. std::vector<cmListFileArgument> args{
  856. cmListFileArgument("RETURN_VALUE", cmListFileArgument::Unquoted, 0),
  857. cmListFileArgument("return_value", cmListFileArgument::Unquoted, 0),
  858. };
  859. if (this->Impl->Parts[PartUpdate] &&
  860. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  861. auto const func = cmListFileFunction("ctest_update", 0, 0, args);
  862. auto status = cmExecutionStatus(mf);
  863. if (!mf.ExecuteCommand(func, status)) {
  864. res |= cmCTest::UPDATE_ERRORS;
  865. }
  866. }
  867. if (this->Impl->TestModel == cmCTest::CONTINUOUS &&
  868. mf.GetDefinition("return_value").IsOff()) {
  869. return 0;
  870. }
  871. if (this->Impl->Parts[PartConfigure] &&
  872. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  873. auto const func = cmListFileFunction("ctest_configure", 0, 0, args);
  874. auto status = cmExecutionStatus(mf);
  875. if (!mf.ExecuteCommand(func, status) ||
  876. std::stoi(mf.GetDefinition("return_value")) < 0) {
  877. res |= cmCTest::CONFIGURE_ERRORS;
  878. }
  879. }
  880. if (this->Impl->Parts[PartBuild] &&
  881. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  882. this->UpdateCTestConfiguration();
  883. this->SetCMakeVariables(mf);
  884. auto const func = cmListFileFunction("ctest_build", 0, 0, args);
  885. auto status = cmExecutionStatus(mf);
  886. if (!mf.ExecuteCommand(func, status) ||
  887. std::stoi(mf.GetDefinition("return_value")) < 0) {
  888. res |= cmCTest::BUILD_ERRORS;
  889. }
  890. }
  891. if ((this->Impl->Parts[PartTest] || notest) &&
  892. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  893. this->UpdateCTestConfiguration();
  894. this->SetCMakeVariables(mf);
  895. auto const func = cmListFileFunction("ctest_test", 0, 0, args);
  896. auto status = cmExecutionStatus(mf);
  897. if (!mf.ExecuteCommand(func, status) ||
  898. std::stoi(mf.GetDefinition("return_value")) < 0) {
  899. res |= cmCTest::TEST_ERRORS;
  900. }
  901. }
  902. if (this->Impl->Parts[PartCoverage] &&
  903. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  904. this->UpdateCTestConfiguration();
  905. this->SetCMakeVariables(mf);
  906. auto const func = cmListFileFunction("ctest_coverage", 0, 0, args);
  907. auto status = cmExecutionStatus(mf);
  908. if (!mf.ExecuteCommand(func, status) ||
  909. std::stoi(mf.GetDefinition("return_value")) < 0) {
  910. res |= cmCTest::COVERAGE_ERRORS;
  911. }
  912. }
  913. if (this->Impl->Parts[PartMemCheck] &&
  914. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  915. this->UpdateCTestConfiguration();
  916. this->SetCMakeVariables(mf);
  917. auto const func = cmListFileFunction("ctest_memcheck", 0, 0, args);
  918. auto status = cmExecutionStatus(mf);
  919. if (!mf.ExecuteCommand(func, status) ||
  920. std::stoi(mf.GetDefinition("return_value")) < 0) {
  921. res |= cmCTest::MEMORY_ERRORS;
  922. }
  923. }
  924. if (!notest) {
  925. std::string notes_dir = this->Impl->BinaryDir + "/Testing/Notes";
  926. if (cmSystemTools::FileIsDirectory(notes_dir)) {
  927. cmsys::Directory d;
  928. d.Load(notes_dir);
  929. unsigned long kk;
  930. for (kk = 0; kk < d.GetNumberOfFiles(); kk++) {
  931. const char* file = d.GetFile(kk);
  932. std::string fullname = notes_dir + "/" + file;
  933. if (cmSystemTools::FileExists(fullname, true)) {
  934. if (!this->Impl->NotesFiles.empty()) {
  935. this->Impl->NotesFiles += ";";
  936. }
  937. this->Impl->NotesFiles += fullname;
  938. this->Impl->Parts[PartNotes].Enable();
  939. }
  940. }
  941. }
  942. }
  943. if (this->Impl->Parts[PartNotes]) {
  944. this->UpdateCTestConfiguration();
  945. if (!this->Impl->NotesFiles.empty()) {
  946. this->GenerateNotesFile(this->Impl->NotesFiles);
  947. }
  948. }
  949. if (this->Impl->Parts[PartSubmit]) {
  950. this->UpdateCTestConfiguration();
  951. this->SetCMakeVariables(mf);
  952. std::string count = this->GetCTestConfiguration("CTestSubmitRetryCount");
  953. std::string delay = this->GetCTestConfiguration("CTestSubmitRetryDelay");
  954. auto const func = cmListFileFunction(
  955. "ctest_submit", 0, 0,
  956. {
  957. cmListFileArgument("RETRY_COUNT", cmListFileArgument::Unquoted, 0),
  958. cmListFileArgument(count, cmListFileArgument::Quoted, 0),
  959. cmListFileArgument("RETRY_DELAY", cmListFileArgument::Unquoted, 0),
  960. cmListFileArgument(delay, cmListFileArgument::Quoted, 0),
  961. cmListFileArgument("RETURN_VALUE", cmListFileArgument::Unquoted, 0),
  962. cmListFileArgument("return_value", cmListFileArgument::Unquoted, 0),
  963. });
  964. auto status = cmExecutionStatus(mf);
  965. if (!mf.ExecuteCommand(func, status) ||
  966. std::stoi(mf.GetDefinition("return_value")) < 0) {
  967. res |= cmCTest::SUBMIT_ERRORS;
  968. }
  969. }
  970. return res;
  971. }
  972. std::string cmCTest::GetTestModelString()
  973. {
  974. if (!this->Impl->SpecificGroup.empty()) {
  975. return this->Impl->SpecificGroup;
  976. }
  977. switch (this->Impl->TestModel) {
  978. case cmCTest::NIGHTLY:
  979. return "Nightly";
  980. case cmCTest::CONTINUOUS:
  981. return "Continuous";
  982. }
  983. return "Experimental";
  984. }
  985. int cmCTest::GetTestModelFromString(const std::string& str)
  986. {
  987. if (str.empty()) {
  988. return cmCTest::EXPERIMENTAL;
  989. }
  990. std::string rstr = cmSystemTools::LowerCase(str);
  991. if (cmHasLiteralPrefix(rstr, "cont")) {
  992. return cmCTest::CONTINUOUS;
  993. }
  994. if (cmHasLiteralPrefix(rstr, "nigh")) {
  995. return cmCTest::NIGHTLY;
  996. }
  997. return cmCTest::EXPERIMENTAL;
  998. }
  999. bool cmCTest::RunMakeCommand(const std::string& command, std::string& output,
  1000. int* retVal, const char* dir, cmDuration timeout,
  1001. std::ostream& ofs, Encoding encoding)
  1002. {
  1003. // First generate the command and arguments
  1004. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  1005. if (args.empty()) {
  1006. return false;
  1007. }
  1008. output.clear();
  1009. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
  1010. for (auto const& arg : args) {
  1011. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
  1012. }
  1013. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
  1014. // Now create process object
  1015. cmUVProcessChainBuilder builder;
  1016. builder.AddCommand(args).SetMergedBuiltinStreams();
  1017. if (dir) {
  1018. builder.SetWorkingDirectory(dir);
  1019. }
  1020. auto chain = builder.Start();
  1021. cm::uv_pipe_ptr outputStream;
  1022. outputStream.init(chain.GetLoop(), 0);
  1023. uv_pipe_open(outputStream, chain.OutputStream());
  1024. // Initialize tick's
  1025. std::string::size_type tick = 0;
  1026. std::string::size_type tick_len = 1024;
  1027. std::string::size_type tick_line_len = 50;
  1028. cmProcessOutput processOutput(encoding);
  1029. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1030. " Each . represents " << tick_len
  1031. << " bytes of output\n"
  1032. " "
  1033. << std::flush);
  1034. auto outputHandle = cmUVStreamRead(
  1035. outputStream,
  1036. [this, &processOutput, &output, &tick, &tick_len, &tick_line_len,
  1037. &ofs](std::vector<char> data) {
  1038. std::string strdata;
  1039. processOutput.DecodeText(data.data(), data.size(), strdata);
  1040. for (char& cc : strdata) {
  1041. if (cc == 0) {
  1042. cc = '\n';
  1043. }
  1044. }
  1045. output.append(strdata);
  1046. while (output.size() > (tick * tick_len)) {
  1047. tick++;
  1048. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
  1049. if (tick % tick_line_len == 0 && tick > 0) {
  1050. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1051. " Size: " << int((double(output.size()) / 1024.0) + 1)
  1052. << "K\n " << std::flush);
  1053. }
  1054. }
  1055. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, strdata);
  1056. if (ofs) {
  1057. ofs << strdata;
  1058. }
  1059. },
  1060. [this, &processOutput, &output, &ofs]() {
  1061. std::string strdata;
  1062. processOutput.DecodeText(std::string(), strdata);
  1063. if (!strdata.empty()) {
  1064. output.append(strdata);
  1065. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, strdata);
  1066. if (ofs) {
  1067. ofs << strdata;
  1068. }
  1069. }
  1070. });
  1071. bool finished = chain.Wait(static_cast<uint64_t>(timeout.count() * 1000.0));
  1072. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  1073. " Size of output: " << int(double(output.size()) / 1024.0) << "K"
  1074. << std::endl);
  1075. if (finished) {
  1076. auto const& status = chain.GetStatus(0);
  1077. auto exception = status.GetException();
  1078. switch (exception.first) {
  1079. case cmUVProcessChain::ExceptionCode::None:
  1080. *retVal = static_cast<int>(status.ExitStatus);
  1081. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1082. "Command exited with the value: " << *retVal << std::endl);
  1083. break;
  1084. case cmUVProcessChain::ExceptionCode::Spawn:
  1085. output += "\n*** ERROR executing: ";
  1086. output += exception.second;
  1087. output += "\n***The build process failed.";
  1088. cmCTestLog(this, ERROR_MESSAGE,
  1089. "There was an error: " << exception.second << std::endl);
  1090. break;
  1091. default:
  1092. *retVal = static_cast<int>(exception.first);
  1093. cmCTestLog(this, WARNING,
  1094. "There was an exception: " << *retVal << std::endl);
  1095. break;
  1096. }
  1097. } else {
  1098. cmCTestLog(this, WARNING, "There was a timeout" << std::endl);
  1099. }
  1100. return true;
  1101. }
  1102. bool cmCTest::RunTest(std::vector<std::string> const& argv,
  1103. std::string* output, int* retVal, cmDuration timeout)
  1104. {
  1105. std::vector<char> tempOutput;
  1106. if (output) {
  1107. output->clear();
  1108. }
  1109. cmUVProcessChainBuilder builder;
  1110. builder.AddCommand(argv).SetMergedBuiltinStreams();
  1111. auto chain = builder.Start();
  1112. cmProcessOutput processOutput(cmProcessOutput::Auto);
  1113. cm::uv_pipe_ptr outputStream;
  1114. outputStream.init(chain.GetLoop(), 0);
  1115. uv_pipe_open(outputStream, chain.OutputStream());
  1116. auto outputHandle = cmUVStreamRead(
  1117. outputStream,
  1118. [&output, &tempOutput](std::vector<char> data) {
  1119. if (output) {
  1120. cm::append(tempOutput, data.data(), data.data() + data.size());
  1121. }
  1122. },
  1123. []() {});
  1124. bool complete = chain.Wait(static_cast<uint64_t>(timeout.count() * 1000.0));
  1125. processOutput.DecodeText(tempOutput, tempOutput);
  1126. if (output && tempOutput.begin() != tempOutput.end()) {
  1127. output->append(tempOutput.data(), tempOutput.size());
  1128. }
  1129. bool result = false;
  1130. if (complete) {
  1131. auto const& status = chain.GetStatus(0);
  1132. auto exception = status.GetException();
  1133. switch (exception.first) {
  1134. case cmUVProcessChain::ExceptionCode::None:
  1135. *retVal = static_cast<int>(status.ExitStatus);
  1136. result = true;
  1137. break;
  1138. case cmUVProcessChain::ExceptionCode::Spawn: {
  1139. if (output) {
  1140. std::string outerr =
  1141. cmStrCat("\n*** ERROR executing: ", exception.second);
  1142. *output += outerr;
  1143. }
  1144. } break;
  1145. default: {
  1146. *retVal = status.TermSignal;
  1147. if (output) {
  1148. std::string outerr =
  1149. cmStrCat("\n*** Exception executing: ", exception.second);
  1150. *output += outerr;
  1151. }
  1152. } break;
  1153. }
  1154. }
  1155. return result;
  1156. }
  1157. std::string cmCTest::SafeBuildIdField(const std::string& value)
  1158. {
  1159. std::string safevalue(value);
  1160. if (!safevalue.empty()) {
  1161. // Disallow non-filename and non-space whitespace characters.
  1162. // If they occur, replace them with ""
  1163. //
  1164. const char* disallowed = "\\:*?\"<>|\n\r\t\f\v";
  1165. if (safevalue.find_first_of(disallowed) != std::string::npos) {
  1166. std::string::size_type i = 0;
  1167. std::string::size_type n = strlen(disallowed);
  1168. char replace[2];
  1169. replace[1] = 0;
  1170. for (i = 0; i < n; ++i) {
  1171. replace[0] = disallowed[i];
  1172. cmSystemTools::ReplaceString(safevalue, replace, "");
  1173. }
  1174. }
  1175. }
  1176. if (safevalue.empty()) {
  1177. safevalue = "(empty)";
  1178. }
  1179. return safevalue;
  1180. }
  1181. void cmCTest::StartXML(cmXMLWriter& xml, bool append)
  1182. {
  1183. if (this->Impl->CurrentTag.empty()) {
  1184. cmCTestLog(this, ERROR_MESSAGE,
  1185. "Current Tag empty, this may mean"
  1186. " NightlStartTime was not set correctly."
  1187. << std::endl);
  1188. cmSystemTools::SetFatalErrorOccurred();
  1189. }
  1190. // find out about the system
  1191. cmsys::SystemInformation info;
  1192. info.RunCPUCheck();
  1193. info.RunOSCheck();
  1194. info.RunMemoryCheck();
  1195. std::string buildname =
  1196. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1197. std::string stamp = cmCTest::SafeBuildIdField(this->Impl->CurrentTag + "-" +
  1198. this->GetTestModelString());
  1199. std::string site =
  1200. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("Site"));
  1201. xml.StartDocument();
  1202. xml.StartElement("Site");
  1203. xml.Attribute("BuildName", buildname);
  1204. xml.BreakAttributes();
  1205. xml.Attribute("BuildStamp", stamp);
  1206. xml.Attribute("Name", site);
  1207. xml.Attribute("Generator",
  1208. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1209. if (append) {
  1210. xml.Attribute("Append", "true");
  1211. }
  1212. xml.Attribute("CompilerName", this->GetCTestConfiguration("Compiler"));
  1213. xml.Attribute("CompilerVersion",
  1214. this->GetCTestConfiguration("CompilerVersion"));
  1215. xml.Attribute("OSName", info.GetOSName());
  1216. xml.Attribute("Hostname", info.GetHostname());
  1217. xml.Attribute("OSRelease", info.GetOSRelease());
  1218. xml.Attribute("OSVersion", info.GetOSVersion());
  1219. xml.Attribute("OSPlatform", info.GetOSPlatform());
  1220. xml.Attribute("Is64Bits", info.Is64Bits());
  1221. xml.Attribute("VendorString", info.GetVendorString());
  1222. xml.Attribute("VendorID", info.GetVendorID());
  1223. xml.Attribute("FamilyID", info.GetFamilyID());
  1224. xml.Attribute("ModelID", info.GetModelID());
  1225. xml.Attribute("ModelName", info.GetModelName());
  1226. xml.Attribute("ProcessorCacheSize", info.GetProcessorCacheSize());
  1227. xml.Attribute("NumberOfLogicalCPU", info.GetNumberOfLogicalCPU());
  1228. xml.Attribute("NumberOfPhysicalCPU", info.GetNumberOfPhysicalCPU());
  1229. xml.Attribute("TotalVirtualMemory", info.GetTotalVirtualMemory());
  1230. xml.Attribute("TotalPhysicalMemory", info.GetTotalPhysicalMemory());
  1231. xml.Attribute("LogicalProcessorsPerPhysical",
  1232. info.GetLogicalProcessorsPerPhysical());
  1233. xml.Attribute("ProcessorClockFrequency", info.GetProcessorClockFrequency());
  1234. std::string changeId = this->GetCTestConfiguration("ChangeId");
  1235. if (!changeId.empty()) {
  1236. xml.Attribute("ChangeId", changeId);
  1237. }
  1238. this->AddSiteProperties(xml);
  1239. }
  1240. void cmCTest::AddSiteProperties(cmXMLWriter& xml)
  1241. {
  1242. cmCTestScriptHandler* ch = this->GetScriptHandler();
  1243. cmake* cm = ch->GetCMake();
  1244. // if no CMake then this is the old style script and props like
  1245. // this will not work anyway.
  1246. if (!cm) {
  1247. return;
  1248. }
  1249. // This code should go when cdash is changed to use labels only
  1250. cmValue subproject = cm->GetState()->GetGlobalProperty("SubProject");
  1251. if (subproject) {
  1252. xml.StartElement("Subproject");
  1253. xml.Attribute("name", *subproject);
  1254. cmValue labels =
  1255. ch->GetCMake()->GetState()->GetGlobalProperty("SubProjectLabels");
  1256. if (labels) {
  1257. xml.StartElement("Labels");
  1258. cmList args{ *labels };
  1259. for (std::string const& i : args) {
  1260. xml.Element("Label", i);
  1261. }
  1262. xml.EndElement();
  1263. }
  1264. xml.EndElement();
  1265. }
  1266. // This code should stay when cdash only does label based sub-projects
  1267. cmValue label = cm->GetState()->GetGlobalProperty("Label");
  1268. if (label) {
  1269. xml.StartElement("Labels");
  1270. xml.Element("Label", *label);
  1271. xml.EndElement();
  1272. }
  1273. }
  1274. void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
  1275. {
  1276. for (std::string const& subproj : this->GetLabelsForSubprojects()) {
  1277. xml.StartElement("Subproject");
  1278. xml.Attribute("name", subproj);
  1279. xml.Element("Label", subproj);
  1280. xml.EndElement(); // Subproject
  1281. }
  1282. }
  1283. std::vector<std::string> cmCTest::GetLabelsForSubprojects()
  1284. {
  1285. std::string labelsForSubprojects =
  1286. this->GetCTestConfiguration("LabelsForSubprojects");
  1287. cmList subprojects{ labelsForSubprojects };
  1288. // sort the array
  1289. std::sort(subprojects.begin(), subprojects.end());
  1290. // remove duplicates
  1291. auto new_end = std::unique(subprojects.begin(), subprojects.end());
  1292. subprojects.erase(new_end, subprojects.end());
  1293. return std::move(subprojects.data());
  1294. }
  1295. void cmCTest::EndXML(cmXMLWriter& xml)
  1296. {
  1297. xml.EndElement(); // Site
  1298. xml.EndDocument();
  1299. }
  1300. int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
  1301. std::vector<std::string> const& files)
  1302. {
  1303. std::string buildname =
  1304. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1305. xml.StartDocument();
  1306. xml.ProcessingInstruction("xml-stylesheet",
  1307. "type=\"text/xsl\" "
  1308. "href=\"Dart/Source/Server/XSL/Build.xsl "
  1309. "<file:///Dart/Source/Server/XSL/Build.xsl> \"");
  1310. xml.StartElement("Site");
  1311. xml.Attribute("BuildName", buildname);
  1312. xml.Attribute("BuildStamp",
  1313. this->Impl->CurrentTag + "-" + this->GetTestModelString());
  1314. xml.Attribute("Name", this->GetCTestConfiguration("Site"));
  1315. xml.Attribute("Generator",
  1316. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1317. this->AddSiteProperties(xml);
  1318. xml.StartElement("Notes");
  1319. for (std::string const& file : files) {
  1320. cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
  1321. std::string note_time = this->CurrentTime();
  1322. xml.StartElement("Note");
  1323. xml.Attribute("Name", file);
  1324. xml.Element("Time", std::chrono::system_clock::now());
  1325. xml.Element("DateTime", note_time);
  1326. xml.StartElement("Text");
  1327. cmsys::ifstream ifs(file.c_str());
  1328. if (ifs) {
  1329. std::string line;
  1330. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1331. xml.Content(line);
  1332. xml.Content("\n");
  1333. }
  1334. ifs.close();
  1335. } else {
  1336. xml.Content("Problem reading file: " + file + "\n");
  1337. cmCTestLog(this, ERROR_MESSAGE,
  1338. "Problem reading file: " << file << " while creating notes"
  1339. << std::endl);
  1340. }
  1341. xml.EndElement(); // Text
  1342. xml.EndElement(); // Note
  1343. }
  1344. xml.EndElement(); // Notes
  1345. xml.EndElement(); // Site
  1346. xml.EndDocument();
  1347. return 1;
  1348. }
  1349. int cmCTest::GenerateNotesFile(std::vector<std::string> const& files)
  1350. {
  1351. cmGeneratedFileStream ofs;
  1352. if (!this->OpenOutputFile(this->Impl->CurrentTag, "Notes.xml", ofs)) {
  1353. cmCTestLog(this, ERROR_MESSAGE, "Cannot open notes file" << std::endl);
  1354. return 1;
  1355. }
  1356. cmXMLWriter xml(ofs);
  1357. this->GenerateCTestNotesOutput(xml, files);
  1358. return 0;
  1359. }
  1360. int cmCTest::GenerateNotesFile(const std::string& cfiles)
  1361. {
  1362. if (cfiles.empty()) {
  1363. return 1;
  1364. }
  1365. cmCTestLog(this, OUTPUT, "Create notes file" << std::endl);
  1366. std::vector<std::string> const files =
  1367. cmSystemTools::SplitString(cfiles, ';');
  1368. if (files.empty()) {
  1369. return 1;
  1370. }
  1371. return this->GenerateNotesFile(files);
  1372. }
  1373. int cmCTest::GenerateDoneFile()
  1374. {
  1375. cmGeneratedFileStream ofs;
  1376. if (!this->OpenOutputFile(this->Impl->CurrentTag, "Done.xml", ofs)) {
  1377. cmCTestLog(this, ERROR_MESSAGE, "Cannot open done file" << std::endl);
  1378. return 1;
  1379. }
  1380. cmXMLWriter xml(ofs);
  1381. xml.StartDocument();
  1382. xml.StartElement("Done");
  1383. xml.Element("buildId", this->Impl->BuildID);
  1384. xml.Element("time", std::chrono::system_clock::now());
  1385. xml.EndElement(); // Done
  1386. xml.EndDocument();
  1387. return 0;
  1388. }
  1389. bool cmCTest::TryToChangeDirectory(std::string const& dir)
  1390. {
  1391. cmCTestLog(this, OUTPUT,
  1392. "Internal ctest changing into directory: " << dir << std::endl);
  1393. cmsys::Status status = cmSystemTools::ChangeDirectory(dir);
  1394. if (!status) {
  1395. auto msg = "Failed to change working directory to \"" + dir +
  1396. "\" : " + status.GetString() + "\n";
  1397. cmCTestLog(this, ERROR_MESSAGE, msg);
  1398. return false;
  1399. }
  1400. return true;
  1401. }
  1402. std::string cmCTest::Base64GzipEncodeFile(std::string const& file)
  1403. {
  1404. const std::string currDir = cmSystemTools::GetCurrentWorkingDirectory();
  1405. std::string parentDir = cmSystemTools::GetParentDirectory(file);
  1406. // Temporarily change to the file's directory so the tar gets created
  1407. // with a flat directory structure.
  1408. if (currDir != parentDir) {
  1409. if (!this->TryToChangeDirectory(parentDir)) {
  1410. return "";
  1411. }
  1412. }
  1413. std::string tarFile = file + "_temp.tar.gz";
  1414. std::vector<std::string> files;
  1415. files.push_back(file);
  1416. if (!cmSystemTools::CreateTar(tarFile, files, {},
  1417. cmSystemTools::TarCompressGZip, false)) {
  1418. cmCTestLog(this, ERROR_MESSAGE,
  1419. "Error creating tar while "
  1420. "encoding file: "
  1421. << file << std::endl);
  1422. return "";
  1423. }
  1424. std::string base64 = this->Base64EncodeFile(tarFile);
  1425. cmSystemTools::RemoveFile(tarFile);
  1426. // Change back to the directory we started in.
  1427. if (currDir != parentDir) {
  1428. cmSystemTools::ChangeDirectory(currDir);
  1429. }
  1430. return base64;
  1431. }
  1432. std::string cmCTest::Base64EncodeFile(std::string const& file)
  1433. {
  1434. size_t const len = cmSystemTools::FileLength(file);
  1435. cmsys::ifstream ifs(file.c_str(),
  1436. std::ios::in
  1437. #ifdef _WIN32
  1438. | std::ios::binary
  1439. #endif
  1440. );
  1441. std::vector<char> file_buffer(len + 1);
  1442. ifs.read(file_buffer.data(), len);
  1443. ifs.close();
  1444. std::vector<char> encoded_buffer((len * 3) / 2 + 5);
  1445. size_t const rlen = cmsysBase64_Encode(
  1446. reinterpret_cast<unsigned char*>(file_buffer.data()), len,
  1447. reinterpret_cast<unsigned char*>(encoded_buffer.data()), 1);
  1448. return std::string(encoded_buffer.data(), rlen);
  1449. }
  1450. bool cmCTest::SubmitExtraFiles(std::vector<std::string> const& files)
  1451. {
  1452. for (std::string const& file : files) {
  1453. if (!cmSystemTools::FileExists(file)) {
  1454. cmCTestLog(this, ERROR_MESSAGE,
  1455. "Cannot find extra file: " << file << " to submit."
  1456. << std::endl);
  1457. return false;
  1458. }
  1459. this->AddSubmitFile(PartExtraFiles, file);
  1460. }
  1461. return true;
  1462. }
  1463. bool cmCTest::SubmitExtraFiles(const std::string& cfiles)
  1464. {
  1465. if (cfiles.empty()) {
  1466. return true;
  1467. }
  1468. cmCTestLog(this, OUTPUT, "Submit extra files" << std::endl);
  1469. std::vector<std::string> const files =
  1470. cmSystemTools::SplitString(cfiles, ';');
  1471. if (files.empty()) {
  1472. return true;
  1473. }
  1474. return this->SubmitExtraFiles(files);
  1475. }
  1476. // for a -D argument convert the next argument into
  1477. // the proper list of dashboard steps via SetTest
  1478. bool cmCTest::AddTestsForDashboardType(std::string const& targ)
  1479. {
  1480. if (targ == "Experimental") {
  1481. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1482. this->SetTest("Start");
  1483. this->SetTest("Configure");
  1484. this->SetTest("Build");
  1485. this->SetTest("Test");
  1486. this->SetTest("Coverage");
  1487. this->SetTest("Submit");
  1488. } else if (targ == "ExperimentalStart") {
  1489. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1490. this->SetTest("Start");
  1491. } else if (targ == "ExperimentalUpdate") {
  1492. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1493. this->SetTest("Update");
  1494. } else if (targ == "ExperimentalConfigure") {
  1495. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1496. this->SetTest("Configure");
  1497. } else if (targ == "ExperimentalBuild") {
  1498. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1499. this->SetTest("Build");
  1500. } else if (targ == "ExperimentalTest") {
  1501. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1502. this->SetTest("Test");
  1503. } else if (targ == "ExperimentalMemCheck" || targ == "ExperimentalPurify") {
  1504. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1505. this->SetTest("MemCheck");
  1506. } else if (targ == "ExperimentalCoverage") {
  1507. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1508. this->SetTest("Coverage");
  1509. } else if (targ == "ExperimentalSubmit") {
  1510. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1511. this->SetTest("Submit");
  1512. } else if (targ == "Continuous") {
  1513. this->SetTestModel(cmCTest::CONTINUOUS);
  1514. this->SetTest("Start");
  1515. this->SetTest("Update");
  1516. this->SetTest("Configure");
  1517. this->SetTest("Build");
  1518. this->SetTest("Test");
  1519. this->SetTest("Coverage");
  1520. this->SetTest("Submit");
  1521. } else if (targ == "ContinuousStart") {
  1522. this->SetTestModel(cmCTest::CONTINUOUS);
  1523. this->SetTest("Start");
  1524. } else if (targ == "ContinuousUpdate") {
  1525. this->SetTestModel(cmCTest::CONTINUOUS);
  1526. this->SetTest("Update");
  1527. } else if (targ == "ContinuousConfigure") {
  1528. this->SetTestModel(cmCTest::CONTINUOUS);
  1529. this->SetTest("Configure");
  1530. } else if (targ == "ContinuousBuild") {
  1531. this->SetTestModel(cmCTest::CONTINUOUS);
  1532. this->SetTest("Build");
  1533. } else if (targ == "ContinuousTest") {
  1534. this->SetTestModel(cmCTest::CONTINUOUS);
  1535. this->SetTest("Test");
  1536. } else if (targ == "ContinuousMemCheck" || targ == "ContinuousPurify") {
  1537. this->SetTestModel(cmCTest::CONTINUOUS);
  1538. this->SetTest("MemCheck");
  1539. } else if (targ == "ContinuousCoverage") {
  1540. this->SetTestModel(cmCTest::CONTINUOUS);
  1541. this->SetTest("Coverage");
  1542. } else if (targ == "ContinuousSubmit") {
  1543. this->SetTestModel(cmCTest::CONTINUOUS);
  1544. this->SetTest("Submit");
  1545. } else if (targ == "Nightly") {
  1546. this->SetTestModel(cmCTest::NIGHTLY);
  1547. this->SetTest("Start");
  1548. this->SetTest("Update");
  1549. this->SetTest("Configure");
  1550. this->SetTest("Build");
  1551. this->SetTest("Test");
  1552. this->SetTest("Coverage");
  1553. this->SetTest("Submit");
  1554. } else if (targ == "NightlyStart") {
  1555. this->SetTestModel(cmCTest::NIGHTLY);
  1556. this->SetTest("Start");
  1557. } else if (targ == "NightlyUpdate") {
  1558. this->SetTestModel(cmCTest::NIGHTLY);
  1559. this->SetTest("Update");
  1560. } else if (targ == "NightlyConfigure") {
  1561. this->SetTestModel(cmCTest::NIGHTLY);
  1562. this->SetTest("Configure");
  1563. } else if (targ == "NightlyBuild") {
  1564. this->SetTestModel(cmCTest::NIGHTLY);
  1565. this->SetTest("Build");
  1566. } else if (targ == "NightlyTest") {
  1567. this->SetTestModel(cmCTest::NIGHTLY);
  1568. this->SetTest("Test");
  1569. } else if (targ == "NightlyMemCheck" || targ == "NightlyPurify") {
  1570. this->SetTestModel(cmCTest::NIGHTLY);
  1571. this->SetTest("MemCheck");
  1572. } else if (targ == "NightlyCoverage") {
  1573. this->SetTestModel(cmCTest::NIGHTLY);
  1574. this->SetTest("Coverage");
  1575. } else if (targ == "NightlySubmit") {
  1576. this->SetTestModel(cmCTest::NIGHTLY);
  1577. this->SetTest("Submit");
  1578. } else if (targ == "MemoryCheck") {
  1579. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1580. this->SetTest("Start");
  1581. this->SetTest("Configure");
  1582. this->SetTest("Build");
  1583. this->SetTest("MemCheck");
  1584. this->SetTest("Coverage");
  1585. this->SetTest("Submit");
  1586. } else if (targ == "NightlyMemoryCheck") {
  1587. this->SetTestModel(cmCTest::NIGHTLY);
  1588. this->SetTest("Start");
  1589. this->SetTest("Update");
  1590. this->SetTest("Configure");
  1591. this->SetTest("Build");
  1592. this->SetTest("MemCheck");
  1593. this->SetTest("Coverage");
  1594. this->SetTest("Submit");
  1595. } else {
  1596. return false;
  1597. }
  1598. return true;
  1599. }
  1600. void cmCTest::ErrorMessageUnknownDashDValue(std::string const& val)
  1601. {
  1602. cmCTestLog(this, ERROR_MESSAGE,
  1603. "CTest -D called with incorrect option: " << val << '\n');
  1604. cmCTestLog(this, ERROR_MESSAGE,
  1605. "Available options are:\n"
  1606. " ctest -D Continuous\n"
  1607. " ctest -D Continuous(Start|Update|Configure|Build)\n"
  1608. " ctest -D Continuous(Test|Coverage|MemCheck|Submit)\n"
  1609. " ctest -D Experimental\n"
  1610. " ctest -D Experimental(Start|Update|Configure|Build)\n"
  1611. " ctest -D Experimental(Test|Coverage|MemCheck|Submit)\n"
  1612. " ctest -D Nightly\n"
  1613. " ctest -D Nightly(Start|Update|Configure|Build)\n"
  1614. " ctest -D Nightly(Test|Coverage|MemCheck|Submit)\n"
  1615. " ctest -D NightlyMemoryCheck\n");
  1616. }
  1617. bool cmCTest::CheckArgument(const std::string& arg, cm::string_view varg1,
  1618. const char* varg2)
  1619. {
  1620. return (arg == varg1) || (varg2 && arg == varg2);
  1621. }
  1622. #if !defined(_WIN32)
  1623. bool cmCTest::ConsoleIsNotDumb()
  1624. {
  1625. std::string term_env_variable;
  1626. if (cmSystemTools::GetEnv("TERM", term_env_variable)) {
  1627. return isatty(1) && term_env_variable != "dumb";
  1628. }
  1629. return false;
  1630. }
  1631. #endif
  1632. bool cmCTest::ProgressOutputSupportedByConsole()
  1633. {
  1634. #if defined(_WIN32)
  1635. // On Windows we need a console buffer.
  1636. void* console = GetStdHandle(STD_OUTPUT_HANDLE);
  1637. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1638. return GetConsoleScreenBufferInfo(console, &csbi);
  1639. #else
  1640. // On UNIX we need a non-dumb tty.
  1641. return ConsoleIsNotDumb();
  1642. #endif
  1643. }
  1644. bool cmCTest::ColoredOutputSupportedByConsole()
  1645. {
  1646. std::string clicolor_force;
  1647. if (cmSystemTools::GetEnv("CLICOLOR_FORCE", clicolor_force) &&
  1648. !clicolor_force.empty() && clicolor_force != "0") {
  1649. return true;
  1650. }
  1651. std::string clicolor;
  1652. if (cmSystemTools::GetEnv("CLICOLOR", clicolor) && clicolor == "0") {
  1653. return false;
  1654. }
  1655. #if defined(_WIN32)
  1656. // Not supported on Windows
  1657. return false;
  1658. #else
  1659. // On UNIX we need a non-dumb tty.
  1660. return ConsoleIsNotDumb();
  1661. #endif
  1662. }
  1663. bool cmCTest::AddVariableDefinition(const std::string& arg)
  1664. {
  1665. std::string name;
  1666. std::string value;
  1667. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  1668. if (cmake::ParseCacheEntry(arg, name, value, type)) {
  1669. this->Impl->Definitions[name] = value;
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. void cmCTest::SetPersistentOptionIfNotEmpty(const std::string& value,
  1675. const std::string& optionName)
  1676. {
  1677. if (!value.empty()) {
  1678. this->GetTestHandler()->SetPersistentOption(optionName, value);
  1679. this->GetMemCheckHandler()->SetPersistentOption(optionName, value);
  1680. }
  1681. }
  1682. void cmCTest::AddPersistentMultiOptionIfNotEmpty(const std::string& value,
  1683. const std::string& optionName)
  1684. {
  1685. if (!value.empty()) {
  1686. this->GetTestHandler()->AddPersistentMultiOption(optionName, value);
  1687. this->GetMemCheckHandler()->AddPersistentMultiOption(optionName, value);
  1688. }
  1689. }
  1690. bool cmCTest::SetArgsFromPreset(const std::string& presetName,
  1691. bool listPresets)
  1692. {
  1693. const auto workingDirectory = cmSystemTools::GetCurrentWorkingDirectory();
  1694. cmCMakePresetsGraph settingsFile;
  1695. auto result = settingsFile.ReadProjectPresets(workingDirectory);
  1696. if (result != true) {
  1697. cmSystemTools::Error(cmStrCat("Could not read presets from ",
  1698. workingDirectory, ":",
  1699. settingsFile.parseState.GetErrorMessage()));
  1700. return false;
  1701. }
  1702. if (listPresets) {
  1703. settingsFile.PrintTestPresetList();
  1704. return true;
  1705. }
  1706. auto presetPair = settingsFile.TestPresets.find(presetName);
  1707. if (presetPair == settingsFile.TestPresets.end()) {
  1708. cmSystemTools::Error(cmStrCat("No such test preset in ", workingDirectory,
  1709. ": \"", presetName, '"'));
  1710. settingsFile.PrintTestPresetList();
  1711. return false;
  1712. }
  1713. if (presetPair->second.Unexpanded.Hidden) {
  1714. cmSystemTools::Error(cmStrCat("Cannot use hidden test preset in ",
  1715. workingDirectory, ": \"", presetName, '"'));
  1716. settingsFile.PrintTestPresetList();
  1717. return false;
  1718. }
  1719. auto const& expandedPreset = presetPair->second.Expanded;
  1720. if (!expandedPreset) {
  1721. cmSystemTools::Error(cmStrCat("Could not evaluate test preset \"",
  1722. presetName, "\": Invalid macro expansion"));
  1723. settingsFile.PrintTestPresetList();
  1724. return false;
  1725. }
  1726. if (!expandedPreset->ConditionResult) {
  1727. cmSystemTools::Error(cmStrCat("Cannot use disabled test preset in ",
  1728. workingDirectory, ": \"", presetName, '"'));
  1729. settingsFile.PrintTestPresetList();
  1730. return false;
  1731. }
  1732. auto configurePresetPair =
  1733. settingsFile.ConfigurePresets.find(expandedPreset->ConfigurePreset);
  1734. if (configurePresetPair == settingsFile.ConfigurePresets.end()) {
  1735. cmSystemTools::Error(cmStrCat("No such configure preset in ",
  1736. workingDirectory, ": \"",
  1737. expandedPreset->ConfigurePreset, '"'));
  1738. settingsFile.PrintConfigurePresetList();
  1739. return false;
  1740. }
  1741. if (configurePresetPair->second.Unexpanded.Hidden) {
  1742. cmSystemTools::Error(cmStrCat("Cannot use hidden configure preset in ",
  1743. workingDirectory, ": \"",
  1744. expandedPreset->ConfigurePreset, '"'));
  1745. settingsFile.PrintConfigurePresetList();
  1746. return false;
  1747. }
  1748. auto const& expandedConfigurePreset = configurePresetPair->second.Expanded;
  1749. if (!expandedConfigurePreset) {
  1750. cmSystemTools::Error(cmStrCat("Could not evaluate configure preset \"",
  1751. expandedPreset->ConfigurePreset,
  1752. "\": Invalid macro expansion"));
  1753. return false;
  1754. }
  1755. auto presetEnvironment = expandedPreset->Environment;
  1756. for (auto const& var : presetEnvironment) {
  1757. if (var.second) {
  1758. cmSystemTools::PutEnv(cmStrCat(var.first, '=', *var.second));
  1759. }
  1760. }
  1761. if (!expandedPreset->Configuration.empty()) {
  1762. this->SetConfigType(expandedPreset->Configuration);
  1763. }
  1764. // Set build directory to value specified by the configure preset.
  1765. this->AddCTestConfigurationOverwrite(
  1766. cmStrCat("BuildDirectory=", expandedConfigurePreset->BinaryDir));
  1767. for (const auto& kvp : expandedPreset->OverwriteConfigurationFile) {
  1768. this->AddCTestConfigurationOverwrite(kvp);
  1769. }
  1770. if (expandedPreset->Output) {
  1771. this->Impl->TestProgressOutput =
  1772. expandedPreset->Output->ShortProgress.value_or(false);
  1773. if (expandedPreset->Output->Verbosity) {
  1774. const auto& verbosity = *expandedPreset->Output->Verbosity;
  1775. switch (verbosity) {
  1776. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1777. Extra:
  1778. this->Impl->ExtraVerbose = true;
  1779. CM_FALLTHROUGH;
  1780. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1781. Verbose:
  1782. this->Impl->Verbose = true;
  1783. break;
  1784. case cmCMakePresetsGraph::TestPreset::OutputOptions::VerbosityEnum::
  1785. Default:
  1786. default:
  1787. // leave default settings
  1788. break;
  1789. }
  1790. }
  1791. this->Impl->Debug = expandedPreset->Output->Debug.value_or(false);
  1792. this->Impl->OutputTestOutputOnTestFailure =
  1793. expandedPreset->Output->OutputOnFailure.value_or(false);
  1794. this->Impl->Quiet = expandedPreset->Output->Quiet.value_or(false);
  1795. if (!expandedPreset->Output->OutputLogFile.empty()) {
  1796. this->SetOutputLogFileName(expandedPreset->Output->OutputLogFile);
  1797. }
  1798. if (!expandedPreset->Output->OutputJUnitFile.empty()) {
  1799. this->SetOutputJUnitFileName(expandedPreset->Output->OutputJUnitFile);
  1800. }
  1801. this->Impl->LabelSummary =
  1802. expandedPreset->Output->LabelSummary.value_or(true);
  1803. this->Impl->SubprojectSummary =
  1804. expandedPreset->Output->SubprojectSummary.value_or(true);
  1805. if (expandedPreset->Output->MaxPassedTestOutputSize) {
  1806. this->Impl->TestHandler.SetTestOutputSizePassed(
  1807. *expandedPreset->Output->MaxPassedTestOutputSize);
  1808. }
  1809. if (expandedPreset->Output->MaxFailedTestOutputSize) {
  1810. this->Impl->TestHandler.SetTestOutputSizeFailed(
  1811. *expandedPreset->Output->MaxFailedTestOutputSize);
  1812. }
  1813. if (expandedPreset->Output->TestOutputTruncation) {
  1814. this->Impl->TestHandler.TestOutputTruncation =
  1815. *expandedPreset->Output->TestOutputTruncation;
  1816. }
  1817. if (expandedPreset->Output->MaxTestNameWidth) {
  1818. this->Impl->MaxTestNameWidth = *expandedPreset->Output->MaxTestNameWidth;
  1819. }
  1820. }
  1821. if (expandedPreset->Filter) {
  1822. if (expandedPreset->Filter->Include) {
  1823. this->SetPersistentOptionIfNotEmpty(
  1824. expandedPreset->Filter->Include->Name, "IncludeRegularExpression");
  1825. this->AddPersistentMultiOptionIfNotEmpty(
  1826. expandedPreset->Filter->Include->Label, "LabelRegularExpression");
  1827. if (expandedPreset->Filter->Include->Index) {
  1828. if (expandedPreset->Filter->Include->Index->IndexFile.empty()) {
  1829. const auto& start = expandedPreset->Filter->Include->Index->Start;
  1830. const auto& end = expandedPreset->Filter->Include->Index->End;
  1831. const auto& stride = expandedPreset->Filter->Include->Index->Stride;
  1832. std::string indexOptions;
  1833. indexOptions += (start ? std::to_string(*start) : "") + ",";
  1834. indexOptions += (end ? std::to_string(*end) : "") + ",";
  1835. indexOptions += (stride ? std::to_string(*stride) : "") + ",";
  1836. indexOptions +=
  1837. cmJoin(expandedPreset->Filter->Include->Index->SpecificTests, ",");
  1838. this->SetPersistentOptionIfNotEmpty(indexOptions,
  1839. "TestsToRunInformation");
  1840. } else {
  1841. this->SetPersistentOptionIfNotEmpty(
  1842. expandedPreset->Filter->Include->Index->IndexFile,
  1843. "TestsToRunInformation");
  1844. }
  1845. }
  1846. if (expandedPreset->Filter->Include->UseUnion.value_or(false)) {
  1847. this->GetTestHandler()->SetPersistentOption("UseUnion", "true");
  1848. this->GetMemCheckHandler()->SetPersistentOption("UseUnion", "true");
  1849. }
  1850. }
  1851. if (expandedPreset->Filter->Exclude) {
  1852. this->SetPersistentOptionIfNotEmpty(
  1853. expandedPreset->Filter->Exclude->Name, "ExcludeRegularExpression");
  1854. this->AddPersistentMultiOptionIfNotEmpty(
  1855. expandedPreset->Filter->Exclude->Label,
  1856. "ExcludeLabelRegularExpression");
  1857. if (expandedPreset->Filter->Exclude->Fixtures) {
  1858. this->SetPersistentOptionIfNotEmpty(
  1859. expandedPreset->Filter->Exclude->Fixtures->Any,
  1860. "ExcludeFixtureRegularExpression");
  1861. this->SetPersistentOptionIfNotEmpty(
  1862. expandedPreset->Filter->Exclude->Fixtures->Setup,
  1863. "ExcludeFixtureSetupRegularExpression");
  1864. this->SetPersistentOptionIfNotEmpty(
  1865. expandedPreset->Filter->Exclude->Fixtures->Cleanup,
  1866. "ExcludeFixtureCleanupRegularExpression");
  1867. }
  1868. }
  1869. }
  1870. if (expandedPreset->Execution) {
  1871. this->Impl->StopOnFailure =
  1872. expandedPreset->Execution->StopOnFailure.value_or(false);
  1873. this->Impl->Failover =
  1874. expandedPreset->Execution->EnableFailover.value_or(false);
  1875. if (expandedPreset->Execution->Jobs) {
  1876. auto jobs = *expandedPreset->Execution->Jobs;
  1877. this->SetParallelLevel(jobs);
  1878. this->Impl->ParallelLevelSetInCli = true;
  1879. }
  1880. this->SetPersistentOptionIfNotEmpty(
  1881. expandedPreset->Execution->ResourceSpecFile, "ResourceSpecFile");
  1882. if (expandedPreset->Execution->TestLoad) {
  1883. auto testLoad = *expandedPreset->Execution->TestLoad;
  1884. this->SetTestLoad(testLoad);
  1885. }
  1886. if (expandedPreset->Execution->ShowOnly) {
  1887. this->Impl->ShowOnly = true;
  1888. switch (*expandedPreset->Execution->ShowOnly) {
  1889. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::ShowOnlyEnum::
  1890. JsonV1:
  1891. this->Impl->Quiet = true;
  1892. this->Impl->OutputAsJson = true;
  1893. this->Impl->OutputAsJsonVersion = 1;
  1894. break;
  1895. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::ShowOnlyEnum::
  1896. Human:
  1897. // intentional fallthrough (human is the default)
  1898. default:
  1899. break;
  1900. }
  1901. }
  1902. if (expandedPreset->Execution->Repeat) {
  1903. this->Impl->RepeatCount = expandedPreset->Execution->Repeat->Count;
  1904. switch (expandedPreset->Execution->Repeat->Mode) {
  1905. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1906. ModeEnum::UntilFail:
  1907. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  1908. break;
  1909. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1910. ModeEnum::UntilPass:
  1911. this->Impl->RepeatMode = cmCTest::Repeat::UntilPass;
  1912. break;
  1913. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::RepeatOptions::
  1914. ModeEnum::AfterTimeout:
  1915. this->Impl->RepeatMode = cmCTest::Repeat::AfterTimeout;
  1916. break;
  1917. default:
  1918. // should never default since mode is required
  1919. return false;
  1920. }
  1921. }
  1922. if (expandedPreset->Execution->InteractiveDebugging) {
  1923. this->Impl->InteractiveDebugMode =
  1924. *expandedPreset->Execution->InteractiveDebugging;
  1925. }
  1926. if (expandedPreset->Execution->ScheduleRandom.value_or(false)) {
  1927. this->Impl->ScheduleType = "Random";
  1928. }
  1929. if (expandedPreset->Execution->Timeout) {
  1930. this->Impl->GlobalTimeout =
  1931. cmDuration(*expandedPreset->Execution->Timeout);
  1932. }
  1933. if (expandedPreset->Execution->NoTestsAction) {
  1934. switch (*expandedPreset->Execution->NoTestsAction) {
  1935. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1936. NoTestsActionEnum::Error:
  1937. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  1938. break;
  1939. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1940. NoTestsActionEnum::Ignore:
  1941. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  1942. break;
  1943. case cmCMakePresetsGraph::TestPreset::ExecutionOptions::
  1944. NoTestsActionEnum::Default:
  1945. break;
  1946. default:
  1947. // should never default
  1948. return false;
  1949. }
  1950. }
  1951. }
  1952. return true;
  1953. }
  1954. // the main entry point of ctest, called from main
  1955. int cmCTest::Run(std::vector<std::string> const& args)
  1956. {
  1957. const char* ctestExec = "ctest";
  1958. bool cmakeAndTest = false;
  1959. bool executeTests = true;
  1960. bool SRArgumentSpecified = false;
  1961. // copy the command line
  1962. cm::append(this->Impl->InitialCommandLineArguments, args);
  1963. // check if a test preset was specified
  1964. bool listPresets =
  1965. find(args.begin(), args.end(), "--list-presets") != args.end();
  1966. auto it =
  1967. std::find_if(args.begin(), args.end(), [](std::string const& arg) -> bool {
  1968. return arg == "--preset" || cmHasLiteralPrefix(arg, "--preset=");
  1969. });
  1970. if (listPresets || it != args.end()) {
  1971. std::string errormsg;
  1972. bool success;
  1973. if (listPresets) {
  1974. // If listing presets we don't need a presetName
  1975. success = this->SetArgsFromPreset("", listPresets);
  1976. } else {
  1977. if (cmHasLiteralPrefix(*it, "--preset=")) {
  1978. auto const& presetName = it->substr(9);
  1979. success = this->SetArgsFromPreset(presetName, listPresets);
  1980. } else if (++it != args.end()) {
  1981. auto const& presetName = *it;
  1982. success = this->SetArgsFromPreset(presetName, listPresets);
  1983. } else {
  1984. cmSystemTools::Error("'--preset' requires an argument");
  1985. success = false;
  1986. }
  1987. }
  1988. if (listPresets) {
  1989. return success ? 0 : 1;
  1990. }
  1991. if (!success) {
  1992. return 1;
  1993. }
  1994. }
  1995. auto const dashD = [this, &executeTests](std::string const& targ) -> bool {
  1996. this->Impl->ProduceXML = true;
  1997. // AddTestsForDashboard parses the dashboard type and converts it
  1998. // into the separate stages
  1999. if (this->AddTestsForDashboardType(targ)) {
  2000. return true;
  2001. }
  2002. if (this->AddVariableDefinition(targ)) {
  2003. return true;
  2004. }
  2005. this->ErrorMessageUnknownDashDValue(targ);
  2006. executeTests = false;
  2007. return false;
  2008. };
  2009. auto const dashT = [this, &executeTests,
  2010. ctestExec](std::string const& action) -> bool {
  2011. this->Impl->ProduceXML = true;
  2012. if (!this->SetTest(action, false)) {
  2013. executeTests = false;
  2014. cmCTestLog(this, ERROR_MESSAGE,
  2015. "CTest -T called with incorrect option: " << action << '\n');
  2016. /* clang-format off */
  2017. cmCTestLog(this, ERROR_MESSAGE,
  2018. "Available options are:\n"
  2019. " " << ctestExec << " -T all\n"
  2020. " " << ctestExec << " -T start\n"
  2021. " " << ctestExec << " -T update\n"
  2022. " " << ctestExec << " -T configure\n"
  2023. " " << ctestExec << " -T build\n"
  2024. " " << ctestExec << " -T test\n"
  2025. " " << ctestExec << " -T coverage\n"
  2026. " " << ctestExec << " -T memcheck\n"
  2027. " " << ctestExec << " -T notes\n"
  2028. " " << ctestExec << " -T submit\n");
  2029. /* clang-format on */
  2030. return false;
  2031. }
  2032. return true;
  2033. };
  2034. auto const dashM = [this, &executeTests,
  2035. ctestExec](std::string const& model) -> bool {
  2036. if (cmSystemTools::LowerCase(model) == "nightly"_s) {
  2037. this->SetTestModel(cmCTest::NIGHTLY);
  2038. } else if (cmSystemTools::LowerCase(model) == "continuous"_s) {
  2039. this->SetTestModel(cmCTest::CONTINUOUS);
  2040. } else if (cmSystemTools::LowerCase(model) == "experimental"_s) {
  2041. this->SetTestModel(cmCTest::EXPERIMENTAL);
  2042. } else {
  2043. executeTests = false;
  2044. cmCTestLog(this, ERROR_MESSAGE,
  2045. "CTest -M called with incorrect option: " << model << '\n');
  2046. /* clang-format off */
  2047. cmCTestLog(this, ERROR_MESSAGE,
  2048. "Available options are:\n"
  2049. " " << ctestExec << " -M Continuous\n"
  2050. " " << ctestExec << " -M Experimental\n"
  2051. " " << ctestExec << " -M Nightly\n");
  2052. /* clang-format on */
  2053. return false;
  2054. }
  2055. return true;
  2056. };
  2057. auto const dashSP =
  2058. [this, &SRArgumentSpecified](std::string const& script) -> bool {
  2059. this->Impl->RunConfigurationScript = true;
  2060. cmCTestScriptHandler* ch = this->GetScriptHandler();
  2061. // -SR is an internal argument, -SP should be ignored when it is passed
  2062. if (!SRArgumentSpecified) {
  2063. ch->AddConfigurationScript(script, false);
  2064. }
  2065. return true;
  2066. };
  2067. auto const dashSR =
  2068. [this, &SRArgumentSpecified](std::string const& script) -> bool {
  2069. SRArgumentSpecified = true;
  2070. this->Impl->RunConfigurationScript = true;
  2071. cmCTestScriptHandler* ch = this->GetScriptHandler();
  2072. ch->AddConfigurationScript(script, true);
  2073. return true;
  2074. };
  2075. auto const dash_S =
  2076. [this, &SRArgumentSpecified](std::string const& script) -> bool {
  2077. this->Impl->RunConfigurationScript = true;
  2078. cmCTestScriptHandler* ch = this->GetScriptHandler();
  2079. // -SR is an internal argument, -S should be ignored when it is passed
  2080. if (!SRArgumentSpecified) {
  2081. ch->AddConfigurationScript(script, true);
  2082. }
  2083. return true;
  2084. };
  2085. auto const dashJ = [this](cm::string_view arg,
  2086. std::string const& j) -> bool {
  2087. cm::optional<size_t> parallelLevel;
  2088. // No value or an empty value tells ctest to choose a default.
  2089. if (!j.empty()) {
  2090. // A non-empty value must be a non-negative integer.
  2091. unsigned long plevel = 0;
  2092. if (!cmStrToULong(j, &plevel)) {
  2093. cmSystemTools::Error(
  2094. cmStrCat('\'', arg, "' given invalid value '", j, '\''));
  2095. return false;
  2096. }
  2097. parallelLevel = plevel;
  2098. }
  2099. this->SetParallelLevel(parallelLevel);
  2100. this->Impl->ParallelLevelSetInCli = true;
  2101. return true;
  2102. };
  2103. auto const dashC = [this](std::string const& config) -> bool {
  2104. this->SetConfigType(config);
  2105. return true;
  2106. };
  2107. auto const dashGroup = [this](std::string const& group) -> bool {
  2108. this->Impl->SpecificGroup = group;
  2109. return true;
  2110. };
  2111. auto const dashQ = [this](std::string const&) -> bool {
  2112. this->Impl->Quiet = true;
  2113. return true;
  2114. };
  2115. auto const dashV = [this](std::string const&) -> bool {
  2116. this->Impl->Verbose = true;
  2117. return true;
  2118. };
  2119. auto const dashVV = [this](std::string const&) -> bool {
  2120. this->Impl->ExtraVerbose = true;
  2121. this->Impl->Verbose = true;
  2122. return true;
  2123. };
  2124. auto const dashO = [this](std::string const& log) -> bool {
  2125. this->SetOutputLogFileName(log);
  2126. return true;
  2127. };
  2128. auto const dashW = [this](std::string const& width) -> bool {
  2129. this->Impl->MaxTestNameWidth = atoi(width.c_str());
  2130. return true;
  2131. };
  2132. auto const dashA = [this](std::string const& notes) -> bool {
  2133. this->Impl->ProduceXML = true;
  2134. this->SetTest("Notes");
  2135. this->SetNotesFiles(notes);
  2136. return true;
  2137. };
  2138. auto const dashI = [this](std::string const& tests) -> bool {
  2139. this->Impl->TestHandler.SetPersistentOption("TestsToRunInformation",
  2140. tests);
  2141. this->Impl->MemCheckHandler.SetPersistentOption("TestsToRunInformation",
  2142. tests);
  2143. return true;
  2144. };
  2145. auto const dashU = [this](std::string const&) -> bool {
  2146. this->Impl->TestHandler.SetPersistentOption("UseUnion", "true");
  2147. this->Impl->MemCheckHandler.SetPersistentOption("UseUnion", "true");
  2148. return true;
  2149. };
  2150. auto const dashR = [this](std::string const& expr) -> bool {
  2151. this->Impl->TestHandler.SetPersistentOption("IncludeRegularExpression",
  2152. expr);
  2153. this->Impl->MemCheckHandler.SetPersistentOption("IncludeRegularExpression",
  2154. expr);
  2155. return true;
  2156. };
  2157. auto const dashE = [this](std::string const& expr) -> bool {
  2158. this->Impl->TestHandler.SetPersistentOption("ExcludeRegularExpression",
  2159. expr);
  2160. this->Impl->MemCheckHandler.SetPersistentOption("ExcludeRegularExpression",
  2161. expr);
  2162. return true;
  2163. };
  2164. auto const dashL = [this](std::string const& expr) -> bool {
  2165. this->Impl->TestHandler.AddPersistentMultiOption("LabelRegularExpression",
  2166. expr);
  2167. this->Impl->MemCheckHandler.AddPersistentMultiOption(
  2168. "LabelRegularExpression", expr);
  2169. return true;
  2170. };
  2171. auto const dashLE = [this](std::string const& expr) -> bool {
  2172. this->Impl->TestHandler.AddPersistentMultiOption(
  2173. "ExcludeLabelRegularExpression", expr);
  2174. this->Impl->MemCheckHandler.AddPersistentMultiOption(
  2175. "ExcludeLabelRegularExpression", expr);
  2176. return true;
  2177. };
  2178. auto const dashFA = [this](std::string const& expr) -> bool {
  2179. this->Impl->TestHandler.SetPersistentOption(
  2180. "ExcludeFixtureRegularExpression", expr);
  2181. this->Impl->MemCheckHandler.SetPersistentOption(
  2182. "ExcludeFixtureRegularExpression", expr);
  2183. return true;
  2184. };
  2185. auto const dashFS = [this](std::string const& expr) -> bool {
  2186. this->Impl->TestHandler.SetPersistentOption(
  2187. "ExcludeFixtureSetupRegularExpression", expr);
  2188. this->Impl->MemCheckHandler.SetPersistentOption(
  2189. "ExcludeFixtureSetupRegularExpression", expr);
  2190. return true;
  2191. };
  2192. auto const dashFC = [this](std::string const& expr) -> bool {
  2193. this->Impl->TestHandler.SetPersistentOption(
  2194. "ExcludeFixtureCleanupRegularExpression", expr);
  2195. this->Impl->MemCheckHandler.SetPersistentOption(
  2196. "ExcludeFixtureCleanupRegularExpression", expr);
  2197. return true;
  2198. };
  2199. using CommandArgument =
  2200. cmCommandLineArgument<bool(std::string const& value)>;
  2201. auto const arguments = std::vector<CommandArgument>{
  2202. CommandArgument{ "--dashboard", CommandArgument::Values::One, dashD },
  2203. CommandArgument{ "-D",
  2204. "-D must be followed by dashboard mode or VAR=VALUE.",
  2205. CommandArgument::Values::One, dashD },
  2206. CommandArgument{
  2207. "-D", "-D must be followed by dashboard mode or VAR=VALUE.",
  2208. CommandArgument::Values::One, CommandArgument::RequiresSeparator::No,
  2209. [this](std::string const& def) -> bool {
  2210. // Unsuccessful parsing of VAR=VALUE has historically
  2211. // been ignored.
  2212. this->AddVariableDefinition(def);
  2213. return true;
  2214. } },
  2215. CommandArgument{ "-T", CommandArgument::Values::One, dashT },
  2216. CommandArgument{ "--test-action", CommandArgument::Values::One, dashT },
  2217. CommandArgument{ "-M", CommandArgument::Values::One, dashM },
  2218. CommandArgument{ "--test-model", CommandArgument::Values::One, dashM },
  2219. CommandArgument{ "--extra-submit", CommandArgument::Values::One,
  2220. [this](std::string const& extra) -> bool {
  2221. this->Impl->ProduceXML = true;
  2222. this->SetTest("Submit");
  2223. return this->SubmitExtraFiles(extra);
  2224. } },
  2225. CommandArgument{
  2226. "--build-and-test", "--build-and-test must have source and binary dir",
  2227. CommandArgument::Values::Two,
  2228. [this, &cmakeAndTest](std::string const& dirs) -> bool {
  2229. cmakeAndTest = true;
  2230. cmList dirList{ dirs };
  2231. if (dirList.size() != 2) {
  2232. return false;
  2233. }
  2234. this->Impl->BuildAndTest.SourceDir =
  2235. cmSystemTools::CollapseFullPath(dirList[0]);
  2236. this->Impl->BuildAndTest.BinaryDir =
  2237. cmSystemTools::CollapseFullPath(dirList[1]);
  2238. cmSystemTools::MakeDirectory(this->Impl->BuildAndTest.BinaryDir);
  2239. return true;
  2240. } },
  2241. CommandArgument{ "--build-target", CommandArgument::Values::One,
  2242. [this](std::string const& t) -> bool {
  2243. this->Impl->BuildAndTest.BuildTargets.emplace_back(t);
  2244. return true;
  2245. } },
  2246. CommandArgument{ "--build-noclean", CommandArgument::Values::Zero,
  2247. [this](std::string const&) -> bool {
  2248. this->Impl->BuildAndTest.BuildNoClean = true;
  2249. return true;
  2250. } },
  2251. CommandArgument{ "--build-nocmake", CommandArgument::Values::Zero,
  2252. [this](std::string const&) -> bool {
  2253. this->Impl->BuildAndTest.BuildNoCMake = true;
  2254. return true;
  2255. } },
  2256. CommandArgument{ "--build-two-config", CommandArgument::Values::Zero,
  2257. [this](std::string const&) -> bool {
  2258. this->Impl->BuildAndTest.BuildTwoConfig = true;
  2259. return true;
  2260. } },
  2261. CommandArgument{ "--build-run-dir", CommandArgument::Values::One,
  2262. [this](std::string const& dir) -> bool {
  2263. this->Impl->BuildAndTest.BuildRunDir = dir;
  2264. return true;
  2265. } },
  2266. CommandArgument{ "--build-exe-dir", CommandArgument::Values::One,
  2267. [this](std::string const& dir) -> bool {
  2268. this->Impl->BuildAndTest.ExecutableDirectory = dir;
  2269. return true;
  2270. } },
  2271. CommandArgument{ "--test-timeout", CommandArgument::Values::One,
  2272. [this](std::string const& t) -> bool {
  2273. this->Impl->BuildAndTest.Timeout =
  2274. cmDuration(atof(t.c_str()));
  2275. return true;
  2276. } },
  2277. CommandArgument{ "--build-generator", CommandArgument::Values::One,
  2278. [this](std::string const& g) -> bool {
  2279. this->Impl->BuildAndTest.BuildGenerator = g;
  2280. return true;
  2281. } },
  2282. CommandArgument{ "--build-generator-platform",
  2283. CommandArgument::Values::One,
  2284. [this](std::string const& p) -> bool {
  2285. this->Impl->BuildAndTest.BuildGeneratorPlatform = p;
  2286. return true;
  2287. } },
  2288. CommandArgument{ "--build-generator-toolset", CommandArgument::Values::One,
  2289. [this](std::string const& t) -> bool {
  2290. this->Impl->BuildAndTest.BuildGeneratorToolset = t;
  2291. return true;
  2292. } },
  2293. CommandArgument{ "--build-project", CommandArgument::Values::One,
  2294. [this](std::string const& p) -> bool {
  2295. this->Impl->BuildAndTest.BuildProject = p;
  2296. return true;
  2297. } },
  2298. CommandArgument{ "--build-makeprogram", CommandArgument::Values::One,
  2299. [this](std::string const& p) -> bool {
  2300. this->Impl->BuildAndTest.BuildMakeProgram = p;
  2301. return true;
  2302. } },
  2303. CommandArgument{ "--build-config-sample", CommandArgument::Values::One,
  2304. [this](std::string const& s) -> bool {
  2305. this->Impl->BuildAndTest.ConfigSample = s;
  2306. return true;
  2307. } },
  2308. CommandArgument{ "-SP", CommandArgument::Values::One, dashSP },
  2309. CommandArgument{ "--script-new-process", CommandArgument::Values::One,
  2310. dashSP },
  2311. CommandArgument{ "-SR", CommandArgument::Values::One, dashSR },
  2312. CommandArgument{ "--script-run", CommandArgument::Values::One, dashSR },
  2313. CommandArgument{ "-S", CommandArgument::Values::One, dash_S },
  2314. CommandArgument{ "--script", CommandArgument::Values::One, dash_S },
  2315. CommandArgument{ "-F", CommandArgument::Values::Zero,
  2316. [this](std::string const&) -> bool {
  2317. this->Impl->Failover = true;
  2318. return true;
  2319. } },
  2320. CommandArgument{
  2321. "-j", CommandArgument::Values::ZeroOrOne,
  2322. [&dashJ](std::string const& j) -> bool { return dashJ("-j"_s, j); } },
  2323. CommandArgument{ "--parallel", CommandArgument::Values::ZeroOrOne,
  2324. [&dashJ](std::string const& j) -> bool {
  2325. return dashJ("--parallel"_s, j);
  2326. } },
  2327. CommandArgument{ "-j", CommandArgument::Values::One,
  2328. CommandArgument::RequiresSeparator::No,
  2329. [this](std::string const& j) -> bool {
  2330. // The value must be a non-negative integer.
  2331. unsigned long plevel = 0;
  2332. if (!cmStrToULong(j, &plevel)) {
  2333. cmSystemTools::Error(
  2334. cmStrCat("'-j' given invalid value '", j, '\''));
  2335. return false;
  2336. }
  2337. this->SetParallelLevel(plevel);
  2338. this->Impl->ParallelLevelSetInCli = true;
  2339. return true;
  2340. } },
  2341. CommandArgument{
  2342. "--repeat-until-fail", "'--repeat-until-fail' requires an argument",
  2343. CommandArgument::Values::One,
  2344. [this](std::string const& r) -> bool {
  2345. if (this->Impl->RepeatMode != cmCTest::Repeat::Never) {
  2346. cmSystemTools::Error("At most one '--repeat' option may be used.");
  2347. return false;
  2348. }
  2349. long repeat = 1;
  2350. if (!cmStrToLong(r, &repeat)) {
  2351. cmSystemTools::Error(cmStrCat(
  2352. "'--repeat-until-fail' given non-integer value '", r, '\''));
  2353. return false;
  2354. }
  2355. this->Impl->RepeatCount = static_cast<int>(repeat);
  2356. if (repeat > 1) {
  2357. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  2358. }
  2359. return true;
  2360. } },
  2361. CommandArgument{
  2362. "--repeat", CommandArgument::Values::One,
  2363. [this](std::string const& r) -> bool {
  2364. if (this->Impl->RepeatMode != cmCTest::Repeat::Never) {
  2365. cmSystemTools::Error("At most one '--repeat' option may be used.");
  2366. return false;
  2367. }
  2368. cmsys::RegularExpression repeatRegex(
  2369. "^(until-fail|until-pass|after-timeout):([0-9]+)$");
  2370. if (repeatRegex.find(r)) {
  2371. std::string const& count = repeatRegex.match(2);
  2372. unsigned long n = 1;
  2373. cmStrToULong(count, &n); // regex guarantees success
  2374. this->Impl->RepeatCount = static_cast<int>(n);
  2375. if (this->Impl->RepeatCount > 1) {
  2376. std::string const& mode = repeatRegex.match(1);
  2377. if (mode == "until-fail") {
  2378. this->Impl->RepeatMode = cmCTest::Repeat::UntilFail;
  2379. } else if (mode == "until-pass") {
  2380. this->Impl->RepeatMode = cmCTest::Repeat::UntilPass;
  2381. } else if (mode == "after-timeout") {
  2382. this->Impl->RepeatMode = cmCTest::Repeat::AfterTimeout;
  2383. }
  2384. }
  2385. } else {
  2386. cmSystemTools::Error(
  2387. cmStrCat("'--repeat' given invalid value '", r, '\''));
  2388. return false;
  2389. }
  2390. return true;
  2391. } },
  2392. CommandArgument{ "--test-load", CommandArgument::Values::One,
  2393. [this](std::string const& l) -> bool {
  2394. unsigned long load;
  2395. if (cmStrToULong(l, &load)) {
  2396. this->SetTestLoad(load);
  2397. } else {
  2398. cmCTestLog(
  2399. this, WARNING,
  2400. "Invalid value for 'Test Load' : " << l << '\n');
  2401. }
  2402. return true;
  2403. } },
  2404. CommandArgument{ "--no-compress-output", CommandArgument::Values::Zero,
  2405. [this](std::string const&) -> bool {
  2406. this->Impl->CompressTestOutput = false;
  2407. return true;
  2408. } },
  2409. CommandArgument{ "--print-labels", CommandArgument::Values::Zero,
  2410. [this](std::string const&) -> bool {
  2411. this->Impl->PrintLabels = true;
  2412. return true;
  2413. } },
  2414. CommandArgument{ "--http1.0", CommandArgument::Values::Zero,
  2415. [this](std::string const&) -> bool {
  2416. this->Impl->UseHTTP10 = true;
  2417. return true;
  2418. } },
  2419. CommandArgument{ "--timeout", CommandArgument::Values::One,
  2420. [this](std::string const& t) -> bool {
  2421. auto timeout = cmDuration(atof(t.c_str()));
  2422. this->Impl->GlobalTimeout = timeout;
  2423. return true;
  2424. } },
  2425. CommandArgument{ "--stop-time", CommandArgument::Values::One,
  2426. [this](std::string const& t) -> bool {
  2427. this->SetStopTime(t);
  2428. return true;
  2429. } },
  2430. CommandArgument{ "--stop-on-failure", CommandArgument::Values::Zero,
  2431. [this](std::string const&) -> bool {
  2432. this->Impl->StopOnFailure = true;
  2433. return true;
  2434. } },
  2435. CommandArgument{ "-C", CommandArgument::Values::One, dashC },
  2436. CommandArgument{ "--build-config", CommandArgument::Values::One, dashC },
  2437. CommandArgument{ "--debug", CommandArgument::Values::Zero,
  2438. [this](std::string const&) -> bool {
  2439. this->Impl->Debug = true;
  2440. return true;
  2441. } },
  2442. CommandArgument{ "--group", CommandArgument::Values::One, dashGroup },
  2443. // This is an undocumented / deprecated option.
  2444. // "Track" has been renamed to "Group".
  2445. CommandArgument{ "--track", CommandArgument::Values::One, dashGroup },
  2446. CommandArgument{ "--show-line-numbers", CommandArgument::Values::Zero,
  2447. [](std::string const&) -> bool {
  2448. // Silently ignore this never-documented and now-removed
  2449. // option.
  2450. return true;
  2451. } },
  2452. CommandArgument{ "--no-label-summary", CommandArgument::Values::Zero,
  2453. [this](std::string const&) -> bool {
  2454. this->Impl->LabelSummary = false;
  2455. return true;
  2456. } },
  2457. CommandArgument{ "--no-subproject-summary", CommandArgument::Values::Zero,
  2458. [this](std::string const&) -> bool {
  2459. this->Impl->SubprojectSummary = false;
  2460. return true;
  2461. } },
  2462. CommandArgument{ "--progress", CommandArgument::Values::Zero,
  2463. [this](std::string const&) -> bool {
  2464. this->Impl->TestProgressOutput = true;
  2465. return true;
  2466. } },
  2467. CommandArgument{ "-Q", CommandArgument::Values::Zero, dashQ },
  2468. CommandArgument{ "--quiet", CommandArgument::Values::Zero, dashQ },
  2469. CommandArgument{ "-V", CommandArgument::Values::Zero, dashV },
  2470. CommandArgument{ "--verbose", CommandArgument::Values::Zero, dashV },
  2471. CommandArgument{ "-VV", CommandArgument::Values::Zero, dashVV },
  2472. CommandArgument{ "--extra-verbose", CommandArgument::Values::Zero,
  2473. dashVV },
  2474. CommandArgument{ "--output-on-failure", CommandArgument::Values::Zero,
  2475. [this](std::string const&) -> bool {
  2476. this->Impl->OutputTestOutputOnTestFailure = true;
  2477. return true;
  2478. } },
  2479. CommandArgument{ "--test-output-size-passed", CommandArgument::Values::One,
  2480. [this](std::string const& sz) -> bool {
  2481. long outputSize;
  2482. if (cmStrToLong(sz, &outputSize)) {
  2483. this->Impl->TestHandler.SetTestOutputSizePassed(
  2484. static_cast<int>(outputSize));
  2485. } else {
  2486. cmCTestLog(
  2487. this, WARNING,
  2488. "Invalid value for '--test-output-size-passed': "
  2489. << sz << "\n");
  2490. }
  2491. return true;
  2492. } },
  2493. CommandArgument{ "--test-output-size-failed", CommandArgument::Values::One,
  2494. [this](std::string const& sz) -> bool {
  2495. long outputSize;
  2496. if (cmStrToLong(sz, &outputSize)) {
  2497. this->Impl->TestHandler.SetTestOutputSizeFailed(
  2498. static_cast<int>(outputSize));
  2499. } else {
  2500. cmCTestLog(
  2501. this, WARNING,
  2502. "Invalid value for '--test-output-size-failed': "
  2503. << sz << "\n");
  2504. }
  2505. return true;
  2506. } },
  2507. CommandArgument{
  2508. "--test-output-truncation", CommandArgument::Values::One,
  2509. [this](std::string const& mode) -> bool {
  2510. if (!this->Impl->TestHandler.SetTestOutputTruncation(mode)) {
  2511. cmSystemTools::Error(
  2512. cmStrCat("Invalid value for '--test-output-truncation': ", mode));
  2513. return false;
  2514. }
  2515. return true;
  2516. } },
  2517. CommandArgument{ "--show-only", CommandArgument::Values::ZeroOrOne,
  2518. [this](std::string const& format) -> bool {
  2519. this->Impl->ShowOnly = true;
  2520. // Check if a specific format is requested.
  2521. // Defaults to human readable text.
  2522. if (format == "json-v1") {
  2523. // Force quiet mode so the only output
  2524. // is the json object model.
  2525. this->Impl->Quiet = true;
  2526. this->Impl->OutputAsJson = true;
  2527. this->Impl->OutputAsJsonVersion = 1;
  2528. } else if (format == "human") {
  2529. } else if (!format.empty()) {
  2530. cmSystemTools::Error(
  2531. cmStrCat("'--show-only=' given unknown value '",
  2532. format, '\''));
  2533. return false;
  2534. }
  2535. return true;
  2536. } },
  2537. CommandArgument{ "-N", CommandArgument::Values::Zero,
  2538. [this](std::string const&) -> bool {
  2539. this->Impl->ShowOnly = true;
  2540. return true;
  2541. } },
  2542. CommandArgument{ "-O", CommandArgument::Values::One, dashO },
  2543. CommandArgument{ "--output-log", CommandArgument::Values::One, dashO },
  2544. CommandArgument{ "--tomorrow-tag", CommandArgument::Values::Zero,
  2545. [this](std::string const&) -> bool {
  2546. this->Impl->TomorrowTag = true;
  2547. return true;
  2548. } },
  2549. CommandArgument{ "--force-new-ctest-process",
  2550. CommandArgument::Values::Zero,
  2551. [](std::string const&) -> bool {
  2552. // Silently ignore now-removed option.
  2553. return true;
  2554. } },
  2555. CommandArgument{ "-W", CommandArgument::Values::One, dashW },
  2556. CommandArgument{ "--max-width", CommandArgument::Values::One, dashW },
  2557. CommandArgument{ "--interactive-debug-mode", CommandArgument::Values::One,
  2558. [this](std::string const& idm) -> bool {
  2559. this->Impl->InteractiveDebugMode = cmIsOn(idm);
  2560. return true;
  2561. } },
  2562. CommandArgument{ "--http-header", CommandArgument::Values::One,
  2563. [this](std::string const& h) -> bool {
  2564. this->Impl->SubmitHandler.AddCommandLineHttpHeader(h);
  2565. return true;
  2566. } },
  2567. CommandArgument{ "--submit-index", CommandArgument::Values::One,
  2568. [this](std::string const& index) -> bool {
  2569. this->Impl->SubmitIndex = atoi(index.c_str());
  2570. if (this->Impl->SubmitIndex < 0) {
  2571. this->Impl->SubmitIndex = 0;
  2572. }
  2573. return true;
  2574. } },
  2575. CommandArgument{ "--overwrite", CommandArgument::Values::One,
  2576. [this](std::string const& opt) -> bool {
  2577. this->AddCTestConfigurationOverwrite(opt);
  2578. return true;
  2579. } },
  2580. CommandArgument{ "-A", CommandArgument::Values::One, dashA },
  2581. CommandArgument{ "--add-notes", CommandArgument::Values::One, dashA },
  2582. CommandArgument{ "--test-dir", "'--test-dir' requires an argument",
  2583. CommandArgument::Values::One,
  2584. [this](std::string const& dir) -> bool {
  2585. this->Impl->TestDir = dir;
  2586. return true;
  2587. } },
  2588. CommandArgument{ "--output-junit", CommandArgument::Values::One,
  2589. [this](std::string const& file) -> bool {
  2590. this->SetOutputJUnitFileName(file);
  2591. return true;
  2592. } },
  2593. CommandArgument{ "--no-tests", CommandArgument::Values::One,
  2594. [this](std::string const& action) -> bool {
  2595. if (action == "error"_s) {
  2596. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  2597. } else if (action == "ignore"_s) {
  2598. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  2599. } else {
  2600. cmSystemTools::Error(
  2601. cmStrCat("'--no-tests=' given unknown value '",
  2602. action, '\''));
  2603. return false;
  2604. }
  2605. this->Impl->NoTestsModeSetInCli = true;
  2606. return true;
  2607. } },
  2608. CommandArgument{ "-I", CommandArgument::Values::One, dashI },
  2609. CommandArgument{ "--tests-information", CommandArgument::Values::One,
  2610. dashI },
  2611. CommandArgument{ "-U", CommandArgument::Values::One, dashU },
  2612. CommandArgument{ "--union", CommandArgument::Values::One, dashU },
  2613. CommandArgument{ "-R", CommandArgument::Values::One, dashR },
  2614. CommandArgument{ "--tests-regex", CommandArgument::Values::One, dashR },
  2615. CommandArgument{ "-E", CommandArgument::Values::One, dashE },
  2616. CommandArgument{ "--exclude-regex", CommandArgument::Values::One, dashE },
  2617. CommandArgument{ "-L", CommandArgument::Values::One, dashL },
  2618. CommandArgument{ "--label-regex", CommandArgument::Values::One, dashL },
  2619. CommandArgument{ "-LE", CommandArgument::Values::One, dashLE },
  2620. CommandArgument{ "--label-exclude", CommandArgument::Values::One, dashLE },
  2621. CommandArgument{ "-FA", CommandArgument::Values::One, dashFA },
  2622. CommandArgument{ "--fixture-exclude-any", CommandArgument::Values::One,
  2623. dashFA },
  2624. CommandArgument{ "-FS", CommandArgument::Values::One, dashFS },
  2625. CommandArgument{ "--fixture-exclude-setup", CommandArgument::Values::One,
  2626. dashFS },
  2627. CommandArgument{ "-FC", CommandArgument::Values::One, dashFC },
  2628. CommandArgument{ "--fixture-exclude-cleanup", CommandArgument::Values::One,
  2629. dashFC },
  2630. CommandArgument{ "--resource-spec-file", CommandArgument::Values::One,
  2631. [this](std::string const& file) -> bool {
  2632. this->Impl->TestHandler.SetPersistentOption(
  2633. "ResourceSpecFile", file);
  2634. this->Impl->MemCheckHandler.SetPersistentOption(
  2635. "ResourceSpecFile", file);
  2636. return true;
  2637. } },
  2638. CommandArgument{
  2639. "--tests-from-file", CommandArgument::Values::One,
  2640. [this](std::string const& file) -> bool {
  2641. this->Impl->TestHandler.SetPersistentOption("TestListFile", file);
  2642. this->Impl->MemCheckHandler.SetPersistentOption("TestListFile", file);
  2643. return true;
  2644. } },
  2645. CommandArgument{ "--exclude-from-file", CommandArgument::Values::One,
  2646. [this](std::string const& file) -> bool {
  2647. this->Impl->TestHandler.SetPersistentOption(
  2648. "ExcludeTestListFile", file);
  2649. this->Impl->MemCheckHandler.SetPersistentOption(
  2650. "ExcludeTestListFile", file);
  2651. return true;
  2652. } },
  2653. CommandArgument{ "--schedule-random", CommandArgument::Values::Zero,
  2654. [this](std::string const&) -> bool {
  2655. this->Impl->ScheduleType = "Random";
  2656. return true;
  2657. } },
  2658. CommandArgument{
  2659. "--rerun-failed", CommandArgument::Values::Zero,
  2660. [this](std::string const&) -> bool {
  2661. this->Impl->TestHandler.SetPersistentOption("RerunFailed", "true");
  2662. this->Impl->MemCheckHandler.SetPersistentOption("RerunFailed", "true");
  2663. return true;
  2664. } },
  2665. };
  2666. // process the command line arguments
  2667. for (size_t i = 1; i < args.size(); ++i) {
  2668. std::string const& arg = args[i];
  2669. bool matched = false;
  2670. for (auto const& m : arguments) {
  2671. if (m.matches(arg)) {
  2672. matched = true;
  2673. if (!m.parse(arg, i, args)) {
  2674. return 1;
  2675. }
  2676. break;
  2677. }
  2678. }
  2679. if (!matched && arg == "--build-options"_s) {
  2680. matched = true;
  2681. while (i + 1 < args.size() && args[i + 1] != "--build-target"_s &&
  2682. args[i + 1] != "--test-command"_s) {
  2683. ++i;
  2684. this->Impl->BuildAndTest.BuildOptions.emplace_back(args[i]);
  2685. }
  2686. }
  2687. if (!matched && arg == "--test-command"_s && i + 1 < args.size()) {
  2688. matched = true;
  2689. ++i;
  2690. this->Impl->BuildAndTest.TestCommand = args[i];
  2691. while (i + 1 < args.size()) {
  2692. ++i;
  2693. this->Impl->BuildAndTest.TestCommandArgs.emplace_back(args[i]);
  2694. }
  2695. }
  2696. if (!matched && cmHasLiteralPrefix(arg, "-") &&
  2697. !cmHasLiteralPrefix(arg, "--preset")) {
  2698. cmSystemTools::Error(cmStrCat("Unknown argument: ", arg));
  2699. cmSystemTools::Error("Run 'ctest --help' for all supported options.");
  2700. return 1;
  2701. }
  2702. }
  2703. // handle CTEST_PARALLEL_LEVEL environment variable
  2704. if (!this->Impl->ParallelLevelSetInCli) {
  2705. if (cm::optional<std::string> parallelEnv =
  2706. cmSystemTools::GetEnvVar("CTEST_PARALLEL_LEVEL")) {
  2707. if (parallelEnv->empty() ||
  2708. parallelEnv->find_first_not_of(" \t") == std::string::npos) {
  2709. // An empty value tells ctest to choose a default.
  2710. this->SetParallelLevel(cm::nullopt);
  2711. } else {
  2712. // A non-empty value must be a non-negative integer.
  2713. // Otherwise, ignore it.
  2714. unsigned long plevel = 0;
  2715. if (cmStrToULong(*parallelEnv, &plevel)) {
  2716. this->SetParallelLevel(plevel);
  2717. }
  2718. }
  2719. }
  2720. }
  2721. // handle CTEST_NO_TESTS_ACTION environment variable
  2722. if (!this->Impl->NoTestsModeSetInCli) {
  2723. std::string action;
  2724. if (cmSystemTools::GetEnv("CTEST_NO_TESTS_ACTION", action) &&
  2725. !action.empty()) {
  2726. if (action == "error"_s) {
  2727. this->Impl->NoTestsMode = cmCTest::NoTests::Error;
  2728. } else if (action == "ignore"_s) {
  2729. this->Impl->NoTestsMode = cmCTest::NoTests::Ignore;
  2730. } else {
  2731. cmCTestLog(this, ERROR_MESSAGE,
  2732. "Unknown value for CTEST_NO_TESTS_ACTION: '" << action
  2733. << '\'');
  2734. return 1;
  2735. }
  2736. }
  2737. }
  2738. // TestProgressOutput only supported if console supports it and not logging
  2739. // to a file
  2740. this->Impl->TestProgressOutput = this->Impl->TestProgressOutput &&
  2741. !this->Impl->OutputLogFile && this->ProgressOutputSupportedByConsole();
  2742. #ifdef _WIN32
  2743. if (this->Impl->TestProgressOutput) {
  2744. // Disable output line buffering so we can print content without
  2745. // a newline.
  2746. std::setvbuf(stdout, nullptr, _IONBF, 0);
  2747. }
  2748. #endif
  2749. // now what should cmake do? if --build-and-test was specified then
  2750. // we run the build and test handler and return
  2751. if (cmakeAndTest) {
  2752. return this->RunCMakeAndTest();
  2753. }
  2754. if (executeTests) {
  2755. return this->ExecuteTests();
  2756. }
  2757. return 1;
  2758. }
  2759. int cmCTest::ExecuteTests()
  2760. {
  2761. int res;
  2762. // call process directory
  2763. if (this->Impl->RunConfigurationScript) {
  2764. if (this->Impl->ExtraVerbose) {
  2765. cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
  2766. }
  2767. for (auto& handler : this->Impl->GetTestingHandlers()) {
  2768. handler->SetVerbose(this->Impl->ExtraVerbose);
  2769. handler->SetSubmitIndex(this->Impl->SubmitIndex);
  2770. }
  2771. this->GetScriptHandler()->SetVerbose(this->Impl->Verbose);
  2772. res = this->GetScriptHandler()->ProcessHandler();
  2773. if (res != 0) {
  2774. cmCTestLog(this, DEBUG,
  2775. "running script failing returning: " << res << std::endl);
  2776. }
  2777. } else {
  2778. // What is this? -V seems to be the same as -VV,
  2779. // and Verbose is always on in this case
  2780. this->Impl->ExtraVerbose = this->Impl->Verbose;
  2781. this->Impl->Verbose = true;
  2782. for (auto& handler : this->Impl->GetTestingHandlers()) {
  2783. handler->SetVerbose(this->Impl->Verbose);
  2784. handler->SetSubmitIndex(this->Impl->SubmitIndex);
  2785. }
  2786. const std::string currDir = cmSystemTools::GetCurrentWorkingDirectory();
  2787. std::string workDir = currDir;
  2788. if (!this->Impl->TestDir.empty()) {
  2789. workDir = cmSystemTools::CollapseFullPath(this->Impl->TestDir);
  2790. }
  2791. if (currDir != workDir) {
  2792. if (!this->TryToChangeDirectory(workDir)) {
  2793. return 1;
  2794. }
  2795. }
  2796. if (!this->Initialize(workDir, nullptr)) {
  2797. res = 12;
  2798. cmCTestLog(this, ERROR_MESSAGE,
  2799. "Problem initializing the dashboard." << std::endl);
  2800. } else {
  2801. res = this->ProcessSteps();
  2802. }
  2803. this->Finalize();
  2804. if (currDir != workDir) {
  2805. cmSystemTools::ChangeDirectory(currDir);
  2806. }
  2807. }
  2808. if (res != 0) {
  2809. cmCTestLog(this, DEBUG,
  2810. "Running a test(s) failed returning : " << res << std::endl);
  2811. }
  2812. return res;
  2813. }
  2814. int cmCTest::RunCMakeAndTest()
  2815. {
  2816. int retv = this->Impl->BuildAndTest.Run();
  2817. std::cout << this->Impl->BuildAndTest.GetOutput();
  2818. return retv;
  2819. }
  2820. void cmCTest::SetNotesFiles(const std::string& notes)
  2821. {
  2822. this->Impl->NotesFiles = notes;
  2823. }
  2824. bool cmCTest::GetStopOnFailure() const
  2825. {
  2826. return this->Impl->StopOnFailure;
  2827. }
  2828. void cmCTest::SetStopOnFailure(bool stop)
  2829. {
  2830. this->Impl->StopOnFailure = stop;
  2831. }
  2832. std::chrono::system_clock::time_point cmCTest::GetStopTime() const
  2833. {
  2834. return this->Impl->StopTime;
  2835. }
  2836. void cmCTest::SetStopTime(std::string const& time_str)
  2837. {
  2838. struct tm* lctime;
  2839. time_t current_time = time(nullptr);
  2840. lctime = gmtime(&current_time);
  2841. int gm_hour = lctime->tm_hour;
  2842. time_t gm_time = mktime(lctime);
  2843. lctime = localtime(&current_time);
  2844. int local_hour = lctime->tm_hour;
  2845. int tzone_offset = local_hour - gm_hour;
  2846. if (gm_time > current_time && gm_hour < local_hour) {
  2847. // this means gm_time is on the next day
  2848. tzone_offset -= 24;
  2849. } else if (gm_time < current_time && gm_hour > local_hour) {
  2850. // this means gm_time is on the previous day
  2851. tzone_offset += 24;
  2852. }
  2853. tzone_offset *= 100;
  2854. char buf[1024];
  2855. snprintf(buf, sizeof(buf), "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  2856. lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(),
  2857. tzone_offset);
  2858. time_t stop_time = curl_getdate(buf, &current_time);
  2859. if (stop_time == -1) {
  2860. this->Impl->StopTime = std::chrono::system_clock::time_point();
  2861. return;
  2862. }
  2863. this->Impl->StopTime = std::chrono::system_clock::from_time_t(stop_time);
  2864. if (stop_time < current_time) {
  2865. this->Impl->StopTime += std::chrono::hours(24);
  2866. }
  2867. }
  2868. std::string cmCTest::GetScheduleType() const
  2869. {
  2870. return this->Impl->ScheduleType;
  2871. }
  2872. void cmCTest::SetScheduleType(std::string const& type)
  2873. {
  2874. this->Impl->ScheduleType = type;
  2875. }
  2876. int cmCTest::ReadCustomConfigurationFileTree(const std::string& dir,
  2877. cmMakefile* mf)
  2878. {
  2879. bool found = false;
  2880. cmCTestLog(this, DEBUG,
  2881. "* Read custom CTest configuration directory: " << dir
  2882. << std::endl);
  2883. std::string fname = cmStrCat(dir, "/CTestCustom.cmake");
  2884. cmCTestLog(this, DEBUG, "* Check for file: " << fname << std::endl);
  2885. if (cmSystemTools::FileExists(fname)) {
  2886. cmCTestLog(this, DEBUG,
  2887. "* Read custom CTest configuration file: " << fname
  2888. << std::endl);
  2889. bool erroroc = cmSystemTools::GetErrorOccurredFlag();
  2890. cmSystemTools::ResetErrorOccurredFlag();
  2891. if (!mf->ReadListFile(fname) || cmSystemTools::GetErrorOccurredFlag()) {
  2892. cmCTestLog(this, ERROR_MESSAGE,
  2893. "Problem reading custom configuration: " << fname
  2894. << std::endl);
  2895. }
  2896. found = true;
  2897. if (erroroc) {
  2898. cmSystemTools::SetErrorOccurred();
  2899. }
  2900. }
  2901. std::string rexpr = cmStrCat(dir, "/CTestCustom.ctest");
  2902. cmCTestLog(this, DEBUG, "* Check for file: " << rexpr << std::endl);
  2903. if (!found && cmSystemTools::FileExists(rexpr)) {
  2904. cmsys::Glob gl;
  2905. gl.RecurseOn();
  2906. gl.FindFiles(rexpr);
  2907. std::vector<std::string>& files = gl.GetFiles();
  2908. for (const std::string& file : files) {
  2909. cmCTestLog(this, DEBUG,
  2910. "* Read custom CTest configuration file: " << file
  2911. << std::endl);
  2912. if (!mf->ReadListFile(file) || cmSystemTools::GetErrorOccurredFlag()) {
  2913. cmCTestLog(this, ERROR_MESSAGE,
  2914. "Problem reading custom configuration: " << file
  2915. << std::endl);
  2916. }
  2917. }
  2918. found = true;
  2919. }
  2920. if (found) {
  2921. for (auto& handler : this->Impl->GetNamedTestingHandlers()) {
  2922. cmCTestLog(this, DEBUG,
  2923. "* Read custom CTest configuration vectors for handler: "
  2924. << handler.first << " (" << handler.second << ")"
  2925. << std::endl);
  2926. handler.second->PopulateCustomVectors(mf);
  2927. }
  2928. }
  2929. return 1;
  2930. }
  2931. void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def,
  2932. std::vector<std::string>& vec)
  2933. {
  2934. cmValue dval = mf->GetDefinition(def);
  2935. if (!dval) {
  2936. return;
  2937. }
  2938. cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl);
  2939. cmList::assign(vec, *dval);
  2940. for (std::string const& it : vec) {
  2941. cmCTestLog(this, DEBUG, " -- " << it << std::endl);
  2942. }
  2943. }
  2944. void cmCTest::PopulateCustomInteger(cmMakefile* mf, const std::string& def,
  2945. int& val)
  2946. {
  2947. cmValue dval = mf->GetDefinition(def);
  2948. if (!dval) {
  2949. return;
  2950. }
  2951. val = atoi(dval->c_str());
  2952. }
  2953. std::string cmCTest::GetShortPathToFile(const std::string& cfname)
  2954. {
  2955. const std::string& sourceDir = cmSystemTools::CollapseFullPath(
  2956. this->GetCTestConfiguration("SourceDirectory"));
  2957. const std::string& buildDir = cmSystemTools::CollapseFullPath(
  2958. this->GetCTestConfiguration("BuildDirectory"));
  2959. std::string fname = cmSystemTools::CollapseFullPath(cfname);
  2960. // Find relative paths to both directories
  2961. std::string srcRelpath = cmSystemTools::RelativePath(sourceDir, fname);
  2962. std::string bldRelpath = cmSystemTools::RelativePath(buildDir, fname);
  2963. // If any contains "." it is not parent directory
  2964. bool inSrc = srcRelpath.find("..") == std::string::npos;
  2965. bool inBld = bldRelpath.find("..") == std::string::npos;
  2966. // TODO: Handle files with .. in their name
  2967. std::string* res = nullptr;
  2968. if (inSrc && inBld) {
  2969. // If both have relative path with no dots, pick the shorter one
  2970. if (srcRelpath.size() < bldRelpath.size()) {
  2971. res = &srcRelpath;
  2972. } else {
  2973. res = &bldRelpath;
  2974. }
  2975. } else if (inSrc) {
  2976. res = &srcRelpath;
  2977. } else if (inBld) {
  2978. res = &bldRelpath;
  2979. }
  2980. std::string path;
  2981. if (!res) {
  2982. path = fname;
  2983. } else {
  2984. cmSystemTools::ConvertToUnixSlashes(*res);
  2985. path = "./" + *res;
  2986. if (path.back() == '/') {
  2987. path.resize(path.size() - 1);
  2988. }
  2989. }
  2990. cmsys::SystemTools::ReplaceString(path, ":", "_");
  2991. cmsys::SystemTools::ReplaceString(path, " ", "_");
  2992. return path;
  2993. }
  2994. std::string cmCTest::GetCTestConfiguration(const std::string& name)
  2995. {
  2996. if (this->Impl->CTestConfigurationOverwrites.find(name) !=
  2997. this->Impl->CTestConfigurationOverwrites.end()) {
  2998. return this->Impl->CTestConfigurationOverwrites[name];
  2999. }
  3000. return this->Impl->CTestConfiguration[name];
  3001. }
  3002. void cmCTest::EmptyCTestConfiguration()
  3003. {
  3004. this->Impl->CTestConfiguration.clear();
  3005. }
  3006. void cmCTest::SetCTestConfiguration(const char* name, const std::string& value,
  3007. bool suppress)
  3008. {
  3009. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  3010. "SetCTestConfiguration:" << name << ":" << value << "\n",
  3011. suppress);
  3012. if (!name) {
  3013. return;
  3014. }
  3015. if (value.empty()) {
  3016. this->Impl->CTestConfiguration.erase(name);
  3017. return;
  3018. }
  3019. this->Impl->CTestConfiguration[name] = value;
  3020. }
  3021. std::string cmCTest::GetSubmitURL()
  3022. {
  3023. std::string url = this->GetCTestConfiguration("SubmitURL");
  3024. if (url.empty()) {
  3025. std::string method = this->GetCTestConfiguration("DropMethod");
  3026. std::string user = this->GetCTestConfiguration("DropSiteUser");
  3027. std::string password = this->GetCTestConfiguration("DropSitePassword");
  3028. std::string site = this->GetCTestConfiguration("DropSite");
  3029. std::string location = this->GetCTestConfiguration("DropLocation");
  3030. url = cmStrCat(method.empty() ? "http" : method, "://"_s);
  3031. if (!user.empty()) {
  3032. url += user;
  3033. if (!password.empty()) {
  3034. url += ':';
  3035. url += password;
  3036. }
  3037. url += '@';
  3038. }
  3039. url += site;
  3040. url += location;
  3041. }
  3042. return url;
  3043. }
  3044. std::string cmCTest::GetCurrentTag()
  3045. {
  3046. return this->Impl->CurrentTag;
  3047. }
  3048. std::string cmCTest::GetBinaryDir()
  3049. {
  3050. return this->Impl->BinaryDir;
  3051. }
  3052. std::string const& cmCTest::GetConfigType()
  3053. {
  3054. return this->Impl->ConfigType;
  3055. }
  3056. cmDuration cmCTest::GetTimeOut() const
  3057. {
  3058. return this->Impl->TimeOut;
  3059. }
  3060. void cmCTest::SetTimeOut(cmDuration t)
  3061. {
  3062. this->Impl->TimeOut = t;
  3063. }
  3064. cmDuration cmCTest::GetGlobalTimeout() const
  3065. {
  3066. return this->Impl->GlobalTimeout;
  3067. }
  3068. bool cmCTest::GetShowOnly()
  3069. {
  3070. return this->Impl->ShowOnly;
  3071. }
  3072. bool cmCTest::GetOutputAsJson()
  3073. {
  3074. return this->Impl->OutputAsJson;
  3075. }
  3076. int cmCTest::GetOutputAsJsonVersion()
  3077. {
  3078. return this->Impl->OutputAsJsonVersion;
  3079. }
  3080. bool cmCTest::ShouldUseHTTP10() const
  3081. {
  3082. return this->Impl->UseHTTP10;
  3083. }
  3084. bool cmCTest::ShouldPrintLabels() const
  3085. {
  3086. return this->Impl->PrintLabels;
  3087. }
  3088. int cmCTest::GetMaxTestNameWidth() const
  3089. {
  3090. return this->Impl->MaxTestNameWidth;
  3091. }
  3092. void cmCTest::SetMaxTestNameWidth(int w)
  3093. {
  3094. this->Impl->MaxTestNameWidth = w;
  3095. }
  3096. void cmCTest::SetProduceXML(bool v)
  3097. {
  3098. this->Impl->ProduceXML = v;
  3099. }
  3100. bool cmCTest::GetProduceXML()
  3101. {
  3102. return this->Impl->ProduceXML;
  3103. }
  3104. std::vector<std::string>& cmCTest::GetInitialCommandLineArguments()
  3105. {
  3106. return this->Impl->InitialCommandLineArguments;
  3107. }
  3108. const char* cmCTest::GetSpecificGroup()
  3109. {
  3110. if (this->Impl->SpecificGroup.empty()) {
  3111. return nullptr;
  3112. }
  3113. return this->Impl->SpecificGroup.c_str();
  3114. }
  3115. void cmCTest::SetSpecificGroup(const char* group)
  3116. {
  3117. if (!group) {
  3118. this->Impl->SpecificGroup.clear();
  3119. return;
  3120. }
  3121. this->Impl->SpecificGroup = group;
  3122. }
  3123. void cmCTest::SetFailover(bool failover)
  3124. {
  3125. this->Impl->Failover = failover;
  3126. }
  3127. bool cmCTest::GetFailover() const
  3128. {
  3129. return this->Impl->Failover;
  3130. }
  3131. bool cmCTest::GetTestProgressOutput() const
  3132. {
  3133. return this->Impl->TestProgressOutput && !GetExtraVerbose();
  3134. }
  3135. bool cmCTest::GetVerbose() const
  3136. {
  3137. return this->Impl->Verbose;
  3138. }
  3139. bool cmCTest::GetExtraVerbose() const
  3140. {
  3141. return this->Impl->ExtraVerbose;
  3142. }
  3143. bool cmCTest::GetLabelSummary() const
  3144. {
  3145. return this->Impl->LabelSummary;
  3146. }
  3147. bool cmCTest::GetSubprojectSummary() const
  3148. {
  3149. return this->Impl->SubprojectSummary;
  3150. }
  3151. bool cmCTest::GetOutputTestOutputOnTestFailure() const
  3152. {
  3153. return this->Impl->OutputTestOutputOnTestFailure;
  3154. }
  3155. const std::map<std::string, std::string>& cmCTest::GetDefinitions() const
  3156. {
  3157. return this->Impl->Definitions;
  3158. }
  3159. int cmCTest::GetRepeatCount() const
  3160. {
  3161. return this->Impl->RepeatCount;
  3162. }
  3163. cmCTest::Repeat cmCTest::GetRepeatMode() const
  3164. {
  3165. return this->Impl->RepeatMode;
  3166. }
  3167. cmCTest::NoTests cmCTest::GetNoTestsMode() const
  3168. {
  3169. return this->Impl->NoTestsMode;
  3170. }
  3171. void cmCTest::SetBuildID(const std::string& id)
  3172. {
  3173. this->Impl->BuildID = id;
  3174. }
  3175. std::string cmCTest::GetBuildID() const
  3176. {
  3177. return this->Impl->BuildID;
  3178. }
  3179. void cmCTest::AddSubmitFile(Part part, const std::string& name)
  3180. {
  3181. this->Impl->Parts[part].SubmitFiles.emplace_back(name);
  3182. }
  3183. std::vector<std::string> const& cmCTest::GetSubmitFiles(Part part) const
  3184. {
  3185. return this->Impl->Parts[part].SubmitFiles;
  3186. }
  3187. void cmCTest::ClearSubmitFiles(Part part)
  3188. {
  3189. this->Impl->Parts[part].SubmitFiles.clear();
  3190. }
  3191. void cmCTest::SetSuppressUpdatingCTestConfiguration(bool val)
  3192. {
  3193. this->Impl->SuppressUpdatingCTestConfiguration = val;
  3194. }
  3195. void cmCTest::AddCTestConfigurationOverwrite(const std::string& overStr)
  3196. {
  3197. size_t epos = overStr.find('=');
  3198. if (epos == std::string::npos) {
  3199. cmCTestLog(this, ERROR_MESSAGE,
  3200. "CTest configuration overwrite specified in the wrong format.\n"
  3201. "Valid format is: --overwrite key=value\n"
  3202. "The specified was: --overwrite "
  3203. << overStr << '\n');
  3204. return;
  3205. }
  3206. std::string key = overStr.substr(0, epos);
  3207. std::string value = overStr.substr(epos + 1);
  3208. this->Impl->CTestConfigurationOverwrites[key] = value;
  3209. }
  3210. void cmCTest::SetConfigType(const std::string& ct)
  3211. {
  3212. this->Impl->ConfigType = ct;
  3213. cmSystemTools::ReplaceString(this->Impl->ConfigType, ".\\", "");
  3214. std::string confTypeEnv = "CMAKE_CONFIG_TYPE=" + this->Impl->ConfigType;
  3215. cmSystemTools::PutEnv(confTypeEnv);
  3216. }
  3217. bool cmCTest::SetCTestConfigurationFromCMakeVariable(
  3218. cmMakefile* mf, const char* dconfig, const std::string& cmake_var,
  3219. bool suppress)
  3220. {
  3221. cmValue ctvar = mf->GetDefinition(cmake_var);
  3222. if (!ctvar) {
  3223. return false;
  3224. }
  3225. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  3226. "SetCTestConfigurationFromCMakeVariable:"
  3227. << dconfig << ":" << cmake_var << std::endl,
  3228. suppress);
  3229. this->SetCTestConfiguration(dconfig, *ctvar, suppress);
  3230. return true;
  3231. }
  3232. void cmCTest::SetCMakeVariables(cmMakefile& mf)
  3233. {
  3234. auto set = [&](char const* cmake_var, char const* ctest_opt) {
  3235. std::string val = this->GetCTestConfiguration(ctest_opt);
  3236. if (!val.empty()) {
  3237. cmCTestOptionalLog(
  3238. this, HANDLER_VERBOSE_OUTPUT,
  3239. "SetCMakeVariable:" << cmake_var << ":" << val << std::endl, false);
  3240. mf.AddDefinition(cmake_var, val);
  3241. }
  3242. };
  3243. set("CTEST_SITE", "Site");
  3244. set("CTEST_BUILD_NAME", "BuildName");
  3245. set("CTEST_NIGHTLY_START_TIME", "NightlyStartTime");
  3246. set("CTEST_SOURCE_DIRECTORY", "SourceDirectory");
  3247. set("CTEST_BINARY_DIRECTORY", "BuildDirectory");
  3248. // CTest Update Step
  3249. set("CTEST_UPDATE_COMMAND", "UpdateCommand");
  3250. set("CTEST_UPDATE_OPTIONS", "UpdateOptions");
  3251. set("CTEST_CVS_COMMAND", "CVSCommand");
  3252. set("CTEST_CVS_UPDATE_OPTIONS", "CVSUpdateOptions");
  3253. set("CTEST_SVN_COMMAND", "SVNCommand");
  3254. set("CTEST_SVN_UPDATE_OPTIONS", "SVNUpdateOptions");
  3255. set("CTEST_SVN_OPTIONS", "SVNOptions");
  3256. set("CTEST_BZR_COMMAND", "BZRCommand");
  3257. set("CTEST_BZR_UPDATE_OPTIONS", "BZRUpdateOptions");
  3258. set("CTEST_GIT_COMMAND", "GITCommand");
  3259. set("CTEST_GIT_UPDATE_OPTIONS", "GITUpdateOptions");
  3260. set("CTEST_GIT_INIT_SUBMODULES", "GITInitSubmodules");
  3261. set("CTEST_GIT_UPDATE_CUSTOM", "GITUpdateCustom");
  3262. set("CTEST_UPDATE_VERSION_ONLY", "UpdateVersionOnly");
  3263. set("CTEST_UPDATE_VERSION_OVERRIDE", "UpdateVersionOverride");
  3264. set("CTEST_HG_COMMAND", "HGCommand");
  3265. set("CTEST_HG_UPDATE_OPTIONS", "HGUpdateOptions");
  3266. set("CTEST_P4_COMMAND", "P4Command");
  3267. set("CTEST_P4_UPDATE_OPTIONS", "P4UpdateOptions");
  3268. set("CTEST_P4_CLIENT", "P4Client");
  3269. set("CTEST_P4_OPTIONS", "P4Options");
  3270. // CTest Configure Step
  3271. set("CTEST_CONFIGURE_COMMAND", "ConfigureCommand");
  3272. set("CTEST_LABELS_FOR_SUBPROJECTS", "LabelsForSubprojects");
  3273. // CTest Build Step
  3274. set("CTEST_BUILD_COMMAND", "MakeCommand");
  3275. set("CTEST_USE_LAUNCHERS", "UseLaunchers");
  3276. // CTest Coverage Step
  3277. set("CTEST_COVERAGE_COMMAND", "CoverageCommand");
  3278. set("CTEST_COVERAGE_EXTRA_FLAGS", "CoverageExtraFlags");
  3279. // CTest MemCheck Step
  3280. set("CTEST_MEMORYCHECK_TYPE", "MemoryCheckType");
  3281. set("CTEST_MEMORYCHECK_SANITIZER_OPTIONS", "MemoryCheckSanitizerOptions");
  3282. set("CTEST_MEMORYCHECK_COMMAND", "MemoryCheckCommand");
  3283. set("CTEST_MEMORYCHECK_COMMAND_OPTIONS", "MemoryCheckCommandOptions");
  3284. set("CTEST_MEMORYCHECK_SUPPRESSIONS_FILE", "MemoryCheckSuppressionFile");
  3285. // CTest Submit Step
  3286. set("CTEST_SUBMIT_URL", "SubmitURL");
  3287. set("CTEST_DROP_METHOD", "DropMethod");
  3288. set("CTEST_DROP_SITE_USER", "DropSiteUser");
  3289. set("CTEST_DROP_SITE_PASSWORD", "DropSitePassword");
  3290. set("CTEST_DROP_SITE", "DropSite");
  3291. set("CTEST_DROP_LOCATION", "DropLocation");
  3292. set("CTEST_TLS_VERIFY", "TLSVerify");
  3293. set("CTEST_TLS_VERSION", "TLSVersion");
  3294. set("CTEST_CURL_OPTIONS", "CurlOptions");
  3295. set("CTEST_SUBMIT_INACTIVITY_TIMEOUT", "SubmitInactivityTimeout");
  3296. this->GetTestHandler()->SetCMakeVariables(mf);
  3297. }
  3298. bool cmCTest::RunCommand(std::vector<std::string> const& args,
  3299. std::string* stdOut, std::string* stdErr, int* retVal,
  3300. const char* dir, cmDuration timeout,
  3301. Encoding encoding)
  3302. {
  3303. std::vector<const char*> argv;
  3304. argv.reserve(args.size() + 1);
  3305. for (std::string const& a : args) {
  3306. argv.push_back(a.c_str());
  3307. }
  3308. argv.push_back(nullptr);
  3309. stdOut->clear();
  3310. stdErr->clear();
  3311. cmUVProcessChainBuilder builder;
  3312. builder.AddCommand(args)
  3313. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  3314. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  3315. if (dir) {
  3316. builder.SetWorkingDirectory(dir);
  3317. }
  3318. auto chain = builder.Start();
  3319. cm::uv_timer_ptr timer;
  3320. bool timedOut = false;
  3321. if (timeout.count()) {
  3322. timer.init(chain.GetLoop(), &timedOut);
  3323. timer.start(
  3324. [](uv_timer_t* t) {
  3325. auto* timedOutPtr = static_cast<bool*>(t->data);
  3326. *timedOutPtr = true;
  3327. },
  3328. static_cast<uint64_t>(timeout.count() * 1000.0), 0);
  3329. }
  3330. std::vector<char> tempOutput;
  3331. bool outFinished = false;
  3332. cm::uv_pipe_ptr outStream;
  3333. std::vector<char> tempError;
  3334. bool errFinished = false;
  3335. cm::uv_pipe_ptr errStream;
  3336. cmProcessOutput processOutput(encoding);
  3337. auto startRead = [this, &chain, &processOutput](
  3338. cm::uv_pipe_ptr& pipe, int stream,
  3339. std::vector<char>& temp,
  3340. bool& finished) -> std::unique_ptr<cmUVStreamReadHandle> {
  3341. pipe.init(chain.GetLoop(), 0);
  3342. uv_pipe_open(pipe, stream);
  3343. return cmUVStreamRead(
  3344. pipe,
  3345. [this, &temp, &processOutput](std::vector<char> data) {
  3346. cm::append(temp, data);
  3347. if (this->Impl->ExtraVerbose) {
  3348. std::string strdata;
  3349. processOutput.DecodeText(data.data(), data.size(), strdata);
  3350. cmSystemTools::Stdout(strdata);
  3351. }
  3352. },
  3353. [&finished]() { finished = true; });
  3354. };
  3355. auto outputHandle =
  3356. startRead(outStream, chain.OutputStream(), tempOutput, outFinished);
  3357. auto errorHandle =
  3358. startRead(errStream, chain.ErrorStream(), tempError, errFinished);
  3359. while (!timedOut && !(outFinished && errFinished)) {
  3360. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  3361. }
  3362. if (this->Impl->ExtraVerbose) {
  3363. std::string strdata;
  3364. processOutput.DecodeText(std::string(), strdata);
  3365. if (!strdata.empty()) {
  3366. cmSystemTools::Stdout(strdata);
  3367. }
  3368. }
  3369. while (!timedOut && !chain.Finished()) {
  3370. uv_run(&chain.GetLoop(), UV_RUN_ONCE);
  3371. }
  3372. if (!tempOutput.empty()) {
  3373. processOutput.DecodeText(tempOutput, tempOutput);
  3374. stdOut->append(tempOutput.data(), tempOutput.size());
  3375. }
  3376. if (!tempError.empty()) {
  3377. processOutput.DecodeText(tempError, tempError);
  3378. stdErr->append(tempError.data(), tempError.size());
  3379. }
  3380. bool result = true;
  3381. if (timedOut) {
  3382. const char* error_str = "Process terminated due to timeout\n";
  3383. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  3384. stdErr->append(error_str, strlen(error_str));
  3385. result = false;
  3386. } else {
  3387. auto const& status = chain.GetStatus(0);
  3388. auto exception = status.GetException();
  3389. switch (exception.first) {
  3390. case cmUVProcessChain::ExceptionCode::None:
  3391. if (retVal) {
  3392. *retVal = static_cast<int>(status.ExitStatus);
  3393. } else {
  3394. if (status.ExitStatus != 0) {
  3395. result = false;
  3396. }
  3397. }
  3398. break;
  3399. default: {
  3400. cmCTestLog(this, ERROR_MESSAGE, exception.second << std::endl);
  3401. stdErr->append(exception.second);
  3402. result = false;
  3403. } break;
  3404. }
  3405. }
  3406. return result;
  3407. }
  3408. void cmCTest::SetOutputLogFileName(const std::string& name)
  3409. {
  3410. if (!name.empty()) {
  3411. this->Impl->OutputLogFile = cm::make_unique<cmGeneratedFileStream>(name);
  3412. } else {
  3413. this->Impl->OutputLogFile.reset();
  3414. }
  3415. }
  3416. void cmCTest::SetOutputJUnitFileName(const std::string& name)
  3417. {
  3418. this->Impl->TestHandler.SetJUnitXMLFileName(name);
  3419. // Turn test output compression off.
  3420. // This makes it easier to include test output in the resulting
  3421. // JUnit XML report.
  3422. this->Impl->CompressTestOutput = false;
  3423. }
  3424. static const char* cmCTestStringLogType[] = { "DEBUG",
  3425. "OUTPUT",
  3426. "HANDLER_OUTPUT",
  3427. "HANDLER_PROGRESS_OUTPUT",
  3428. "HANDLER_TEST_PROGRESS_OUTPUT",
  3429. "HANDLER_VERBOSE_OUTPUT",
  3430. "WARNING",
  3431. "ERROR_MESSAGE" };
  3432. void cmCTest::Log(LogType logType, std::string msg, bool suppress)
  3433. {
  3434. if (msg.empty()) {
  3435. return;
  3436. }
  3437. if (suppress && logType != cmCTest::ERROR_MESSAGE) {
  3438. return;
  3439. }
  3440. if (logType == cmCTest::HANDLER_PROGRESS_OUTPUT &&
  3441. (this->Impl->Debug || this->Impl->ExtraVerbose)) {
  3442. return;
  3443. }
  3444. if (this->Impl->OutputLogFile) {
  3445. bool display = true;
  3446. if (logType == cmCTest::DEBUG && !this->Impl->Debug) {
  3447. display = false;
  3448. }
  3449. if (logType == cmCTest::HANDLER_VERBOSE_OUTPUT && !this->Impl->Debug &&
  3450. !this->Impl->ExtraVerbose) {
  3451. display = false;
  3452. }
  3453. if (display) {
  3454. if (this->Impl->OutputLogFileLastTag &&
  3455. logType != *this->Impl->OutputLogFileLastTag) {
  3456. *this->Impl->OutputLogFile << "[" << cmCTestStringLogType[logType]
  3457. << "] " << std::endl;
  3458. }
  3459. *this->Impl->OutputLogFile << msg << std::flush;
  3460. if (this->Impl->OutputLogFileLastTag &&
  3461. logType != *this->Impl->OutputLogFileLastTag) {
  3462. *this->Impl->OutputLogFile << std::endl;
  3463. this->Impl->OutputLogFileLastTag = logType;
  3464. }
  3465. }
  3466. }
  3467. if (!this->Impl->Quiet) {
  3468. if (logType == HANDLER_TEST_PROGRESS_OUTPUT) {
  3469. if (this->Impl->TestProgressOutput) {
  3470. if (this->Impl->FlushTestProgressLine) {
  3471. printf("\r");
  3472. this->Impl->FlushTestProgressLine = false;
  3473. std::cout.flush();
  3474. }
  3475. if (msg.find('\n') != std::string::npos) {
  3476. this->Impl->FlushTestProgressLine = true;
  3477. msg.erase(std::remove(msg.begin(), msg.end(), '\n'), msg.end());
  3478. }
  3479. std::cout << msg;
  3480. #ifndef _WIN32
  3481. printf("\x1B[K"); // move caret to end
  3482. #endif
  3483. std::cout.flush();
  3484. return;
  3485. }
  3486. logType = HANDLER_OUTPUT;
  3487. }
  3488. switch (logType) {
  3489. case DEBUG:
  3490. if (this->Impl->Debug) {
  3491. std::cout << msg << std::flush;
  3492. }
  3493. break;
  3494. case OUTPUT:
  3495. case HANDLER_OUTPUT:
  3496. if (this->Impl->Debug || this->Impl->Verbose) {
  3497. std::cout << msg << std::flush;
  3498. }
  3499. break;
  3500. case HANDLER_VERBOSE_OUTPUT:
  3501. if (this->Impl->Debug || this->Impl->ExtraVerbose) {
  3502. std::cout << msg << std::flush;
  3503. }
  3504. break;
  3505. case WARNING:
  3506. std::cerr << msg << std::flush;
  3507. break;
  3508. case ERROR_MESSAGE:
  3509. std::cerr << msg << std::flush;
  3510. cmSystemTools::SetErrorOccurred();
  3511. break;
  3512. default:
  3513. std::cout << msg << std::flush;
  3514. }
  3515. }
  3516. }
  3517. std::string cmCTest::GetColorCode(Color color) const
  3518. {
  3519. if (this->Impl->OutputColorCode) {
  3520. return "\033[0;" + std::to_string(static_cast<int>(color)) + "m";
  3521. }
  3522. return "";
  3523. }
  3524. cmDuration cmCTest::GetRemainingTimeAllowed()
  3525. {
  3526. return this->GetScriptHandler()->GetRemainingTimeAllowed();
  3527. }
  3528. cmDuration cmCTest::MaxDuration()
  3529. {
  3530. return cmDuration(1.0e7);
  3531. }
  3532. bool cmCTest::CompressString(std::string& str)
  3533. {
  3534. int ret;
  3535. z_stream strm;
  3536. strm.zalloc = Z_NULL;
  3537. strm.zfree = Z_NULL;
  3538. strm.opaque = Z_NULL;
  3539. ret = deflateInit(&strm, -1); // default compression level
  3540. if (ret != Z_OK) {
  3541. return false;
  3542. }
  3543. unsigned char* in =
  3544. reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
  3545. // zlib makes the guarantee that this is the maximum output size
  3546. int outSize =
  3547. static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
  3548. std::vector<unsigned char> out(outSize);
  3549. strm.avail_in = static_cast<uInt>(str.size());
  3550. strm.next_in = in;
  3551. strm.avail_out = outSize;
  3552. strm.next_out = out.data();
  3553. ret = deflate(&strm, Z_FINISH);
  3554. if (ret != Z_STREAM_END) {
  3555. cmCTestLog(this, ERROR_MESSAGE,
  3556. "Error during gzip compression." << std::endl);
  3557. return false;
  3558. }
  3559. (void)deflateEnd(&strm);
  3560. // Now base64 encode the resulting binary string
  3561. std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
  3562. size_t rlen = cmsysBase64_Encode(out.data(), strm.total_out,
  3563. base64EncodedBuffer.data(), 1);
  3564. str.assign(reinterpret_cast<char*>(base64EncodedBuffer.data()), rlen);
  3565. return true;
  3566. }