index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var BaseRenderer = require('power-assert-renderer-base');
  3. var stringWidth = require('power-assert-util-string-width');
  4. var inherits = require('util').inherits;
  5. function AssertionRenderer () {
  6. BaseRenderer.call(this);
  7. }
  8. inherits(AssertionRenderer, BaseRenderer);
  9. AssertionRenderer.prototype.onStart = function (context) {
  10. this.context = context;
  11. this.assertionLine = context.source.content;
  12. };
  13. AssertionRenderer.prototype.onEnd = function () {
  14. this.write('');
  15. this.write(this.assertionLine);
  16. var e = this.context.source.error;
  17. if (e && e instanceof SyntaxError) {
  18. var re = /Unexpected token \(1\:(\d+)\)/;
  19. var matchResult = re.exec(e.message);
  20. if (matchResult) {
  21. var syntaxErrorIndex = Number(matchResult[1]);
  22. this.renderValueAt(syntaxErrorIndex, '?');
  23. this.renderValueAt(syntaxErrorIndex, '?');
  24. this.renderValueAt(syntaxErrorIndex, e.toString());
  25. this.renderValueAt(0, '');
  26. this.renderValueAt(0, 'If you are using `babel-plugin-espower` and want to use experimental syntax in your assert(), you should set `embedAst` option to true.');
  27. this.renderValueAt(0, 'see: https://github.com/power-assert-js/babel-plugin-espower#optionsembedast');
  28. }
  29. }
  30. };
  31. AssertionRenderer.prototype.renderValueAt = function (idx, str) {
  32. var row = createRow(stringWidth(this.assertionLine), ' ');
  33. replaceColumn(idx, row, str);
  34. this.write(row.join(''));
  35. };
  36. function replaceColumn (columnIndex, row, str) {
  37. var i, width = stringWidth(str);
  38. for (i = 0; i < width; i += 1) {
  39. row.splice(columnIndex + i, 1, str.charAt(i));
  40. }
  41. }
  42. function createRow (numCols, initial) {
  43. var row = [], i;
  44. for(i = 0; i < numCols; i += 1) {
  45. row[i] = initial;
  46. }
  47. return row;
  48. }
  49. module.exports = AssertionRenderer;