cmCTestCoverageHandler.cxx 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  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 "cmCTestCoverageHandler.h"
  4. #include <algorithm>
  5. #include <chrono>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <iomanip>
  9. #include <iterator>
  10. #include <memory>
  11. #include <ratio>
  12. #include <sstream>
  13. #include <type_traits>
  14. #include <utility>
  15. #include <cmext/algorithm>
  16. #include "cmsys/FStream.hxx"
  17. #include "cmsys/Glob.hxx"
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmCTest.h"
  20. #include "cmDuration.h"
  21. #include "cmGeneratedFileStream.h"
  22. #include "cmParseBlanketJSCoverage.h"
  23. #include "cmParseCacheCoverage.h"
  24. #include "cmParseCoberturaCoverage.h"
  25. #include "cmParseDelphiCoverage.h"
  26. #include "cmParseGTMCoverage.h"
  27. #include "cmParseJacocoCoverage.h"
  28. #include "cmParsePHPCoverage.h"
  29. #include "cmStringAlgorithms.h"
  30. #include "cmSystemTools.h"
  31. #include "cmUVProcessChain.h"
  32. #include "cmWorkingDirectory.h"
  33. #include "cmXMLWriter.h"
  34. class cmMakefile;
  35. #define SAFEDIV(x, y) (((y) != 0) ? ((x) / (y)) : (0))
  36. cmCTestCoverageHandler::cmCTestCoverageHandler() = default;
  37. void cmCTestCoverageHandler::Initialize()
  38. {
  39. this->Superclass::Initialize();
  40. this->CustomCoverageExclude.clear();
  41. this->SourceLabels.clear();
  42. this->TargetDirs.clear();
  43. this->LabelIdMap.clear();
  44. this->Labels.clear();
  45. this->LabelFilter.clear();
  46. }
  47. void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log)
  48. {
  49. std::string logGlob =
  50. cmStrCat(this->CTest->GetCTestConfiguration("BuildDirectory"), "/Testing/",
  51. this->CTest->GetCurrentTag(), "/CoverageLog*");
  52. cmsys::Glob gl;
  53. gl.FindFiles(logGlob);
  54. std::vector<std::string> const& files = gl.GetFiles();
  55. for (std::string const& f : files) {
  56. log << "Removing old coverage log: " << f << "\n";
  57. cmSystemTools::RemoveFile(f);
  58. }
  59. }
  60. bool cmCTestCoverageHandler::StartCoverageLogFile(
  61. cmGeneratedFileStream& covLogFile, int logFileCount)
  62. {
  63. char covLogFilename[1024];
  64. snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d",
  65. logFileCount);
  66. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  67. "Open file: " << covLogFilename << std::endl,
  68. this->Quiet);
  69. if (!this->StartResultingXML(cmCTest::PartCoverage, covLogFilename,
  70. covLogFile)) {
  71. cmCTestLog(this->CTest, ERROR_MESSAGE,
  72. "Cannot open log file: " << covLogFilename << std::endl);
  73. return false;
  74. }
  75. return true;
  76. }
  77. void cmCTestCoverageHandler::EndCoverageLogFile(cmGeneratedFileStream& ostr,
  78. int logFileCount)
  79. {
  80. char covLogFilename[1024];
  81. snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d.xml",
  82. logFileCount);
  83. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  84. "Close file: " << covLogFilename << std::endl,
  85. this->Quiet);
  86. ostr.Close();
  87. }
  88. void cmCTestCoverageHandler::StartCoverageLogXML(cmXMLWriter& xml)
  89. {
  90. this->CTest->StartXML(xml, this->AppendXML);
  91. xml.StartElement("CoverageLog");
  92. xml.Element("StartDateTime", this->CTest->CurrentTime());
  93. xml.Element("StartTime", std::chrono::system_clock::now());
  94. }
  95. void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml)
  96. {
  97. xml.Element("EndDateTime", this->CTest->CurrentTime());
  98. xml.Element("EndTime", std::chrono::system_clock::now());
  99. xml.EndElement(); // CoverageLog
  100. this->CTest->EndXML(xml);
  101. }
  102. bool cmCTestCoverageHandler::ShouldIDoCoverage(std::string const& file,
  103. std::string const& srcDir,
  104. std::string const& binDir)
  105. {
  106. if (this->IsFilteredOut(file)) {
  107. return false;
  108. }
  109. for (cmsys::RegularExpression& rx : this->CustomCoverageExcludeRegex) {
  110. if (rx.find(file)) {
  111. cmCTestOptionalLog(
  112. this->CTest, HANDLER_VERBOSE_OUTPUT,
  113. " File " << file << " is excluded in CTestCustom.ctest" << std::endl;
  114. , this->Quiet);
  115. return false;
  116. }
  117. }
  118. std::string fSrcDir = cmSystemTools::CollapseFullPath(srcDir);
  119. std::string fBinDir = cmSystemTools::CollapseFullPath(binDir);
  120. std::string fFile = cmSystemTools::CollapseFullPath(file);
  121. bool sourceSubDir = cmSystemTools::IsSubDirectory(fFile, fSrcDir);
  122. bool buildSubDir = cmSystemTools::IsSubDirectory(fFile, fBinDir);
  123. // Always check parent directory of the file.
  124. std::string fileDir = cmSystemTools::GetFilenamePath(fFile);
  125. std::string checkDir;
  126. // We also need to check the binary/source directory pair.
  127. if (sourceSubDir && buildSubDir) {
  128. if (fSrcDir.size() > fBinDir.size()) {
  129. checkDir = fSrcDir;
  130. } else {
  131. checkDir = fBinDir;
  132. }
  133. } else if (sourceSubDir) {
  134. checkDir = fSrcDir;
  135. } else if (buildSubDir) {
  136. checkDir = fBinDir;
  137. }
  138. std::string ndc = cmSystemTools::FileExistsInParentDirectories(
  139. ".NoDartCoverage", fFile, checkDir);
  140. if (!ndc.empty()) {
  141. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  142. "Found: " << ndc << " so skip coverage of " << file
  143. << std::endl,
  144. this->Quiet);
  145. return false;
  146. }
  147. // By now checkDir should be set to parent directory of the file.
  148. // Get the relative path to the file an apply it to the opposite directory.
  149. // If it is the same as fileDir, then ignore, otherwise check.
  150. std::string relPath;
  151. if (!checkDir.empty()) {
  152. relPath = cmSystemTools::RelativePath(checkDir, fFile);
  153. } else {
  154. relPath = fFile;
  155. }
  156. if (checkDir == fSrcDir) {
  157. checkDir = fBinDir;
  158. } else {
  159. checkDir = fSrcDir;
  160. }
  161. fFile = checkDir + "/" + relPath;
  162. fFile = cmSystemTools::GetFilenamePath(fFile);
  163. if (fileDir == fFile) {
  164. // This is in-source build, so we trust the previous check.
  165. return true;
  166. }
  167. ndc = cmSystemTools::FileExistsInParentDirectories(".NoDartCoverage", fFile,
  168. checkDir);
  169. if (!ndc.empty()) {
  170. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  171. "Found: " << ndc << " so skip coverage of: " << file
  172. << std::endl,
  173. this->Quiet);
  174. return false;
  175. }
  176. // Ok, nothing in source tree, nothing in binary tree
  177. return true;
  178. }
  179. // clearly it would be nice if this were broken up into a few smaller
  180. // functions and commented...
  181. int cmCTestCoverageHandler::ProcessHandler()
  182. {
  183. this->CTest->ClearSubmitFiles(cmCTest::PartCoverage);
  184. int error = 0;
  185. // do we have time for this
  186. if (this->CTest->GetRemainingTimeAllowed() < std::chrono::minutes(2)) {
  187. return error;
  188. }
  189. std::string coverage_start_time = this->CTest->CurrentTime();
  190. auto coverage_start_time_time = std::chrono::system_clock::now();
  191. std::string sourceDir =
  192. this->CTest->GetCTestConfiguration("SourceDirectory");
  193. std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  194. if (binaryDir.empty()) {
  195. cmCTestLog(this->CTest, ERROR_MESSAGE,
  196. "Binary directory is not set. "
  197. "No coverage checking will be performed."
  198. << std::endl);
  199. return 0;
  200. }
  201. this->LoadLabels();
  202. cmGeneratedFileStream ofs;
  203. auto elapsed_time_start = std::chrono::steady_clock::now();
  204. if (!this->StartLogFile("Coverage", ofs)) {
  205. cmCTestLog(this->CTest, ERROR_MESSAGE,
  206. "Cannot create LastCoverage.log file" << std::endl);
  207. }
  208. ofs << "Performing coverage: "
  209. << elapsed_time_start.time_since_epoch().count() << std::endl;
  210. this->CleanCoverageLogFiles(ofs);
  211. cmSystemTools::ConvertToUnixSlashes(sourceDir);
  212. cmSystemTools::ConvertToUnixSlashes(binaryDir);
  213. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  214. "Performing coverage" << std::endl, this->Quiet);
  215. cmCTestCoverageHandlerContainer cont;
  216. cont.Error = error;
  217. cont.SourceDir = sourceDir;
  218. cont.BinaryDir = binaryDir;
  219. cont.OFS = &ofs;
  220. cont.Quiet = this->Quiet;
  221. // setup the regex exclude stuff
  222. this->CustomCoverageExcludeRegex.clear();
  223. for (std::string const& rex : this->CustomCoverageExclude) {
  224. this->CustomCoverageExcludeRegex.emplace_back(rex);
  225. }
  226. if (this->HandleBullseyeCoverage(&cont)) {
  227. return cont.Error;
  228. }
  229. int file_count = 0;
  230. file_count += this->HandleGCovCoverage(&cont);
  231. error = cont.Error;
  232. if (file_count < 0) {
  233. return error;
  234. }
  235. file_count += this->HandleLCovCoverage(&cont);
  236. error = cont.Error;
  237. if (file_count < 0) {
  238. return error;
  239. }
  240. file_count += this->HandleTracePyCoverage(&cont);
  241. error = cont.Error;
  242. if (file_count < 0) {
  243. return error;
  244. }
  245. file_count += this->HandlePHPCoverage(&cont);
  246. error = cont.Error;
  247. if (file_count < 0) {
  248. return error;
  249. }
  250. file_count += this->HandleCoberturaCoverage(&cont);
  251. error = cont.Error;
  252. if (file_count < 0) {
  253. return error;
  254. }
  255. file_count += this->HandleMumpsCoverage(&cont);
  256. error = cont.Error;
  257. if (file_count < 0) {
  258. return error;
  259. }
  260. file_count += this->HandleJacocoCoverage(&cont);
  261. error = cont.Error;
  262. if (file_count < 0) {
  263. return error;
  264. }
  265. file_count += this->HandleBlanketJSCoverage(&cont);
  266. error = cont.Error;
  267. if (file_count < 0) {
  268. return error;
  269. }
  270. file_count += this->HandleDelphiCoverage(&cont);
  271. error = cont.Error;
  272. if (file_count < 0) {
  273. return error;
  274. }
  275. std::set<std::string> uncovered = this->FindUncoveredFiles(&cont);
  276. if (file_count == 0 && this->ExtraCoverageGlobs.empty()) {
  277. cmCTestOptionalLog(
  278. this->CTest, WARNING,
  279. " Cannot find any coverage files. Ignoring Coverage request."
  280. << std::endl,
  281. this->Quiet);
  282. return error;
  283. }
  284. cmGeneratedFileStream covSumFile;
  285. cmGeneratedFileStream covLogFile;
  286. cmXMLWriter covSumXML(covSumFile);
  287. cmXMLWriter covLogXML(covLogFile);
  288. if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
  289. covSumFile)) {
  290. cmCTestLog(this->CTest, ERROR_MESSAGE,
  291. "Cannot open coverage summary file." << std::endl);
  292. return -1;
  293. }
  294. covSumFile.setf(std::ios::fixed, std::ios::floatfield);
  295. covSumFile.precision(2);
  296. this->CTest->StartXML(covSumXML, this->AppendXML);
  297. // Produce output xml files
  298. covSumXML.StartElement("Coverage");
  299. covSumXML.Element("StartDateTime", coverage_start_time);
  300. covSumXML.Element("StartTime", coverage_start_time_time);
  301. int logFileCount = 0;
  302. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  303. return -1;
  304. }
  305. this->StartCoverageLogXML(covLogXML);
  306. int cnt = 0;
  307. long total_tested = 0;
  308. long total_untested = 0;
  309. // std::string fullSourceDir = sourceDir + "/";
  310. // std::string fullBinaryDir = binaryDir + "/";
  311. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  312. cmCTestOptionalLog(
  313. this->CTest, HANDLER_OUTPUT,
  314. " Accumulating results (each . represents one file):" << std::endl,
  315. this->Quiet);
  316. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  317. std::vector<std::string> errorsWhileAccumulating;
  318. file_count = 0;
  319. for (auto const& file : cont.TotalCoverage) {
  320. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  321. this->Quiet);
  322. file_count++;
  323. if (file_count % 50 == 0) {
  324. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  325. " processed: " << file_count << " out of "
  326. << cont.TotalCoverage.size()
  327. << std::endl,
  328. this->Quiet);
  329. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  330. }
  331. const std::string fullFileName = file.first;
  332. bool shouldIDoCoverage =
  333. this->ShouldIDoCoverage(fullFileName, sourceDir, binaryDir);
  334. if (!shouldIDoCoverage) {
  335. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  336. ".NoDartCoverage found, so skip coverage check for: "
  337. << fullFileName << std::endl,
  338. this->Quiet);
  339. continue;
  340. }
  341. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  342. "Process file: " << fullFileName << std::endl,
  343. this->Quiet);
  344. if (!cmSystemTools::FileExists(fullFileName)) {
  345. cmCTestLog(this->CTest, ERROR_MESSAGE,
  346. "Cannot find file: " << fullFileName << std::endl);
  347. continue;
  348. }
  349. if (++cnt % 100 == 0) {
  350. this->EndCoverageLogXML(covLogXML);
  351. this->EndCoverageLogFile(covLogFile, logFileCount);
  352. logFileCount++;
  353. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  354. return -1;
  355. }
  356. this->StartCoverageLogXML(covLogXML);
  357. }
  358. const std::string fileName = cmSystemTools::GetFilenameName(fullFileName);
  359. const std::string shortFileName =
  360. this->CTest->GetShortPathToFile(fullFileName);
  361. const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov =
  362. file.second;
  363. covLogXML.StartElement("File");
  364. covLogXML.Attribute("Name", fileName);
  365. covLogXML.Attribute("FullPath", shortFileName);
  366. covLogXML.StartElement("Report");
  367. cmsys::ifstream ifs(fullFileName.c_str());
  368. if (!ifs) {
  369. std::ostringstream ostr;
  370. ostr << "Cannot open source file: " << fullFileName;
  371. errorsWhileAccumulating.push_back(ostr.str());
  372. error++;
  373. continue;
  374. }
  375. int tested = 0;
  376. int untested = 0;
  377. cmCTestCoverageHandlerContainer::SingleFileCoverageVector::size_type cc;
  378. std::string line;
  379. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  380. "Actually performing coverage for: " << fullFileName
  381. << std::endl,
  382. this->Quiet);
  383. for (cc = 0; cc < fcov.size(); cc++) {
  384. if (!cmSystemTools::GetLineFromStream(ifs, line) &&
  385. cc != fcov.size() - 1) {
  386. std::ostringstream ostr;
  387. ostr << "Problem reading source file: " << fullFileName
  388. << " line:" << cc << " out total: " << fcov.size() - 1;
  389. errorsWhileAccumulating.push_back(ostr.str());
  390. error++;
  391. break;
  392. }
  393. covLogXML.StartElement("Line");
  394. covLogXML.Attribute("Number", cc);
  395. covLogXML.Attribute("Count", fcov[cc]);
  396. covLogXML.Content(line);
  397. covLogXML.EndElement(); // Line
  398. if (fcov[cc] == 0) {
  399. untested++;
  400. } else if (fcov[cc] > 0) {
  401. tested++;
  402. }
  403. }
  404. if (cmSystemTools::GetLineFromStream(ifs, line)) {
  405. std::ostringstream ostr;
  406. ostr << "Looks like there are more lines in the file: " << fullFileName;
  407. errorsWhileAccumulating.push_back(ostr.str());
  408. }
  409. float cper = 0;
  410. float cmet = 0;
  411. if (tested + untested > 0) {
  412. cper = (100 *
  413. SAFEDIV(static_cast<float>(tested),
  414. static_cast<float>(tested + untested)));
  415. cmet = (SAFEDIV(static_cast<float>(tested + 10),
  416. static_cast<float>(tested + untested + 10)));
  417. }
  418. total_tested += tested;
  419. total_untested += untested;
  420. covLogXML.EndElement(); // Report
  421. covLogXML.EndElement(); // File
  422. covSumXML.StartElement("File");
  423. covSumXML.Attribute("Name", fileName);
  424. covSumXML.Attribute("FullPath",
  425. this->CTest->GetShortPathToFile(fullFileName));
  426. covSumXML.Attribute("Covered", tested + untested > 0 ? "true" : "false");
  427. covSumXML.Element("LOCTested", tested);
  428. covSumXML.Element("LOCUnTested", untested);
  429. covSumXML.Element("PercentCoverage", cper);
  430. covSumXML.Element("CoverageMetric", cmet);
  431. this->WriteXMLLabels(covSumXML, shortFileName);
  432. covSumXML.EndElement(); // File
  433. }
  434. // Handle all the files in the extra coverage globs that have no cov data
  435. for (std::string const& u : uncovered) {
  436. std::string fileName = cmSystemTools::GetFilenameName(u);
  437. std::string fullPath = cont.SourceDir + "/" + u;
  438. covLogXML.StartElement("File");
  439. covLogXML.Attribute("Name", fileName);
  440. covLogXML.Attribute("FullPath", u);
  441. covLogXML.StartElement("Report");
  442. cmsys::ifstream ifs(fullPath.c_str());
  443. if (!ifs) {
  444. std::ostringstream ostr;
  445. ostr << "Cannot open source file: " << fullPath;
  446. errorsWhileAccumulating.push_back(ostr.str());
  447. error++;
  448. covLogXML.EndElement(); // Report
  449. covLogXML.EndElement(); // File
  450. continue;
  451. }
  452. int untested = 0;
  453. std::string line;
  454. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  455. "Actually performing coverage for: " << u << std::endl,
  456. this->Quiet);
  457. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  458. covLogXML.StartElement("Line");
  459. covLogXML.Attribute("Number", untested);
  460. covLogXML.Attribute("Count", 0);
  461. covLogXML.Content(line);
  462. covLogXML.EndElement(); // Line
  463. untested++;
  464. }
  465. covLogXML.EndElement(); // Report
  466. covLogXML.EndElement(); // File
  467. total_untested += untested;
  468. covSumXML.StartElement("File");
  469. covSumXML.Attribute("Name", fileName);
  470. covSumXML.Attribute("FullPath", u);
  471. covSumXML.Attribute("Covered", "true");
  472. covSumXML.Element("LOCTested", 0);
  473. covSumXML.Element("LOCUnTested", untested);
  474. covSumXML.Element("PercentCoverage", 0);
  475. covSumXML.Element("CoverageMetric", 0);
  476. this->WriteXMLLabels(covSumXML, u);
  477. covSumXML.EndElement(); // File
  478. }
  479. this->EndCoverageLogXML(covLogXML);
  480. this->EndCoverageLogFile(covLogFile, logFileCount);
  481. if (!errorsWhileAccumulating.empty()) {
  482. cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl);
  483. cmCTestLog(this->CTest, ERROR_MESSAGE,
  484. "Error(s) while accumulating results:" << std::endl);
  485. for (std::string const& er : errorsWhileAccumulating) {
  486. cmCTestLog(this->CTest, ERROR_MESSAGE, " " << er << std::endl);
  487. }
  488. }
  489. long total_lines = total_tested + total_untested;
  490. float percent_coverage = 100 *
  491. SAFEDIV(static_cast<float>(total_tested), static_cast<float>(total_lines));
  492. if (total_lines == 0) {
  493. percent_coverage = 0;
  494. }
  495. std::string end_time = this->CTest->CurrentTime();
  496. covSumXML.Element("LOCTested", total_tested);
  497. covSumXML.Element("LOCUntested", total_untested);
  498. covSumXML.Element("LOC", total_lines);
  499. covSumXML.Element("PercentCoverage", percent_coverage);
  500. covSumXML.Element("EndDateTime", end_time);
  501. covSumXML.Element("EndTime", std::chrono::system_clock::now());
  502. covSumXML.Element("ElapsedMinutes",
  503. std::chrono::duration_cast<std::chrono::minutes>(
  504. std::chrono::steady_clock::now() - elapsed_time_start)
  505. .count());
  506. covSumXML.EndElement(); // Coverage
  507. this->CTest->EndXML(covSumXML);
  508. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  509. "" << std::endl
  510. << "\tCovered LOC: " << total_tested << std::endl
  511. << "\tNot covered LOC: " << total_untested << std::endl
  512. << "\tTotal LOC: " << total_lines << std::endl
  513. << "\tPercentage Coverage: "
  514. << std::setiosflags(std::ios::fixed) << std::setprecision(2)
  515. << (percent_coverage) << "%" << std::endl);
  516. ofs << "\tCovered LOC: " << total_tested << std::endl
  517. << "\tNot covered LOC: " << total_untested << std::endl
  518. << "\tTotal LOC: " << total_lines << std::endl
  519. << "\tPercentage Coverage: " << std::setiosflags(std::ios::fixed)
  520. << std::setprecision(2) << (percent_coverage) << "%" << std::endl;
  521. if (error) {
  522. return -1;
  523. }
  524. return 0;
  525. }
  526. void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile* mf)
  527. {
  528. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  529. " Add coverage exclude regular expressions." << std::endl,
  530. this->Quiet);
  531. this->CTest->PopulateCustomVector(mf, "CTEST_CUSTOM_COVERAGE_EXCLUDE",
  532. this->CustomCoverageExclude);
  533. this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB",
  534. this->ExtraCoverageGlobs);
  535. for (std::string const& cce : this->CustomCoverageExclude) {
  536. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  537. " Add coverage exclude: " << cce << std::endl,
  538. this->Quiet);
  539. }
  540. for (std::string const& ecg : this->ExtraCoverageGlobs) {
  541. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  542. " Add coverage glob: " << ecg << std::endl,
  543. this->Quiet);
  544. }
  545. }
  546. // Fix for issue #4971 where the case of the drive letter component of
  547. // the filenames might be different when analyzing gcov output.
  548. //
  549. // Compare file names: fnc(fn1) == fnc(fn2) // fnc == file name compare
  550. //
  551. #ifdef _WIN32
  552. # define fnc(s) cmSystemTools::LowerCase(s)
  553. # define fnc_prefix(s, t) fnc(s.substr(0, t.size())) == fnc(t)
  554. #else
  555. # define fnc_prefix(s, t) cmHasPrefix(s, t)
  556. #endif
  557. static bool IsFileInDir(const std::string& infile, const std::string& indir)
  558. {
  559. std::string file = cmSystemTools::CollapseFullPath(infile);
  560. std::string dir = cmSystemTools::CollapseFullPath(indir);
  561. return file.size() > dir.size() && fnc_prefix(file, dir) &&
  562. file[dir.size()] == '/';
  563. }
  564. int cmCTestCoverageHandler::HandlePHPCoverage(
  565. cmCTestCoverageHandlerContainer* cont)
  566. {
  567. cmParsePHPCoverage cov(*cont, this->CTest);
  568. std::string coverageDir = this->CTest->GetBinaryDir() + "/xdebugCoverage";
  569. if (cmSystemTools::FileIsDirectory(coverageDir)) {
  570. cov.ReadPHPCoverageDirectory(coverageDir.c_str());
  571. }
  572. return static_cast<int>(cont->TotalCoverage.size());
  573. }
  574. int cmCTestCoverageHandler::HandleCoberturaCoverage(
  575. cmCTestCoverageHandlerContainer* cont)
  576. {
  577. cmParseCoberturaCoverage cov(*cont, this->CTest);
  578. // Assume the coverage.xml is in the binary directory
  579. // check for the COBERTURADIR environment variable,
  580. // if it doesn't exist or is empty, assume the
  581. // binary directory is used.
  582. std::string coverageXMLFile;
  583. if (!cmSystemTools::GetEnv("COBERTURADIR", coverageXMLFile) ||
  584. coverageXMLFile.empty()) {
  585. coverageXMLFile = this->CTest->GetBinaryDir();
  586. }
  587. // build the find file string with the directory from above
  588. coverageXMLFile += "/coverage.xml";
  589. if (cmSystemTools::FileExists(coverageXMLFile)) {
  590. // If file exists, parse it
  591. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  592. "Parsing Cobertura XML file: " << coverageXMLFile
  593. << std::endl,
  594. this->Quiet);
  595. cov.ReadCoverageXML(coverageXMLFile.c_str());
  596. } else {
  597. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  598. " Cannot find Cobertura XML file: " << coverageXMLFile
  599. << std::endl,
  600. this->Quiet);
  601. }
  602. return static_cast<int>(cont->TotalCoverage.size());
  603. }
  604. int cmCTestCoverageHandler::HandleMumpsCoverage(
  605. cmCTestCoverageHandlerContainer* cont)
  606. {
  607. // try gtm coverage
  608. cmParseGTMCoverage cov(*cont, this->CTest);
  609. std::string coverageFile =
  610. this->CTest->GetBinaryDir() + "/gtm_coverage.mcov";
  611. if (cmSystemTools::FileExists(coverageFile)) {
  612. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  613. "Parsing Cache Coverage: " << coverageFile << std::endl,
  614. this->Quiet);
  615. cov.ReadCoverageFile(coverageFile.c_str());
  616. return static_cast<int>(cont->TotalCoverage.size());
  617. }
  618. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  619. " Cannot find GTM coverage file: " << coverageFile
  620. << std::endl,
  621. this->Quiet);
  622. cmParseCacheCoverage ccov(*cont, this->CTest);
  623. coverageFile = this->CTest->GetBinaryDir() + "/cache_coverage.cmcov";
  624. if (cmSystemTools::FileExists(coverageFile)) {
  625. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  626. "Parsing Cache Coverage: " << coverageFile << std::endl,
  627. this->Quiet);
  628. ccov.ReadCoverageFile(coverageFile.c_str());
  629. } else {
  630. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  631. " Cannot find Cache coverage file: " << coverageFile
  632. << std::endl,
  633. this->Quiet);
  634. }
  635. return static_cast<int>(cont->TotalCoverage.size());
  636. }
  637. struct cmCTestCoverageHandlerLocale
  638. {
  639. cmCTestCoverageHandlerLocale()
  640. {
  641. std::string l;
  642. if (cmSystemTools::GetEnv("LC_ALL", l)) {
  643. this->lc_all = l;
  644. }
  645. if (this->lc_all != "C") {
  646. cmSystemTools::PutEnv("LC_ALL=C");
  647. }
  648. }
  649. ~cmCTestCoverageHandlerLocale()
  650. {
  651. if (!this->lc_all.empty()) {
  652. cmSystemTools::PutEnv("LC_ALL=" + this->lc_all);
  653. } else {
  654. cmSystemTools::UnsetEnv("LC_ALL");
  655. }
  656. }
  657. cmCTestCoverageHandlerLocale(const cmCTestCoverageHandlerLocale&) = delete;
  658. cmCTestCoverageHandlerLocale& operator=(
  659. const cmCTestCoverageHandlerLocale&) = delete;
  660. std::string lc_all;
  661. };
  662. int cmCTestCoverageHandler::HandleJacocoCoverage(
  663. cmCTestCoverageHandlerContainer* cont)
  664. {
  665. cmParseJacocoCoverage cov = cmParseJacocoCoverage(*cont, this->CTest);
  666. // Search in the source directory.
  667. cmsys::Glob g1;
  668. std::vector<std::string> files;
  669. g1.SetRecurse(true);
  670. std::string SourceDir =
  671. this->CTest->GetCTestConfiguration("SourceDirectory");
  672. std::string coverageFile = SourceDir + "/*jacoco.xml";
  673. g1.FindFiles(coverageFile);
  674. files = g1.GetFiles();
  675. // ...and in the binary directory.
  676. cmsys::Glob g2;
  677. g2.SetRecurse(true);
  678. std::string binaryDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  679. std::string binCoverageFile = binaryDir + "/*jacoco.xml";
  680. g2.FindFiles(binCoverageFile);
  681. cm::append(files, g2.GetFiles());
  682. if (!files.empty()) {
  683. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  684. "Found Jacoco Files, Performing Coverage" << std::endl,
  685. this->Quiet);
  686. cov.LoadCoverageData(files);
  687. } else {
  688. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  689. " Cannot find Jacoco coverage files: " << coverageFile
  690. << std::endl,
  691. this->Quiet);
  692. }
  693. return static_cast<int>(cont->TotalCoverage.size());
  694. }
  695. int cmCTestCoverageHandler::HandleDelphiCoverage(
  696. cmCTestCoverageHandlerContainer* cont)
  697. {
  698. cmParseDelphiCoverage cov = cmParseDelphiCoverage(*cont, this->CTest);
  699. cmsys::Glob g;
  700. std::vector<std::string> files;
  701. g.SetRecurse(true);
  702. std::string BinDir = this->CTest->GetBinaryDir();
  703. std::string coverageFile = BinDir + "/*(*.pas).html";
  704. g.FindFiles(coverageFile);
  705. files = g.GetFiles();
  706. if (!files.empty()) {
  707. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  708. "Found Delphi HTML Files, Performing Coverage"
  709. << std::endl,
  710. this->Quiet);
  711. cov.LoadCoverageData(files);
  712. } else {
  713. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  714. " Cannot find Delphi coverage files: " << coverageFile
  715. << std::endl,
  716. this->Quiet);
  717. }
  718. return static_cast<int>(cont->TotalCoverage.size());
  719. }
  720. static std::string joinCommandLine(const std::vector<std::string>& args)
  721. {
  722. std::string ret;
  723. for (std::string const& s : args) {
  724. if (s.find(' ') == std::string::npos) {
  725. ret += s + ' ';
  726. } else {
  727. ret += "\"" + s + "\" ";
  728. }
  729. }
  730. // drop trailing whitespace
  731. ret.erase(ret.size() - 1);
  732. return ret;
  733. }
  734. int cmCTestCoverageHandler::HandleBlanketJSCoverage(
  735. cmCTestCoverageHandlerContainer* cont)
  736. {
  737. cmParseBlanketJSCoverage cov = cmParseBlanketJSCoverage(*cont, this->CTest);
  738. std::string SourceDir =
  739. this->CTest->GetCTestConfiguration("SourceDirectory");
  740. // Look for something other than output.json, still JSON extension.
  741. std::string coverageFile = SourceDir + "/*.json";
  742. cmsys::Glob g;
  743. std::vector<std::string> files;
  744. std::vector<std::string> blanketFiles;
  745. g.FindFiles(coverageFile);
  746. files = g.GetFiles();
  747. // Ensure that the JSON files found are the result of the
  748. // Blanket.js output. Check for the "node-jscoverage"
  749. // string on the second line
  750. std::string line;
  751. for (std::string const& fileEntry : files) {
  752. cmsys::ifstream in(fileEntry.c_str());
  753. cmSystemTools::GetLineFromStream(in, line);
  754. cmSystemTools::GetLineFromStream(in, line);
  755. if (line.find("node-jscoverage") != std::string::npos) {
  756. blanketFiles.push_back(fileEntry);
  757. }
  758. }
  759. // Take all files with the node-jscoverage string and parse those
  760. if (!blanketFiles.empty()) {
  761. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  762. "Found BlanketJS output JSON, Performing Coverage"
  763. << std::endl,
  764. this->Quiet);
  765. cov.LoadCoverageData(files);
  766. } else {
  767. cmCTestOptionalLog(
  768. this->CTest, HANDLER_VERBOSE_OUTPUT,
  769. " Cannot find BlanketJS coverage files: " << coverageFile << std::endl,
  770. this->Quiet);
  771. }
  772. return static_cast<int>(cont->TotalCoverage.size());
  773. }
  774. int cmCTestCoverageHandler::HandleGCovCoverage(
  775. cmCTestCoverageHandlerContainer* cont)
  776. {
  777. std::string gcovCommand =
  778. this->CTest->GetCTestConfiguration("CoverageCommand");
  779. if (gcovCommand.empty()) {
  780. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  781. "Could not find gcov." << std::endl, this->Quiet);
  782. return 0;
  783. }
  784. std::string gcovExtraFlags =
  785. this->CTest->GetCTestConfiguration("CoverageExtraFlags");
  786. // Immediately skip to next coverage option since codecov is only for Intel
  787. // compiler
  788. if (gcovCommand == "codecov") {
  789. return 0;
  790. }
  791. // Style 1
  792. std::string st1gcovOutputRex1 =
  793. "[0-9]+\\.[0-9]+% of [0-9]+ (source |)lines executed in file (.*)$";
  794. std::string st1gcovOutputRex2 = "^Creating (.*\\.gcov)\\.";
  795. cmsys::RegularExpression st1re1(st1gcovOutputRex1.c_str());
  796. cmsys::RegularExpression st1re2(st1gcovOutputRex2.c_str());
  797. // Style 2
  798. std::string st2gcovOutputRex1 = "^File *[`'](.*)'$";
  799. std::string st2gcovOutputRex2 =
  800. "Lines executed: *[0-9]+\\.[0-9]+% of [0-9]+$";
  801. std::string st2gcovOutputRex3 = "^(.*)reating [`'](.*\\.gcov)'";
  802. std::string st2gcovOutputRex4 = "^(.*):unexpected EOF *$";
  803. std::string st2gcovOutputRex5 = "^(.*):cannot open source file*$";
  804. std::string st2gcovOutputRex6 =
  805. "^(.*):source file is newer than graph file `(.*)'$";
  806. cmsys::RegularExpression st2re1(st2gcovOutputRex1.c_str());
  807. cmsys::RegularExpression st2re2(st2gcovOutputRex2.c_str());
  808. cmsys::RegularExpression st2re3(st2gcovOutputRex3.c_str());
  809. cmsys::RegularExpression st2re4(st2gcovOutputRex4.c_str());
  810. cmsys::RegularExpression st2re5(st2gcovOutputRex5.c_str());
  811. cmsys::RegularExpression st2re6(st2gcovOutputRex6.c_str());
  812. std::vector<std::string> files;
  813. this->FindGCovFiles(files);
  814. if (files.empty()) {
  815. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  816. " Cannot find any GCov coverage files." << std::endl,
  817. this->Quiet);
  818. // No coverage files is a valid thing, so the exit code is 0
  819. return 0;
  820. }
  821. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  822. std::string tempDir = testingDir + "/CoverageInfo";
  823. if (!cmSystemTools::MakeDirectory(tempDir)) {
  824. cmCTestLog(this->CTest, ERROR_MESSAGE,
  825. "Unable to make directory: " << tempDir << std::endl);
  826. cont->Error++;
  827. return 0;
  828. }
  829. cmWorkingDirectory workdir(tempDir);
  830. int gcovStyle = 0;
  831. std::set<std::string> missingFiles;
  832. std::string actualSourceFile;
  833. cmCTestOptionalLog(
  834. this->CTest, HANDLER_OUTPUT,
  835. " Processing coverage (each . represents one file):" << std::endl,
  836. this->Quiet);
  837. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  838. int file_count = 0;
  839. // make sure output from gcov is in English!
  840. cmCTestCoverageHandlerLocale locale_C;
  841. static_cast<void>(locale_C);
  842. std::vector<std::string> basecovargs =
  843. cmSystemTools::ParseArguments(gcovExtraFlags);
  844. basecovargs.insert(basecovargs.begin(), gcovCommand);
  845. basecovargs.emplace_back("-o");
  846. // files is a list of *.da and *.gcda files with coverage data in them.
  847. // These are binary files that you give as input to gcov so that it will
  848. // give us text output we can analyze to summarize coverage.
  849. //
  850. for (std::string const& f : files) {
  851. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  852. this->Quiet);
  853. // Call gcov to get coverage data for this *.gcda file:
  854. //
  855. std::string fileDir = cmSystemTools::GetFilenamePath(f);
  856. std::vector<std::string> covargs = basecovargs;
  857. covargs.push_back(fileDir);
  858. covargs.push_back(f);
  859. const std::string command = joinCommandLine(covargs);
  860. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  861. command << std::endl, this->Quiet);
  862. std::string output;
  863. std::string errors;
  864. int retVal = 0;
  865. *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
  866. *cont->OFS << " Command: " << command << std::endl;
  867. int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
  868. tempDir.c_str(),
  869. cmDuration::zero() /*this->TimeOut*/);
  870. *cont->OFS << " Output: " << output << std::endl;
  871. *cont->OFS << " Errors: " << errors << std::endl;
  872. if (!res) {
  873. cmCTestLog(this->CTest, ERROR_MESSAGE,
  874. "Problem running coverage on file: " << f << std::endl);
  875. cmCTestLog(this->CTest, ERROR_MESSAGE,
  876. "Command produced error: " << errors << std::endl);
  877. cont->Error++;
  878. continue;
  879. }
  880. if (retVal != 0) {
  881. cmCTestLog(this->CTest, ERROR_MESSAGE,
  882. "Coverage command returned: "
  883. << retVal << " while processing: " << f << std::endl);
  884. cmCTestLog(this->CTest, ERROR_MESSAGE,
  885. "Command produced error: " << cont->Error << std::endl);
  886. }
  887. cmCTestOptionalLog(
  888. this->CTest, HANDLER_VERBOSE_OUTPUT,
  889. "--------------------------------------------------------------"
  890. << std::endl
  891. << output << std::endl
  892. << "--------------------------------------------------------------"
  893. << std::endl,
  894. this->Quiet);
  895. std::vector<std::string> lines;
  896. cmsys::SystemTools::Split(output, lines);
  897. for (std::string const& line : lines) {
  898. std::string sourceFile;
  899. std::string gcovFile;
  900. cmCTestOptionalLog(this->CTest, DEBUG,
  901. "Line: [" << line << "]" << std::endl, this->Quiet);
  902. if (line.empty()) {
  903. // Ignore empty line; probably style 2
  904. } else if (st1re1.find(line)) {
  905. if (gcovStyle == 0) {
  906. gcovStyle = 1;
  907. }
  908. if (gcovStyle != 1) {
  909. cmCTestLog(this->CTest, ERROR_MESSAGE,
  910. "Unknown gcov output style e1" << std::endl);
  911. cont->Error++;
  912. break;
  913. }
  914. actualSourceFile.clear();
  915. sourceFile = st1re1.match(2);
  916. } else if (st1re2.find(line)) {
  917. if (gcovStyle == 0) {
  918. gcovStyle = 1;
  919. }
  920. if (gcovStyle != 1) {
  921. cmCTestLog(this->CTest, ERROR_MESSAGE,
  922. "Unknown gcov output style e2" << std::endl);
  923. cont->Error++;
  924. break;
  925. }
  926. gcovFile = st1re2.match(1);
  927. } else if (st2re1.find(line)) {
  928. if (gcovStyle == 0) {
  929. gcovStyle = 2;
  930. }
  931. if (gcovStyle != 2) {
  932. cmCTestLog(this->CTest, ERROR_MESSAGE,
  933. "Unknown gcov output style e3" << std::endl);
  934. cont->Error++;
  935. break;
  936. }
  937. actualSourceFile.clear();
  938. sourceFile = st2re1.match(1);
  939. } else if (st2re2.find(line)) {
  940. if (gcovStyle == 0) {
  941. gcovStyle = 2;
  942. }
  943. if (gcovStyle != 2) {
  944. cmCTestLog(this->CTest, ERROR_MESSAGE,
  945. "Unknown gcov output style e4" << std::endl);
  946. cont->Error++;
  947. break;
  948. }
  949. } else if (st2re3.find(line)) {
  950. if (gcovStyle == 0) {
  951. gcovStyle = 2;
  952. }
  953. if (gcovStyle != 2) {
  954. cmCTestLog(this->CTest, ERROR_MESSAGE,
  955. "Unknown gcov output style e5" << std::endl);
  956. cont->Error++;
  957. break;
  958. }
  959. gcovFile = st2re3.match(2);
  960. } else if (st2re4.find(line)) {
  961. if (gcovStyle == 0) {
  962. gcovStyle = 2;
  963. }
  964. if (gcovStyle != 2) {
  965. cmCTestLog(this->CTest, ERROR_MESSAGE,
  966. "Unknown gcov output style e6" << std::endl);
  967. cont->Error++;
  968. break;
  969. }
  970. cmCTestOptionalLog(this->CTest, WARNING,
  971. "Warning: " << st2re4.match(1)
  972. << " had unexpected EOF" << std::endl,
  973. this->Quiet);
  974. } else if (st2re5.find(line)) {
  975. if (gcovStyle == 0) {
  976. gcovStyle = 2;
  977. }
  978. if (gcovStyle != 2) {
  979. cmCTestLog(this->CTest, ERROR_MESSAGE,
  980. "Unknown gcov output style e7" << std::endl);
  981. cont->Error++;
  982. break;
  983. }
  984. cmCTestOptionalLog(this->CTest, WARNING,
  985. "Warning: Cannot open file: " << st2re5.match(1)
  986. << std::endl,
  987. this->Quiet);
  988. } else if (st2re6.find(line)) {
  989. if (gcovStyle == 0) {
  990. gcovStyle = 2;
  991. }
  992. if (gcovStyle != 2) {
  993. cmCTestLog(this->CTest, ERROR_MESSAGE,
  994. "Unknown gcov output style e8" << std::endl);
  995. cont->Error++;
  996. break;
  997. }
  998. cmCTestOptionalLog(this->CTest, WARNING,
  999. "Warning: File: " << st2re6.match(1)
  1000. << " is newer than "
  1001. << st2re6.match(2) << std::endl,
  1002. this->Quiet);
  1003. } else {
  1004. // gcov 4.7 can have output lines saying "No executable lines" and
  1005. // "Removing 'filename.gcov'"... Don't log those as "errors."
  1006. if (line != "No executable lines" &&
  1007. !cmHasLiteralPrefix(line, "Removing ")) {
  1008. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1009. "Unknown gcov output line: [" << line << "]"
  1010. << std::endl);
  1011. cont->Error++;
  1012. // abort();
  1013. }
  1014. }
  1015. // If the last line of gcov output gave us a valid value for gcovFile,
  1016. // and we have an actualSourceFile, then insert a (or add to existing)
  1017. // SingleFileCoverageVector for actualSourceFile:
  1018. //
  1019. if (!gcovFile.empty() && !actualSourceFile.empty()) {
  1020. cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
  1021. cont->TotalCoverage[actualSourceFile];
  1022. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1023. " in gcovFile: " << gcovFile << std::endl,
  1024. this->Quiet);
  1025. cmsys::ifstream ifile(gcovFile.c_str());
  1026. if (!ifile) {
  1027. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1028. "Cannot open file: " << gcovFile << std::endl);
  1029. } else {
  1030. std::string nl;
  1031. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1032. // Skip empty lines
  1033. if (nl.empty()) {
  1034. continue;
  1035. }
  1036. // Skip unused lines
  1037. if (nl.size() < 12) {
  1038. continue;
  1039. }
  1040. // Handle gcov 3.0 non-coverage lines
  1041. // non-coverage lines seem to always start with something not
  1042. // a space and don't have a ':' in the 9th position
  1043. // TODO: Verify that this is actually a robust metric
  1044. if (nl[0] != ' ' && nl[9] != ':') {
  1045. continue;
  1046. }
  1047. // Read the coverage count from the beginning of the gcov output
  1048. // line
  1049. std::string prefix = nl.substr(0, 12);
  1050. int cov = atoi(prefix.c_str());
  1051. // Read the line number starting at the 10th character of the gcov
  1052. // output line
  1053. std::string lineNumber = nl.substr(10, 5);
  1054. int lineIdx = atoi(lineNumber.c_str()) - 1;
  1055. if (lineIdx >= 0) {
  1056. while (vec.size() <= static_cast<size_t>(lineIdx)) {
  1057. vec.push_back(-1);
  1058. }
  1059. // Initially all entries are -1 (not used). If we get coverage
  1060. // information, increment it to 0 first.
  1061. if (vec[lineIdx] < 0) {
  1062. if (cov > 0 || prefix.find('#') != std::string::npos) {
  1063. vec[lineIdx] = 0;
  1064. }
  1065. }
  1066. vec[lineIdx] += cov;
  1067. }
  1068. }
  1069. }
  1070. actualSourceFile.clear();
  1071. }
  1072. if (!sourceFile.empty() && actualSourceFile.empty()) {
  1073. gcovFile.clear();
  1074. // Is it in the source dir or the binary dir?
  1075. //
  1076. if (IsFileInDir(sourceFile, cont->SourceDir)) {
  1077. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1078. " produced s: " << sourceFile << std::endl,
  1079. this->Quiet);
  1080. *cont->OFS << " produced in source dir: " << sourceFile
  1081. << std::endl;
  1082. actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
  1083. } else if (IsFileInDir(sourceFile, cont->BinaryDir)) {
  1084. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1085. " produced b: " << sourceFile << std::endl,
  1086. this->Quiet);
  1087. *cont->OFS << " produced in binary dir: " << sourceFile
  1088. << std::endl;
  1089. actualSourceFile = cmSystemTools::CollapseFullPath(sourceFile);
  1090. }
  1091. if (actualSourceFile.empty()) {
  1092. if (missingFiles.find(sourceFile) == missingFiles.end()) {
  1093. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1094. "Something went wrong" << std::endl,
  1095. this->Quiet);
  1096. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1097. "Cannot find file: [" << sourceFile << "]"
  1098. << std::endl,
  1099. this->Quiet);
  1100. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1101. " in source dir: [" << cont->SourceDir << "]"
  1102. << std::endl,
  1103. this->Quiet);
  1104. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1105. " or binary dir: [" << cont->BinaryDir.size()
  1106. << "]" << std::endl,
  1107. this->Quiet);
  1108. *cont->OFS << " Something went wrong. Cannot find file: "
  1109. << sourceFile << " in source dir: " << cont->SourceDir
  1110. << " or binary dir: " << cont->BinaryDir << std::endl;
  1111. missingFiles.insert(sourceFile);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. file_count++;
  1117. if (file_count % 50 == 0) {
  1118. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1119. " processed: " << file_count << " out of "
  1120. << files.size() << std::endl,
  1121. this->Quiet);
  1122. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1123. }
  1124. }
  1125. return file_count;
  1126. }
  1127. int cmCTestCoverageHandler::HandleLCovCoverage(
  1128. cmCTestCoverageHandlerContainer* cont)
  1129. {
  1130. std::string lcovCommand =
  1131. this->CTest->GetCTestConfiguration("CoverageCommand");
  1132. std::string lcovExtraFlags =
  1133. this->CTest->GetCTestConfiguration("CoverageExtraFlags");
  1134. if (lcovCommand != "codecov") {
  1135. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1136. " Not a valid Intel Coverage command." << std::endl,
  1137. this->Quiet);
  1138. return 0;
  1139. }
  1140. // There is only percentage completed output from LCOV
  1141. std::string st2lcovOutputRex3 = "[0-9]+%";
  1142. cmsys::RegularExpression st2re3(st2lcovOutputRex3.c_str());
  1143. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1144. " This is coverage command: " << lcovCommand << std::endl,
  1145. this->Quiet);
  1146. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1147. " These are coverage command flags: " << lcovExtraFlags
  1148. << std::endl,
  1149. this->Quiet);
  1150. std::vector<std::string> files;
  1151. if (!this->FindLCovFiles(files)) {
  1152. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1153. "Error while finding LCov files.\n");
  1154. return 0;
  1155. }
  1156. if (files.empty()) {
  1157. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1158. " Cannot find any LCov coverage files." << std::endl,
  1159. this->Quiet);
  1160. // No coverage files is a valid thing, so the exit code is 0
  1161. return 0;
  1162. }
  1163. std::string testingDir = this->CTest->GetBinaryDir();
  1164. std::set<std::string> missingFiles;
  1165. std::string actualSourceFile;
  1166. cmCTestOptionalLog(
  1167. this->CTest, HANDLER_OUTPUT,
  1168. " Processing coverage (each . represents one file):" << std::endl,
  1169. this->Quiet);
  1170. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1171. int file_count = 0;
  1172. // make sure output from lcov is in English!
  1173. cmCTestCoverageHandlerLocale locale_C;
  1174. static_cast<void>(locale_C);
  1175. std::vector<std::string> covargs =
  1176. cmSystemTools::ParseArguments(lcovExtraFlags);
  1177. covargs.insert(covargs.begin(), lcovCommand);
  1178. const std::string command = joinCommandLine(covargs);
  1179. // In intel compiler we have to call codecov only once in each executable
  1180. // directory. It collects all *.dyn files to generate .dpi file.
  1181. for (std::string const& f : files) {
  1182. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
  1183. this->Quiet);
  1184. std::string fileDir = cmSystemTools::GetFilenamePath(f);
  1185. cmWorkingDirectory workdir(fileDir);
  1186. if (workdir.Failed()) {
  1187. cmCTestLog(this->CTest, ERROR_MESSAGE, workdir.GetError() << std::endl);
  1188. cont->Error++;
  1189. continue;
  1190. }
  1191. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1192. "Current coverage dir: " << fileDir << std::endl,
  1193. this->Quiet);
  1194. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1195. command << std::endl, this->Quiet);
  1196. std::string output;
  1197. std::string errors;
  1198. int retVal = 0;
  1199. *cont->OFS << "* Run coverage for: " << fileDir << std::endl;
  1200. *cont->OFS << " Command: " << command << std::endl;
  1201. int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
  1202. fileDir.c_str(),
  1203. cmDuration::zero() /*this->TimeOut*/);
  1204. *cont->OFS << " Output: " << output << std::endl;
  1205. *cont->OFS << " Errors: " << errors << std::endl;
  1206. if (!res) {
  1207. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1208. "Problem running coverage on file: " << f << std::endl);
  1209. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1210. "Command produced error: " << errors << std::endl);
  1211. cont->Error++;
  1212. continue;
  1213. }
  1214. if (retVal != 0) {
  1215. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1216. "Coverage command returned: "
  1217. << retVal << " while processing: " << f << std::endl);
  1218. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1219. "Command produced error: " << cont->Error << std::endl);
  1220. }
  1221. cmCTestOptionalLog(
  1222. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1223. "--------------------------------------------------------------"
  1224. << std::endl
  1225. << output << std::endl
  1226. << "--------------------------------------------------------------"
  1227. << std::endl,
  1228. this->Quiet);
  1229. std::vector<std::string> lines;
  1230. cmsys::SystemTools::Split(output, lines);
  1231. for (std::string const& line : lines) {
  1232. std::string sourceFile;
  1233. std::string lcovFile;
  1234. if (line.empty()) {
  1235. // Ignore empty line
  1236. }
  1237. // Look for LCOV files in binary directory
  1238. // Intel Compiler creates a CodeCoverage dir for each subfolder and
  1239. // each subfolder has LCOV files
  1240. cmsys::Glob gl;
  1241. gl.RecurseOn();
  1242. gl.RecurseThroughSymlinksOff();
  1243. std::string dir;
  1244. std::vector<std::string> lcovFiles;
  1245. dir = this->CTest->GetBinaryDir();
  1246. std::string daGlob;
  1247. daGlob = cmStrCat(dir, "/*.LCOV");
  1248. cmCTestOptionalLog(
  1249. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1250. " looking for LCOV files in: " << daGlob << std::endl, this->Quiet);
  1251. gl.FindFiles(daGlob);
  1252. // Keep a list of all LCOV files
  1253. cm::append(lcovFiles, gl.GetFiles());
  1254. for (std::string const& file : lcovFiles) {
  1255. lcovFile = file;
  1256. cmsys::ifstream srcead(lcovFile.c_str());
  1257. if (!srcead) {
  1258. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1259. "Cannot open file: " << lcovFile << std::endl);
  1260. }
  1261. std::string srcname;
  1262. int success = cmSystemTools::GetLineFromStream(srcead, srcname);
  1263. if (!success) {
  1264. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1265. "Error while parsing lcov file '"
  1266. << lcovFile << "':"
  1267. << " No source file name found!" << std::endl);
  1268. return 0;
  1269. }
  1270. srcname = srcname.substr(18);
  1271. // We can directly read found LCOV files to determine the source
  1272. // files
  1273. sourceFile = srcname;
  1274. actualSourceFile = srcname;
  1275. for (std::string const& t : lcovFiles) {
  1276. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1277. "Found LCOV File: " << t << std::endl,
  1278. this->Quiet);
  1279. }
  1280. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1281. "SourceFile: " << sourceFile << std::endl,
  1282. this->Quiet);
  1283. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1284. "lCovFile: " << lcovFile << std::endl, this->Quiet);
  1285. // If we have some LCOV files to process
  1286. if (!lcovFile.empty() && !actualSourceFile.empty()) {
  1287. cmCTestCoverageHandlerContainer::SingleFileCoverageVector& vec =
  1288. cont->TotalCoverage[actualSourceFile];
  1289. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1290. " in lcovFile: " << lcovFile << std::endl,
  1291. this->Quiet);
  1292. cmsys::ifstream ifile(lcovFile.c_str());
  1293. if (!ifile) {
  1294. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1295. "Cannot open file: " << lcovFile << std::endl);
  1296. } else {
  1297. std::string nl;
  1298. // Skip the first line
  1299. cmSystemTools::GetLineFromStream(ifile, nl);
  1300. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1301. "File is ready, start reading." << std::endl,
  1302. this->Quiet);
  1303. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1304. // Skip empty lines
  1305. if (nl.empty()) {
  1306. continue;
  1307. }
  1308. // Skip unused lines
  1309. if (nl.size() < 12) {
  1310. continue;
  1311. }
  1312. // Read the coverage count from the beginning of the lcov
  1313. // output line
  1314. std::string prefix = nl.substr(0, 17);
  1315. int cov = atoi(prefix.c_str());
  1316. // Read the line number starting at the 17th character of the
  1317. // lcov output line
  1318. std::string lineNumber = nl.substr(17, 7);
  1319. int lineIdx = atoi(lineNumber.c_str()) - 1;
  1320. if (lineIdx >= 0) {
  1321. while (vec.size() <= static_cast<size_t>(lineIdx)) {
  1322. vec.push_back(-1);
  1323. }
  1324. // Initially all entries are -1 (not used). If we get coverage
  1325. // information, increment it to 0 first.
  1326. if (vec[lineIdx] < 0) {
  1327. if (cov > 0 || prefix.find('#') != std::string::npos) {
  1328. vec[lineIdx] = 0;
  1329. }
  1330. }
  1331. vec[lineIdx] += cov;
  1332. }
  1333. }
  1334. }
  1335. actualSourceFile.clear();
  1336. }
  1337. }
  1338. }
  1339. file_count++;
  1340. if (file_count % 50 == 0) {
  1341. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1342. " processed: " << file_count << " out of "
  1343. << files.size() << std::endl,
  1344. this->Quiet);
  1345. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
  1346. }
  1347. }
  1348. return file_count;
  1349. }
  1350. void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
  1351. {
  1352. cmsys::Glob gl;
  1353. gl.RecurseOn();
  1354. gl.RecurseThroughSymlinksOff();
  1355. for (auto const& lm : this->TargetDirs) {
  1356. // Skip targets containing no interesting labels.
  1357. if (!this->IntersectsFilter(lm.second)) {
  1358. continue;
  1359. }
  1360. // Coverage files appear next to their object files in the target
  1361. // support directory.
  1362. cmCTestOptionalLog(
  1363. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1364. " globbing for coverage in: " << lm.first << std::endl, this->Quiet);
  1365. std::string daGlob = cmStrCat(lm.first, "/*.da");
  1366. gl.FindFiles(daGlob);
  1367. cm::append(files, gl.GetFiles());
  1368. daGlob = cmStrCat(lm.first, "/*.gcda");
  1369. gl.FindFiles(daGlob);
  1370. cm::append(files, gl.GetFiles());
  1371. }
  1372. }
  1373. bool cmCTestCoverageHandler::FindLCovFiles(std::vector<std::string>& files)
  1374. {
  1375. cmsys::Glob gl;
  1376. gl.RecurseOff(); // No need of recurse if -prof_dir${BUILD_DIR} flag is
  1377. // used while compiling.
  1378. gl.RecurseThroughSymlinksOff();
  1379. std::string buildDir = this->CTest->GetCTestConfiguration("BuildDirectory");
  1380. cmWorkingDirectory workdir(buildDir);
  1381. if (workdir.Failed()) {
  1382. cmCTestLog(this->CTest, ERROR_MESSAGE, workdir.GetError() << std::endl);
  1383. return false;
  1384. }
  1385. // Run profmerge to merge all *.dyn files into dpi files
  1386. if (!cmSystemTools::RunSingleCommand("profmerge")) {
  1387. cmCTestLog(this->CTest, ERROR_MESSAGE, "Error while running profmerge.\n");
  1388. return false;
  1389. }
  1390. // DPI file should appear in build directory
  1391. std::string daGlob;
  1392. daGlob = cmStrCat(buildDir, "/*.dpi");
  1393. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1394. " looking for dpi files in: " << daGlob << std::endl,
  1395. this->Quiet);
  1396. if (!gl.FindFiles(daGlob)) {
  1397. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1398. "Error while finding files matching " << daGlob << std::endl);
  1399. return false;
  1400. }
  1401. cm::append(files, gl.GetFiles());
  1402. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1403. "Now searching in: " << daGlob << std::endl, this->Quiet);
  1404. return true;
  1405. }
  1406. int cmCTestCoverageHandler::HandleTracePyCoverage(
  1407. cmCTestCoverageHandlerContainer* cont)
  1408. {
  1409. cmsys::Glob gl;
  1410. gl.RecurseOn();
  1411. gl.RecurseThroughSymlinksOff();
  1412. std::string daGlob = cont->BinaryDir + "/*.cover";
  1413. gl.FindFiles(daGlob);
  1414. std::vector<std::string> files = gl.GetFiles();
  1415. if (files.empty()) {
  1416. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1417. " Cannot find any Python Trace.py coverage files."
  1418. << std::endl,
  1419. this->Quiet);
  1420. // No coverage files is a valid thing, so the exit code is 0
  1421. return 0;
  1422. }
  1423. std::string testingDir = this->CTest->GetBinaryDir() + "/Testing";
  1424. std::string tempDir = testingDir + "/CoverageInfo";
  1425. cmSystemTools::MakeDirectory(tempDir);
  1426. int file_count = 0;
  1427. for (std::string const& file : files) {
  1428. std::string fileName = this->FindFile(cont, file);
  1429. if (fileName.empty()) {
  1430. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1431. "Cannot find source Python file corresponding to: "
  1432. << file << std::endl);
  1433. continue;
  1434. }
  1435. std::string actualSourceFile = cmSystemTools::CollapseFullPath(fileName);
  1436. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1437. " Check coverage for file: " << actualSourceFile
  1438. << std::endl,
  1439. this->Quiet);
  1440. cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec =
  1441. &cont->TotalCoverage[actualSourceFile];
  1442. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1443. " in file: " << file << std::endl, this->Quiet);
  1444. cmsys::ifstream ifile(file.c_str());
  1445. if (!ifile) {
  1446. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1447. "Cannot open file: " << file << std::endl);
  1448. } else {
  1449. long cnt = -1;
  1450. std::string nl;
  1451. while (cmSystemTools::GetLineFromStream(ifile, nl)) {
  1452. cnt++;
  1453. // Skip empty lines
  1454. if (nl.empty()) {
  1455. continue;
  1456. }
  1457. // Skip unused lines
  1458. if (nl.size() < 12) {
  1459. continue;
  1460. }
  1461. // Read the coverage count from the beginning of the Trace.py output
  1462. // line
  1463. std::string::size_type pos;
  1464. int cov = 0;
  1465. // This is a hack. We should really do something more elaborate
  1466. for (pos = 5; pos < 8; pos++) {
  1467. if (nl[pos] == ' ') {
  1468. // This line does not have ':' so no coverage here. That said,
  1469. // Trace.py does not handle not covered lines versus comments etc.
  1470. // So, this will be set to 0.
  1471. break;
  1472. }
  1473. if (nl[pos] == ':') {
  1474. cov = atoi(nl.substr(0, pos - 1).c_str());
  1475. break;
  1476. }
  1477. }
  1478. if (pos == 8) {
  1479. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1480. "Currently the limit is maximum coverage of 999999"
  1481. << std::endl);
  1482. }
  1483. // Read the line number starting at the 10th character of the gcov
  1484. // output line
  1485. long lineIdx = cnt;
  1486. if (lineIdx >= 0) {
  1487. while (vec->size() <= static_cast<size_t>(lineIdx)) {
  1488. vec->push_back(-1);
  1489. }
  1490. // Initially all entries are -1 (not used). If we get coverage
  1491. // information, increment it to 0 first.
  1492. if ((*vec)[lineIdx] < 0) {
  1493. if (cov >= 0) {
  1494. (*vec)[lineIdx] = 0;
  1495. }
  1496. }
  1497. (*vec)[lineIdx] += cov;
  1498. }
  1499. }
  1500. }
  1501. ++file_count;
  1502. }
  1503. return file_count;
  1504. }
  1505. std::string cmCTestCoverageHandler::FindFile(
  1506. cmCTestCoverageHandlerContainer* cont, std::string const& fileName)
  1507. {
  1508. std::string fileNameNoE =
  1509. cmSystemTools::GetFilenameWithoutLastExtension(fileName);
  1510. // First check in source and binary directory
  1511. std::string fullName = cont->SourceDir + "/" + fileNameNoE + ".py";
  1512. if (cmSystemTools::FileExists(fullName)) {
  1513. return fullName;
  1514. }
  1515. fullName = cont->BinaryDir + "/" + fileNameNoE + ".py";
  1516. if (cmSystemTools::FileExists(fullName)) {
  1517. return fullName;
  1518. }
  1519. return "";
  1520. }
  1521. // This is a header put on each marked up source file
  1522. namespace {
  1523. const char* bullseyeHelp[] = {
  1524. " Coverage produced by bullseye covbr tool: ",
  1525. " www.bullseye.com/help/ref_covbr.html",
  1526. " * An arrow --> indicates incomplete coverage.",
  1527. " * An X indicates a function that was invoked, a switch label that ",
  1528. " was exercised, a try-block that finished, or an exception handler ",
  1529. " that was invoked.",
  1530. " * A T or F indicates a boolean decision that evaluated true or false,",
  1531. " respectively.",
  1532. " * A t or f indicates a boolean condition within a decision if the ",
  1533. " condition evaluated true or false, respectively.",
  1534. " * A k indicates a constant decision or condition.",
  1535. " * The slash / means this probe is excluded from summary results. ",
  1536. nullptr
  1537. };
  1538. }
  1539. int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
  1540. cmCTestCoverageHandlerContainer* cont,
  1541. std::set<std::string>& coveredFileNames, std::vector<std::string>& files,
  1542. std::vector<std::string>& filesFullPath)
  1543. {
  1544. if (files.size() != filesFullPath.size()) {
  1545. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1546. "Files and full path files not the same size?:\n");
  1547. return 0;
  1548. }
  1549. // create the output stream for the CoverageLog-N.xml file
  1550. cmGeneratedFileStream covLogFile;
  1551. cmXMLWriter covLogXML(covLogFile);
  1552. int logFileCount = 0;
  1553. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  1554. return -1;
  1555. }
  1556. this->StartCoverageLogXML(covLogXML);
  1557. // for each file run covbr on that file to get the coverage
  1558. // information for that file
  1559. std::string outputFile;
  1560. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1561. "run covbr: " << std::endl, this->Quiet);
  1562. if (!this->RunBullseyeCommand(cont, "covbr", nullptr, outputFile)) {
  1563. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1564. "error running covbr for."
  1565. << "\n");
  1566. return -1;
  1567. }
  1568. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1569. "covbr output in " << outputFile << std::endl,
  1570. this->Quiet);
  1571. // open the output file
  1572. cmsys::ifstream fin(outputFile.c_str());
  1573. if (!fin) {
  1574. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1575. "Cannot open coverage file: " << outputFile << std::endl);
  1576. return 0;
  1577. }
  1578. std::map<std::string, std::string> fileMap;
  1579. auto fp = filesFullPath.begin();
  1580. for (auto f = files.begin(); f != files.end(); ++f, ++fp) {
  1581. fileMap[*f] = *fp;
  1582. }
  1583. int count = 0; // keep count of the number of files
  1584. // Now parse each line from the bullseye cov log file
  1585. std::string lineIn;
  1586. bool valid = false; // are we in a valid output file
  1587. int line = 0; // line of the current file
  1588. std::string file;
  1589. while (cmSystemTools::GetLineFromStream(fin, lineIn)) {
  1590. bool startFile = false;
  1591. if (lineIn.size() > 1 && lineIn[lineIn.size() - 1] == ':') {
  1592. file = lineIn.substr(0, lineIn.size() - 1);
  1593. if (coveredFileNames.find(file) != coveredFileNames.end()) {
  1594. startFile = true;
  1595. }
  1596. }
  1597. if (startFile) {
  1598. // if we are in a valid file close it because a new one started
  1599. if (valid) {
  1600. covLogXML.EndElement(); // Report
  1601. covLogXML.EndElement(); // File
  1602. }
  1603. // only allow 100 files in each log file
  1604. if (count != 0 && count % 100 == 0) {
  1605. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1606. "start a new log file: " << count << std::endl,
  1607. this->Quiet);
  1608. this->EndCoverageLogXML(covLogXML);
  1609. this->EndCoverageLogFile(covLogFile, logFileCount);
  1610. logFileCount++;
  1611. if (!this->StartCoverageLogFile(covLogFile, logFileCount)) {
  1612. return -1;
  1613. }
  1614. this->StartCoverageLogXML(covLogXML);
  1615. count++; // move on one
  1616. }
  1617. auto i = fileMap.find(file);
  1618. // if the file should be covered write out the header for that file
  1619. if (i != fileMap.end()) {
  1620. // we have a new file so count it in the output
  1621. count++;
  1622. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1623. "Produce coverage for file: " << file << " "
  1624. << count << std::endl,
  1625. this->Quiet);
  1626. // start the file output
  1627. covLogXML.StartElement("File");
  1628. covLogXML.Attribute("Name", i->first);
  1629. covLogXML.Attribute("FullPath",
  1630. this->CTest->GetShortPathToFile(i->second));
  1631. covLogXML.StartElement("Report");
  1632. // write the bullseye header
  1633. line = 0;
  1634. for (int k = 0; bullseyeHelp[k]; ++k) {
  1635. covLogXML.StartElement("Line");
  1636. covLogXML.Attribute("Number", line);
  1637. covLogXML.Attribute("Count", -1);
  1638. covLogXML.Content(bullseyeHelp[k]);
  1639. covLogXML.EndElement(); // Line
  1640. line++;
  1641. }
  1642. valid = true; // we are in a valid file section
  1643. } else {
  1644. // this is not a file that we want coverage for
  1645. valid = false;
  1646. }
  1647. }
  1648. // we are not at a start file, and we are in a valid file output the line
  1649. else if (valid) {
  1650. covLogXML.StartElement("Line");
  1651. covLogXML.Attribute("Number", line);
  1652. covLogXML.Attribute("Count", -1);
  1653. covLogXML.Content(lineIn);
  1654. covLogXML.EndElement(); // Line
  1655. line++;
  1656. }
  1657. }
  1658. // if we ran out of lines a valid file then close that file
  1659. if (valid) {
  1660. covLogXML.EndElement(); // Report
  1661. covLogXML.EndElement(); // File
  1662. }
  1663. this->EndCoverageLogXML(covLogXML);
  1664. this->EndCoverageLogFile(covLogFile, logFileCount);
  1665. return 1;
  1666. }
  1667. int cmCTestCoverageHandler::RunBullseyeCommand(
  1668. cmCTestCoverageHandlerContainer* cont, const char* cmd, const char* arg,
  1669. std::string& outputFile)
  1670. {
  1671. std::string program = cmSystemTools::FindProgram(cmd);
  1672. if (program.empty()) {
  1673. cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find :" << cmd << "\n");
  1674. return 0;
  1675. }
  1676. std::vector<std::string> args{ cmd };
  1677. if (arg) {
  1678. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1679. "Run : " << program << " " << arg << "\n", this->Quiet);
  1680. args.emplace_back(arg);
  1681. } else {
  1682. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1683. "Run : " << program << "\n", this->Quiet);
  1684. }
  1685. // create a process object and start it
  1686. cmUVProcessChainBuilder builder;
  1687. std::string stdoutFile =
  1688. cmStrCat(cont->BinaryDir, "/Testing/Temporary/",
  1689. this->GetCTestInstance()->GetCurrentTag(), '-', cmd);
  1690. std::string stderrFile = stdoutFile;
  1691. stdoutFile += ".stdout";
  1692. stderrFile += ".stderr";
  1693. std::unique_ptr<FILE, int (*)(FILE*)> stdoutHandle(
  1694. cmsys::SystemTools::Fopen(stdoutFile, "w"), fclose);
  1695. std::unique_ptr<FILE, int (*)(FILE*)> stderrHandle(
  1696. cmsys::SystemTools::Fopen(stderrFile, "w"), fclose);
  1697. builder.AddCommand(args)
  1698. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1699. stdoutHandle.get())
  1700. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  1701. stderrHandle.get());
  1702. // since we set the output file names wait for it to end
  1703. auto chain = builder.Start();
  1704. chain.Wait();
  1705. outputFile = stdoutFile;
  1706. return 1;
  1707. }
  1708. int cmCTestCoverageHandler::RunBullseyeSourceSummary(
  1709. cmCTestCoverageHandlerContainer* cont)
  1710. {
  1711. // Run the covsrc command and create a temp outputfile
  1712. std::string outputFile;
  1713. if (!this->RunBullseyeCommand(cont, "covsrc", "-c", outputFile)) {
  1714. cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covsrc:\n");
  1715. return 0;
  1716. }
  1717. std::ostream& tmpLog = *cont->OFS;
  1718. // copen the Coverage.xml file in the Testing directory
  1719. cmGeneratedFileStream covSumFile;
  1720. cmXMLWriter xml(covSumFile);
  1721. if (!this->StartResultingXML(cmCTest::PartCoverage, "Coverage",
  1722. covSumFile)) {
  1723. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1724. "Cannot open coverage summary file." << std::endl);
  1725. return 0;
  1726. }
  1727. this->CTest->StartXML(xml, this->AppendXML);
  1728. auto elapsed_time_start = std::chrono::steady_clock::now();
  1729. std::string coverage_start_time = this->CTest->CurrentTime();
  1730. xml.StartElement("Coverage");
  1731. xml.Element("StartDateTime", coverage_start_time);
  1732. xml.Element("StartTime", std::chrono::system_clock::now());
  1733. std::string stdline;
  1734. std::string errline;
  1735. // expected output:
  1736. // first line is:
  1737. // "Source","Function Coverage","out of","%","C/D Coverage","out of","%"
  1738. // after that data follows in that format
  1739. std::string sourceFile;
  1740. int functionsCalled = 0;
  1741. int totalFunctions = 0;
  1742. int percentFunction = 0;
  1743. int branchCovered = 0;
  1744. int totalBranches = 0;
  1745. int percentBranch = 0;
  1746. double total_tested = 0;
  1747. double total_untested = 0;
  1748. double total_functions = 0;
  1749. double percent_coverage = 0;
  1750. double number_files = 0;
  1751. std::vector<std::string> coveredFiles;
  1752. std::vector<std::string> coveredFilesFullPath;
  1753. // Read and parse the summary output file
  1754. cmsys::ifstream fin(outputFile.c_str());
  1755. if (!fin) {
  1756. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1757. "Cannot open coverage summary file: " << outputFile
  1758. << std::endl);
  1759. return 0;
  1760. }
  1761. std::set<std::string> coveredFileNames;
  1762. while (cmSystemTools::GetLineFromStream(fin, stdline)) {
  1763. // if we have a line of output from stdout
  1764. if (!stdline.empty()) {
  1765. // parse the comma separated output
  1766. this->ParseBullsEyeCovsrcLine(
  1767. stdline, sourceFile, functionsCalled, totalFunctions, percentFunction,
  1768. branchCovered, totalBranches, percentBranch);
  1769. // The first line is the header
  1770. if (sourceFile == "Source" || sourceFile == "Total") {
  1771. continue;
  1772. }
  1773. std::string file = sourceFile;
  1774. coveredFileNames.insert(file);
  1775. if (!cmSystemTools::FileIsFullPath(sourceFile)) {
  1776. // file will be relative to the binary dir
  1777. file = cmStrCat(cont->BinaryDir, '/', sourceFile);
  1778. }
  1779. file = cmSystemTools::CollapseFullPath(file);
  1780. bool shouldIDoCoverage =
  1781. this->ShouldIDoCoverage(file, cont->SourceDir, cont->BinaryDir);
  1782. if (!shouldIDoCoverage) {
  1783. cmCTestOptionalLog(
  1784. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1785. ".NoDartCoverage found, so skip coverage check for: " << file
  1786. << std::endl,
  1787. this->Quiet);
  1788. continue;
  1789. }
  1790. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1791. "Doing coverage for: " << file << std::endl,
  1792. this->Quiet);
  1793. coveredFiles.push_back(sourceFile);
  1794. coveredFilesFullPath.push_back(file);
  1795. number_files++;
  1796. total_functions += totalFunctions;
  1797. total_tested += functionsCalled;
  1798. total_untested += (totalFunctions - functionsCalled);
  1799. std::string fileName = cmSystemTools::GetFilenameName(file);
  1800. std::string shortFileName = this->CTest->GetShortPathToFile(file);
  1801. float cper = static_cast<float>(percentBranch + percentFunction);
  1802. if (totalBranches > 0) {
  1803. cper /= 2.0f;
  1804. }
  1805. percent_coverage += static_cast<double>(cper);
  1806. float cmet = static_cast<float>(percentFunction + percentBranch);
  1807. if (totalBranches > 0) {
  1808. cmet /= 2.0f;
  1809. }
  1810. cmet /= 100.0f;
  1811. tmpLog << stdline << "\n";
  1812. tmpLog << fileName << "\n";
  1813. tmpLog << "functionsCalled: " << functionsCalled / 100 << "\n";
  1814. tmpLog << "totalFunctions: " << totalFunctions / 100 << "\n";
  1815. tmpLog << "percentFunction: " << percentFunction << "\n";
  1816. tmpLog << "branchCovered: " << branchCovered << "\n";
  1817. tmpLog << "totalBranches: " << totalBranches << "\n";
  1818. tmpLog << "percentBranch: " << percentBranch << "\n";
  1819. tmpLog << "percentCoverage: " << percent_coverage << "\n";
  1820. tmpLog << "coverage metric: " << cmet << "\n";
  1821. xml.StartElement("File");
  1822. xml.Attribute("Name", sourceFile);
  1823. xml.Attribute("FullPath", shortFileName);
  1824. xml.Attribute("Covered", cmet > 0 ? "true" : "false");
  1825. xml.Element("BranchesTested", branchCovered);
  1826. xml.Element("BranchesUnTested", totalBranches - branchCovered);
  1827. xml.Element("FunctionsTested", functionsCalled);
  1828. xml.Element("FunctionsUnTested", totalFunctions - functionsCalled);
  1829. // Hack for conversion of function to loc assume a function
  1830. // has 100 lines of code
  1831. xml.Element("LOCTested", functionsCalled * 100);
  1832. xml.Element("LOCUnTested", (totalFunctions - functionsCalled) * 100);
  1833. xml.Element("PercentCoverage", cper);
  1834. xml.Element("CoverageMetric", cmet);
  1835. this->WriteXMLLabels(xml, shortFileName);
  1836. xml.EndElement(); // File
  1837. }
  1838. }
  1839. std::string end_time = this->CTest->CurrentTime();
  1840. xml.Element("LOCTested", total_tested);
  1841. xml.Element("LOCUntested", total_untested);
  1842. xml.Element("LOC", total_functions);
  1843. xml.Element("PercentCoverage", SAFEDIV(percent_coverage, number_files));
  1844. xml.Element("EndDateTime", end_time);
  1845. xml.Element("EndTime", std::chrono::system_clock::now());
  1846. xml.Element("ElapsedMinutes",
  1847. std::chrono::duration_cast<std::chrono::minutes>(
  1848. std::chrono::steady_clock::now() - elapsed_time_start)
  1849. .count());
  1850. xml.EndElement(); // Coverage
  1851. this->CTest->EndXML(xml);
  1852. // Now create the coverage information for each file
  1853. return this->RunBullseyeCoverageBranch(cont, coveredFileNames, coveredFiles,
  1854. coveredFilesFullPath);
  1855. }
  1856. int cmCTestCoverageHandler::HandleBullseyeCoverage(
  1857. cmCTestCoverageHandlerContainer* cont)
  1858. {
  1859. std::string covfile;
  1860. if (!cmSystemTools::GetEnv("COVFILE", covfile) || covfile.empty()) {
  1861. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1862. " COVFILE environment variable not found, not running "
  1863. " bullseye\n",
  1864. this->Quiet);
  1865. return 0;
  1866. }
  1867. cmCTestOptionalLog(
  1868. this->CTest, HANDLER_VERBOSE_OUTPUT,
  1869. " run covsrc with COVFILE=[" << covfile << "]" << std::endl, this->Quiet);
  1870. if (!this->RunBullseyeSourceSummary(cont)) {
  1871. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1872. "Error running bullseye summary.\n");
  1873. return 0;
  1874. }
  1875. cmCTestOptionalLog(this->CTest, DEBUG,
  1876. "HandleBullseyeCoverage return 1 " << std::endl,
  1877. this->Quiet);
  1878. return 1;
  1879. }
  1880. bool cmCTestCoverageHandler::GetNextInt(std::string const& inputLine,
  1881. std::string::size_type& pos,
  1882. int& value)
  1883. {
  1884. std::string::size_type start = pos;
  1885. pos = inputLine.find(',', start);
  1886. value = atoi(inputLine.substr(start, pos).c_str());
  1887. if (pos == std::string::npos) {
  1888. return true;
  1889. }
  1890. pos++;
  1891. return true;
  1892. }
  1893. bool cmCTestCoverageHandler::ParseBullsEyeCovsrcLine(
  1894. std::string const& inputLine, std::string& sourceFile, int& functionsCalled,
  1895. int& totalFunctions, int& percentFunction, int& branchCovered,
  1896. int& totalBranches, int& percentBranch)
  1897. {
  1898. // find the first comma
  1899. std::string::size_type pos = inputLine.find(',');
  1900. if (pos == std::string::npos) {
  1901. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1902. "Error parsing string : " << inputLine << "\n");
  1903. return false;
  1904. }
  1905. // the source file has "" around it so extract out the file name
  1906. sourceFile = inputLine.substr(1, pos - 2);
  1907. pos++;
  1908. if (!this->GetNextInt(inputLine, pos, functionsCalled)) {
  1909. return false;
  1910. }
  1911. if (!this->GetNextInt(inputLine, pos, totalFunctions)) {
  1912. return false;
  1913. }
  1914. if (!this->GetNextInt(inputLine, pos, percentFunction)) {
  1915. return false;
  1916. }
  1917. if (!this->GetNextInt(inputLine, pos, branchCovered)) {
  1918. return false;
  1919. }
  1920. if (!this->GetNextInt(inputLine, pos, totalBranches)) {
  1921. return false;
  1922. }
  1923. if (!this->GetNextInt(inputLine, pos, percentBranch)) {
  1924. return false;
  1925. }
  1926. // should be at the end now
  1927. if (pos != std::string::npos) {
  1928. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1929. "Error parsing input : "
  1930. << inputLine << " last pos not npos = " << pos << "\n");
  1931. }
  1932. return true;
  1933. }
  1934. int cmCTestCoverageHandler::GetLabelId(std::string const& label)
  1935. {
  1936. auto i = this->LabelIdMap.find(label);
  1937. if (i == this->LabelIdMap.end()) {
  1938. int n = static_cast<int>(this->Labels.size());
  1939. this->Labels.push_back(label);
  1940. LabelIdMapType::value_type entry(label, n);
  1941. i = this->LabelIdMap.insert(entry).first;
  1942. }
  1943. return i->second;
  1944. }
  1945. void cmCTestCoverageHandler::LoadLabels()
  1946. {
  1947. std::string fileList =
  1948. cmStrCat(this->CTest->GetBinaryDir(), "/CMakeFiles/TargetDirectories.txt");
  1949. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1950. " target directory list [" << fileList << "]\n",
  1951. this->Quiet);
  1952. cmsys::ifstream finList(fileList.c_str());
  1953. std::string line;
  1954. while (cmSystemTools::GetLineFromStream(finList, line)) {
  1955. this->LoadLabels(line.c_str());
  1956. }
  1957. }
  1958. void cmCTestCoverageHandler::LoadLabels(const char* dir)
  1959. {
  1960. LabelSet& dirLabels = this->TargetDirs[dir];
  1961. std::string fname = cmStrCat(dir, "/Labels.txt");
  1962. cmsys::ifstream fin(fname.c_str());
  1963. if (!fin) {
  1964. return;
  1965. }
  1966. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1967. " loading labels from [" << fname << "]\n", this->Quiet);
  1968. bool inTarget = true;
  1969. std::string source;
  1970. std::string line;
  1971. std::vector<int> targetLabels;
  1972. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1973. if (line.empty() || line[0] == '#') {
  1974. // Ignore blank and comment lines.
  1975. continue;
  1976. }
  1977. if (line[0] == ' ') {
  1978. // Label lines appear indented by one space.
  1979. std::string label = line.substr(1);
  1980. int id = this->GetLabelId(label);
  1981. dirLabels.insert(id);
  1982. if (inTarget) {
  1983. targetLabels.push_back(id);
  1984. } else {
  1985. this->SourceLabels[source].insert(id);
  1986. }
  1987. } else {
  1988. // Non-indented lines specify a source file name. The first one
  1989. // is the end of the target-wide labels.
  1990. inTarget = false;
  1991. source = this->CTest->GetShortPathToFile(line);
  1992. // Label the source with the target labels.
  1993. LabelSet& labelSet = this->SourceLabels[source];
  1994. labelSet.insert(targetLabels.begin(), targetLabels.end());
  1995. }
  1996. }
  1997. }
  1998. void cmCTestCoverageHandler::WriteXMLLabels(cmXMLWriter& xml,
  1999. std::string const& source)
  2000. {
  2001. auto li = this->SourceLabels.find(source);
  2002. if (li != this->SourceLabels.end() && !li->second.empty()) {
  2003. xml.StartElement("Labels");
  2004. for (auto const& ls : li->second) {
  2005. xml.Element("Label", this->Labels[ls]);
  2006. }
  2007. xml.EndElement(); // Labels
  2008. }
  2009. }
  2010. void cmCTestCoverageHandler::SetLabelFilter(
  2011. std::set<std::string> const& labels)
  2012. {
  2013. this->LabelFilter.clear();
  2014. for (std::string const& l : labels) {
  2015. this->LabelFilter.insert(this->GetLabelId(l));
  2016. }
  2017. }
  2018. bool cmCTestCoverageHandler::IntersectsFilter(LabelSet const& labels)
  2019. {
  2020. // If there is no label filter then nothing is filtered out.
  2021. if (this->LabelFilter.empty()) {
  2022. return true;
  2023. }
  2024. std::vector<int> ids;
  2025. std::set_intersection(labels.begin(), labels.end(),
  2026. this->LabelFilter.begin(), this->LabelFilter.end(),
  2027. std::back_inserter(ids));
  2028. return !ids.empty();
  2029. }
  2030. bool cmCTestCoverageHandler::IsFilteredOut(std::string const& source)
  2031. {
  2032. // If there is no label filter then nothing is filtered out.
  2033. if (this->LabelFilter.empty()) {
  2034. return false;
  2035. }
  2036. // The source is filtered out if it does not have any labels in
  2037. // common with the filter set.
  2038. std::string shortSrc = this->CTest->GetShortPathToFile(source);
  2039. auto li = this->SourceLabels.find(shortSrc);
  2040. if (li != this->SourceLabels.end()) {
  2041. return !this->IntersectsFilter(li->second);
  2042. }
  2043. return true;
  2044. }
  2045. std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles(
  2046. cmCTestCoverageHandlerContainer* cont)
  2047. {
  2048. std::set<std::string> extraMatches;
  2049. for (std::string const& ecg : this->ExtraCoverageGlobs) {
  2050. cmsys::Glob gl;
  2051. gl.RecurseOn();
  2052. gl.RecurseThroughSymlinksOff();
  2053. std::string glob = cont->SourceDir + "/" + ecg;
  2054. gl.FindFiles(glob);
  2055. std::vector<std::string> files = gl.GetFiles();
  2056. for (std::string const& f : files) {
  2057. if (this->ShouldIDoCoverage(f, cont->SourceDir, cont->BinaryDir)) {
  2058. extraMatches.insert(this->CTest->GetShortPathToFile(f));
  2059. }
  2060. }
  2061. }
  2062. if (!extraMatches.empty()) {
  2063. for (auto const& i : cont->TotalCoverage) {
  2064. std::string shortPath = this->CTest->GetShortPathToFile(i.first);
  2065. extraMatches.erase(shortPath);
  2066. }
  2067. }
  2068. return extraMatches;
  2069. }