cmCTest.cxx 124 KB

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