-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
95 lines (84 loc) · 2.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var failingCode = require('./failing-code');
var style = require('./style-format');
var format = require('./format-text');
var leftpad = require('left-pad');
/**
* The template that is rendered with the error detailed error information.
*
* @type {String}
* @private
*/
var template = style([
'{bold}{red}{title} {grey}{filename}{reset}',
' {red}{v}',
' {grey}{previousLineNo}. {previousLine}',
' {reset}{failingLineNo}. {failingLine}',
' {grey}{nextLineNo}. {nextLine}',
' {red}{^}{reset}',
' {stack}',
'{reset}'
].join('\n'));
/**
* Replaces the newlines with tabbed newlines.
*
* @param {String} Stack error stack that needs to be tabbed
* @returns {String} Tabbed stacktrace
* @private
*/
function tabStack(stack) {
return stack.replace(/\n/g, '\n ');
}
/**
* Shows the column
*
* @param {Array} code The failing code information.
* @param {Number} tabn Tabs
* @param {String} ch Character that needs to be shown.
* @private
*/
function showColumn(code, tabn, ch) {
var i = String(code[1].line).length + code[1].col + 1 + tabn;
var result = '';
while (i--) {
result += ' ';
}
return result + ch;
}
/**
* Reformat an error so it shows detailed debug information.
*
* @param {Error} error The error that needs to be pretty.
* @param {Object} options Addition configuration.
* @returns {Undefined|String} Rendered template or bust.
* @public
*/
function pruddy(error, options) {
if (!error || !error.stack) return;
options = options || {};
var code = options.code || failingCode(error, options);
if (!code) return;
var previous = String(code[0].line);
var failing = String(code[1].line);
var next = String(code[2].line);
var line = Math.max(previous.length, failing.length, next.length);
return format(template, {
title: error.message,
filename: code[1].filename,
previousLine: code[0].code,
previousLineNo: leftpad(previous, line),
previousColNo: code[0].col,
failingLine: code[1].code,
failingLineNo: leftpad(failing, line),
failingColNo: code[1].col,
nextLine: code[2].code,
nextLineNo: leftpad(next, line),
nextColNo: code[2].col,
stack: tabStack(error.stack),
'^': showColumn(code, line - failing.length, '^'),
'v': showColumn(code, line - failing.length, 'v')
});
}
//
// Expose the module
//
module.exports = pruddy;