index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. 'use strict';
  2. /*
  3. Copyright 2012-2015, Yahoo Inc.
  4. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  5. */
  6. const fs = require('fs');
  7. const path = require('path');
  8. const html = require('html-escaper');
  9. const { ReportBase } = require('istanbul-lib-report');
  10. const annotator = require('./annotator');
  11. function htmlHead(details) {
  12. return `
  13. <head>
  14. <title>Code coverage report for ${html.escape(details.entity)}</title>
  15. <meta charset="utf-8" />
  16. <link rel="stylesheet" href="${html.escape(details.prettify.css)}" />
  17. <link rel="stylesheet" href="${html.escape(details.base.css)}" />
  18. <link rel="shortcut icon" type="image/x-icon" href="${html.escape(
  19. details.favicon
  20. )}" />
  21. <meta name="viewport" content="width=device-width, initial-scale=1" />
  22. <style type='text/css'>
  23. .coverage-summary .sorter {
  24. background-image: url(${html.escape(details.sorter.image)});
  25. }
  26. </style>
  27. </head>
  28. `;
  29. }
  30. function headerTemplate(details) {
  31. function metricsTemplate({ pct, covered, total }, kind) {
  32. return `
  33. <div class='fl pad1y space-right2'>
  34. <span class="strong">${pct}% </span>
  35. <span class="quiet">${kind}</span>
  36. <span class='fraction'>${covered}/${total}</span>
  37. </div>
  38. `;
  39. }
  40. function skipTemplate(metrics) {
  41. const statements = metrics.statements.skipped;
  42. const branches = metrics.branches.skipped;
  43. const functions = metrics.functions.skipped;
  44. const countLabel = (c, label, plural) =>
  45. c === 0 ? [] : `${c} ${label}${c === 1 ? '' : plural}`;
  46. const skips = [].concat(
  47. countLabel(statements, 'statement', 's'),
  48. countLabel(functions, 'function', 's'),
  49. countLabel(branches, 'branch', 'es')
  50. );
  51. if (skips.length === 0) {
  52. return '';
  53. }
  54. return `
  55. <div class='fl pad1y'>
  56. <span class="strong">${skips.join(', ')}</span>
  57. <span class="quiet">Ignored</span> &nbsp;&nbsp;&nbsp;&nbsp;
  58. </div>
  59. `;
  60. }
  61. return `
  62. <!doctype html>
  63. <html lang="en">
  64. ${htmlHead(details)}
  65. <body>
  66. <div class='wrapper'>
  67. <div class='pad1'>
  68. <h1>${details.pathHtml}</h1>
  69. <div class='clearfix'>
  70. ${metricsTemplate(details.metrics.statements, 'Statements')}
  71. ${metricsTemplate(details.metrics.branches, 'Branches')}
  72. ${metricsTemplate(details.metrics.functions, 'Functions')}
  73. ${metricsTemplate(details.metrics.lines, 'Lines')}
  74. ${skipTemplate(details.metrics)}
  75. </div>
  76. <p class="quiet">
  77. Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
  78. </p>
  79. <template id="filterTemplate">
  80. <div class="quiet">
  81. Filter:
  82. <input oninput="onInput()" type="search" id="fileSearch">
  83. </div>
  84. </template>
  85. </div>
  86. <div class='status-line ${details.reportClass}'></div>
  87. `;
  88. }
  89. function footerTemplate(details) {
  90. return `
  91. <div class='push'></div><!-- for sticky footer -->
  92. </div><!-- /wrapper -->
  93. <div class='footer quiet pad2 space-top1 center small'>
  94. Code coverage generated by
  95. <a href="https://istanbul.js.org/" target="_blank" rel="noopener noreferrer">istanbul</a>
  96. at ${html.escape(details.datetime)}
  97. </div>
  98. <script src="${html.escape(details.prettify.js)}"></script>
  99. <script>
  100. window.onload = function () {
  101. prettyPrint();
  102. };
  103. </script>
  104. <script src="${html.escape(details.sorter.js)}"></script>
  105. <script src="${html.escape(details.blockNavigation.js)}"></script>
  106. </body>
  107. </html>
  108. `;
  109. }
  110. function detailTemplate(data) {
  111. const lineNumbers = new Array(data.maxLines).fill().map((_, i) => i + 1);
  112. const lineLink = num =>
  113. `<a name='L${num}'></a><a href='#L${num}'>${num}</a>`;
  114. const lineCount = line =>
  115. `<span class="cline-any cline-${line.covered}">${line.hits}</span>`;
  116. /* This is rendered in a `<pre>`, need control of all whitespace. */
  117. return [
  118. '<tr>',
  119. `<td class="line-count quiet">${lineNumbers
  120. .map(lineLink)
  121. .join('\n')}</td>`,
  122. `<td class="line-coverage quiet">${data.lineCoverage
  123. .map(lineCount)
  124. .join('\n')}</td>`,
  125. `<td class="text"><pre class="prettyprint lang-js">${data.annotatedCode.join(
  126. '\n'
  127. )}</pre></td>`,
  128. '</tr>'
  129. ].join('');
  130. }
  131. const summaryTableHeader = [
  132. '<div class="pad1">',
  133. '<table class="coverage-summary">',
  134. '<thead>',
  135. '<tr>',
  136. ' <th data-col="file" data-fmt="html" data-html="true" class="file">File</th>',
  137. ' <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>',
  138. ' <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>',
  139. ' <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>',
  140. ' <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>',
  141. ' <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>',
  142. ' <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>',
  143. ' <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>',
  144. ' <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>',
  145. ' <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>',
  146. '</tr>',
  147. '</thead>',
  148. '<tbody>'
  149. ].join('\n');
  150. function summaryLineTemplate(details) {
  151. const { reportClasses, metrics, file, output } = details;
  152. const percentGraph = pct => {
  153. if (!isFinite(pct)) {
  154. return '';
  155. }
  156. const cls = ['cover-fill'];
  157. if (pct === 100) {
  158. cls.push('cover-full');
  159. }
  160. pct = Math.floor(pct);
  161. return [
  162. `<div class="${cls.join(' ')}" style="width: ${pct}%"></div>`,
  163. `<div class="cover-empty" style="width: ${100 - pct}%"></div>`
  164. ].join('');
  165. };
  166. const summaryType = (type, showGraph = false) => {
  167. const info = metrics[type];
  168. const reportClass = reportClasses[type];
  169. const result = [
  170. `<td data-value="${info.pct}" class="pct ${reportClass}">${info.pct}%</td>`,
  171. `<td data-value="${info.total}" class="abs ${reportClass}">${info.covered}/${info.total}</td>`
  172. ];
  173. if (showGraph) {
  174. result.unshift(
  175. `<td data-value="${info.pct}" class="pic ${reportClass}">`,
  176. `<div class="chart">${percentGraph(info.pct)}</div>`,
  177. `</td>`
  178. );
  179. }
  180. return result;
  181. };
  182. return []
  183. .concat(
  184. '<tr>',
  185. `<td class="file ${
  186. reportClasses.statements
  187. }" data-value="${html.escape(file)}"><a href="${html.escape(
  188. output
  189. )}">${html.escape(file)}</a></td>`,
  190. summaryType('statements', true),
  191. summaryType('branches'),
  192. summaryType('functions'),
  193. summaryType('lines'),
  194. '</tr>\n'
  195. )
  196. .join('\n\t');
  197. }
  198. const summaryTableFooter = ['</tbody>', '</table>', '</div>'].join('\n');
  199. const emptyClasses = {
  200. statements: 'empty',
  201. lines: 'empty',
  202. functions: 'empty',
  203. branches: 'empty'
  204. };
  205. const standardLinkMapper = {
  206. getPath(node) {
  207. if (typeof node === 'string') {
  208. return node;
  209. }
  210. let filePath = node.getQualifiedName();
  211. if (node.isSummary()) {
  212. if (filePath !== '') {
  213. filePath += '/index.html';
  214. } else {
  215. filePath = 'index.html';
  216. }
  217. } else {
  218. filePath += '.html';
  219. }
  220. return filePath;
  221. },
  222. relativePath(source, target) {
  223. const targetPath = this.getPath(target);
  224. const sourcePath = path.dirname(this.getPath(source));
  225. return path.posix.relative(sourcePath, targetPath);
  226. },
  227. assetPath(node, name) {
  228. return this.relativePath(this.getPath(node), name);
  229. }
  230. };
  231. function fixPct(metrics) {
  232. Object.keys(emptyClasses).forEach(key => {
  233. metrics[key].pct = 0;
  234. });
  235. return metrics;
  236. }
  237. class HtmlReport extends ReportBase {
  238. constructor(opts) {
  239. super();
  240. this.verbose = opts.verbose;
  241. this.linkMapper = opts.linkMapper || standardLinkMapper;
  242. this.subdir = opts.subdir || '';
  243. this.date = Date();
  244. this.skipEmpty = opts.skipEmpty;
  245. }
  246. getBreadcrumbHtml(node) {
  247. let parent = node.getParent();
  248. const nodePath = [];
  249. while (parent) {
  250. nodePath.push(parent);
  251. parent = parent.getParent();
  252. }
  253. const linkPath = nodePath.map(ancestor => {
  254. const target = this.linkMapper.relativePath(node, ancestor);
  255. const name = ancestor.getRelativeName() || 'All files';
  256. return '<a href="' + target + '">' + name + '</a>';
  257. });
  258. linkPath.reverse();
  259. return linkPath.length > 0
  260. ? linkPath.join(' / ') + ' ' + node.getRelativeName()
  261. : 'All files';
  262. }
  263. fillTemplate(node, templateData, context) {
  264. const linkMapper = this.linkMapper;
  265. const summary = node.getCoverageSummary();
  266. templateData.entity = node.getQualifiedName() || 'All files';
  267. templateData.metrics = summary;
  268. templateData.reportClass = context.classForPercent(
  269. 'statements',
  270. summary.statements.pct
  271. );
  272. templateData.pathHtml = this.getBreadcrumbHtml(node);
  273. templateData.base = {
  274. css: linkMapper.assetPath(node, 'base.css')
  275. };
  276. templateData.sorter = {
  277. js: linkMapper.assetPath(node, 'sorter.js'),
  278. image: linkMapper.assetPath(node, 'sort-arrow-sprite.png')
  279. };
  280. templateData.blockNavigation = {
  281. js: linkMapper.assetPath(node, 'block-navigation.js')
  282. };
  283. templateData.prettify = {
  284. js: linkMapper.assetPath(node, 'prettify.js'),
  285. css: linkMapper.assetPath(node, 'prettify.css')
  286. };
  287. templateData.favicon = linkMapper.assetPath(node, 'favicon.png');
  288. }
  289. getTemplateData() {
  290. return { datetime: this.date };
  291. }
  292. getWriter(context) {
  293. if (!this.subdir) {
  294. return context.writer;
  295. }
  296. return context.writer.writerForDir(this.subdir);
  297. }
  298. onStart(root, context) {
  299. const assetHeaders = {
  300. '.js': '/* eslint-disable */\n'
  301. };
  302. ['.', 'vendor'].forEach(subdir => {
  303. const writer = this.getWriter(context);
  304. const srcDir = path.resolve(__dirname, 'assets', subdir);
  305. fs.readdirSync(srcDir).forEach(f => {
  306. const resolvedSource = path.resolve(srcDir, f);
  307. const resolvedDestination = '.';
  308. const stat = fs.statSync(resolvedSource);
  309. let dest;
  310. if (stat.isFile()) {
  311. dest = resolvedDestination + '/' + f;
  312. if (this.verbose) {
  313. console.log('Write asset: ' + dest);
  314. }
  315. writer.copyFile(
  316. resolvedSource,
  317. dest,
  318. assetHeaders[path.extname(f)]
  319. );
  320. }
  321. });
  322. });
  323. }
  324. onSummary(node, context) {
  325. const linkMapper = this.linkMapper;
  326. const templateData = this.getTemplateData();
  327. const children = node.getChildren();
  328. const skipEmpty = this.skipEmpty;
  329. this.fillTemplate(node, templateData, context);
  330. const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
  331. cw.write(headerTemplate(templateData));
  332. cw.write(summaryTableHeader);
  333. children.forEach(child => {
  334. const metrics = child.getCoverageSummary();
  335. const isEmpty = metrics.isEmpty();
  336. if (skipEmpty && isEmpty) {
  337. return;
  338. }
  339. const reportClasses = isEmpty
  340. ? emptyClasses
  341. : {
  342. statements: context.classForPercent(
  343. 'statements',
  344. metrics.statements.pct
  345. ),
  346. lines: context.classForPercent(
  347. 'lines',
  348. metrics.lines.pct
  349. ),
  350. functions: context.classForPercent(
  351. 'functions',
  352. metrics.functions.pct
  353. ),
  354. branches: context.classForPercent(
  355. 'branches',
  356. metrics.branches.pct
  357. )
  358. };
  359. const data = {
  360. metrics: isEmpty ? fixPct(metrics) : metrics,
  361. reportClasses,
  362. file: child.getRelativeName(),
  363. output: linkMapper.relativePath(node, child)
  364. };
  365. cw.write(summaryLineTemplate(data) + '\n');
  366. });
  367. cw.write(summaryTableFooter);
  368. cw.write(footerTemplate(templateData));
  369. cw.close();
  370. }
  371. onDetail(node, context) {
  372. const linkMapper = this.linkMapper;
  373. const templateData = this.getTemplateData();
  374. this.fillTemplate(node, templateData, context);
  375. const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
  376. cw.write(headerTemplate(templateData));
  377. cw.write('<pre><table class="coverage">\n');
  378. cw.write(detailTemplate(annotator(node.getFileCoverage(), context)));
  379. cw.write('</table></pre>\n');
  380. cw.write(footerTemplate(templateData));
  381. cw.close();
  382. }
  383. }
  384. module.exports = HtmlReport;