cmCTest.cxx 124 KB

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