cmCTest.cxx 118 KB

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