cmCTest.cxx 101 KB

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