cmCTest.cxx 120 KB

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