cmCTest.cxx 122 KB

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