cmCTest.cxx 125 KB

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