cmCTest.cxx 124 KB

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