index.js 13 KB

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