markdown.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Module dependencies.
  3. */
  4. var Base = require('./base')
  5. , utils = require('../utils');
  6. /**
  7. * Expose `Markdown`.
  8. */
  9. exports = module.exports = Markdown;
  10. /**
  11. * Initialize a new `Markdown` reporter.
  12. *
  13. * @param {Runner} runner
  14. * @api public
  15. */
  16. function Markdown(runner) {
  17. Base.call(this, runner);
  18. var self = this
  19. , stats = this.stats
  20. , level = 0
  21. , buf = '';
  22. function title(str) {
  23. return Array(level).join('#') + ' ' + str;
  24. }
  25. function indent() {
  26. return Array(level).join(' ');
  27. }
  28. function mapTOC(suite, obj) {
  29. var ret = obj;
  30. obj = obj[suite.title] = obj[suite.title] || { suite: suite };
  31. suite.suites.forEach(function(suite){
  32. mapTOC(suite, obj);
  33. });
  34. return ret;
  35. }
  36. function stringifyTOC(obj, level) {
  37. ++level;
  38. var buf = '';
  39. var link;
  40. for (var key in obj) {
  41. if ('suite' == key) continue;
  42. if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
  43. if (key) buf += Array(level).join(' ') + link;
  44. buf += stringifyTOC(obj[key], level);
  45. }
  46. --level;
  47. return buf;
  48. }
  49. function generateTOC(suite) {
  50. var obj = mapTOC(suite, {});
  51. return stringifyTOC(obj, 0);
  52. }
  53. generateTOC(runner.suite);
  54. runner.on('suite', function(suite){
  55. ++level;
  56. var slug = utils.slug(suite.fullTitle());
  57. buf += '<a name="' + slug + '"></a>' + '\n';
  58. buf += title(suite.title) + '\n';
  59. });
  60. runner.on('suite end', function(suite){
  61. --level;
  62. });
  63. runner.on('pass', function(test){
  64. var code = utils.clean(test.fn.toString());
  65. buf += test.title + '.\n';
  66. buf += '\n```js\n';
  67. buf += code + '\n';
  68. buf += '```\n\n';
  69. });
  70. runner.on('end', function(){
  71. process.stdout.write('# TOC\n');
  72. process.stdout.write(generateTOC(runner.suite));
  73. process.stdout.write(buf);
  74. });
  75. }