markdown.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 'use strict';
  2. /**
  3. * @module Markdown
  4. */
  5. /**
  6. * Module dependencies.
  7. */
  8. var Base = require('./base');
  9. var utils = require('../utils');
  10. var constants = require('../runner').constants;
  11. var EVENT_RUN_END = constants.EVENT_RUN_END;
  12. var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
  13. var EVENT_SUITE_END = constants.EVENT_SUITE_END;
  14. var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
  15. /**
  16. * Constants
  17. */
  18. var SUITE_PREFIX = '$';
  19. /**
  20. * Expose `Markdown`.
  21. */
  22. exports = module.exports = Markdown;
  23. /**
  24. * Initialize a new `Markdown` reporter.
  25. *
  26. * @public
  27. * @class
  28. * @memberof Mocha.reporters
  29. * @extends Mocha.reporters.Base
  30. * @param {Runner} runner
  31. */
  32. function Markdown(runner) {
  33. Base.call(this, runner);
  34. var level = 0;
  35. var buf = '';
  36. function title(str) {
  37. return Array(level).join('#') + ' ' + str;
  38. }
  39. function mapTOC(suite, obj) {
  40. var ret = obj;
  41. var key = SUITE_PREFIX + suite.title;
  42. obj = obj[key] = obj[key] || {suite: suite};
  43. suite.suites.forEach(function(suite) {
  44. mapTOC(suite, obj);
  45. });
  46. return ret;
  47. }
  48. function stringifyTOC(obj, level) {
  49. ++level;
  50. var buf = '';
  51. var link;
  52. for (var key in obj) {
  53. if (key === 'suite') {
  54. continue;
  55. }
  56. if (key !== SUITE_PREFIX) {
  57. link = ' - [' + key.substring(1) + ']';
  58. link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
  59. buf += Array(level).join(' ') + link;
  60. }
  61. buf += stringifyTOC(obj[key], level);
  62. }
  63. return buf;
  64. }
  65. function generateTOC(suite) {
  66. var obj = mapTOC(suite, {});
  67. return stringifyTOC(obj, 0);
  68. }
  69. generateTOC(runner.suite);
  70. runner.on(EVENT_SUITE_BEGIN, function(suite) {
  71. ++level;
  72. var slug = utils.slug(suite.fullTitle());
  73. buf += '<a name="' + slug + '"></a>' + '\n';
  74. buf += title(suite.title) + '\n';
  75. });
  76. runner.on(EVENT_SUITE_END, function() {
  77. --level;
  78. });
  79. runner.on(EVENT_TEST_PASS, function(test) {
  80. var code = utils.clean(test.body);
  81. buf += test.title + '.\n';
  82. buf += '\n```js\n';
  83. buf += code + '\n';
  84. buf += '```\n\n';
  85. });
  86. runner.once(EVENT_RUN_END, function() {
  87. process.stdout.write('# TOC\n');
  88. process.stdout.write(generateTOC(runner.suite));
  89. process.stdout.write(buf);
  90. });
  91. }
  92. Markdown.description = 'GitHub Flavored Markdown';