cmCTest.cxx 118 KB

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