-
-
Notifications
You must be signed in to change notification settings - Fork 929
/
stringFormatter.js
233 lines (194 loc) · 5.66 KB
/
stringFormatter.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
'use strict';
const _ = require('lodash');
const chalk = require('chalk');
const path = require('path');
const stringWidth = require('string-width');
const symbols = require('log-symbols');
const utils = require('postcss-reporter/lib/util');
/** @type {import('table')} */
let table;
const MARGIN_WIDTHS = 9;
const levelColors = {
info: 'blue',
warning: 'yellow',
error: 'red',
success: undefined,
};
/**
* @param {import('stylelint').StylelintResult[]} results
* @returns {string}
*/
function deprecationsFormatter(results) {
const allDeprecationWarnings = _.flatMap(results, 'deprecations');
const uniqueDeprecationWarnings = _.uniqBy(allDeprecationWarnings, 'text');
if (!uniqueDeprecationWarnings || !uniqueDeprecationWarnings.length) {
return '';
}
return uniqueDeprecationWarnings.reduce((output, warning) => {
output += chalk.yellow('Deprecation Warning: ');
output += warning.text;
if (warning.reference) {
output += chalk.dim(' See: ');
output += chalk.dim.underline(warning.reference);
}
return output + '\n';
}, '\n');
}
/**
* @param {import('stylelint').StylelintResult[]} results
* @return {string}
*/
function invalidOptionsFormatter(results) {
const allInvalidOptionWarnings = _.flatMap(results, (r) =>
r.invalidOptionWarnings.map((w) => w.text),
);
const uniqueInvalidOptionWarnings = _.uniq(allInvalidOptionWarnings);
return uniqueInvalidOptionWarnings.reduce((output, warning) => {
output += chalk.red('Invalid Option: ');
output += warning;
return output + '\n';
}, '\n');
}
/**
* @param {string} fromValue
* @return {string}
*/
function logFrom(fromValue) {
if (fromValue.charAt(0) === '<') return fromValue;
return path
.relative(process.cwd(), fromValue)
.split(path.sep)
.join('/');
}
/**
* @param {{[k: number]: number}} columnWidths
* @return {number}
*/
function getMessageWidth(columnWidths) {
if (!process.stdout.isTTY) {
return columnWidths[3];
}
const availableWidth = process.stdout.columns < 80 ? 80 : process.stdout.columns;
const fullWidth = _.sum(_.values(columnWidths));
// If there is no reason to wrap the text, we won't align the last column to the right
if (availableWidth > fullWidth + MARGIN_WIDTHS) {
return columnWidths[3];
}
return availableWidth - (fullWidth - columnWidths[3] + MARGIN_WIDTHS);
}
/**
* @param {import('stylelint').StylelintWarning[]} messages
* @param {string} source
* @return {string}
*/
function formatter(messages, source) {
if (!messages.length) return '';
const orderedMessages = _.sortBy(
messages,
(m) => (m.line ? 2 : 1), // positionless first
(m) => m.line,
(m) => m.column,
);
/**
* Create a list of column widths, needed to calculate
* the size of the message column and if needed wrap it.
* @type {{[k: string]: number}}
*/
const columnWidths = { 0: 1, 1: 1, 2: 1, 3: 1, 4: 1 };
/**
* @param {[string, string, string, string, string]} columns
* @return {[string, string, string, string, string]}
*/
const calculateWidths = function(columns) {
_.forOwn(columns, (value, key) => {
const normalisedValue = value ? value.toString() : value;
columnWidths[key] = Math.max(columnWidths[key], stringWidth(normalisedValue));
});
return columns;
};
let output = '\n';
if (source) {
output += chalk.underline(logFrom(source)) + '\n';
}
const cleanedMessages = orderedMessages.map((message) => {
const location = utils.getLocation(message);
const severity = /** @type {keyof import('log-symbols')} */ (message.severity);
/**
* @type {[string, string, string, string, string]}
*/
const row = [
location.line ? location.line.toString() : '',
location.column ? location.column.toString() : '',
symbols[severity]
? chalk[/** @type {'blue' | 'red' | 'yellow'} */ (levelColors[severity])](symbols[severity])
: severity,
message.text
// Remove all control characters (newline, tab and etc)
.replace(/[\x01-\x1A]+/g, ' ') // eslint-disable-line no-control-regex
.replace(/\.$/, '')
.replace(new RegExp(_.escapeRegExp('(' + message.rule + ')') + '$'), ''),
chalk.dim(message.rule || ''),
];
calculateWidths(row);
return row;
});
if (!table) {
table = require('table');
}
output += table
.table(cleanedMessages, {
border: table.getBorderCharacters('void'),
columns: {
0: { alignment: 'right', width: columnWidths[0], paddingRight: 0 },
1: { alignment: 'left', width: columnWidths[1] },
2: { alignment: 'center', width: columnWidths[2] },
3: {
alignment: 'left',
width: getMessageWidth(columnWidths),
wrapWord: getMessageWidth(columnWidths) > 1,
},
4: { alignment: 'left', width: columnWidths[4], paddingRight: 0 },
},
drawHorizontalLine: () => false,
})
.split('\n')
.map(
/**
* @param {string} el
* @returns {string}
*/
(el) => el.replace(/(\d+)\s+(\d+)/, (m, p1, p2) => chalk.dim(p1 + ':' + p2)),
)
.join('\n');
return output;
}
/**
* @param {import('stylelint').StylelintResult[]} results
* @returns {string}
*/
module.exports = function(results) {
let output = invalidOptionsFormatter(results);
output += deprecationsFormatter(results);
output = results.reduce((output, result) => {
// Treat parseErrors as warnings
if (result.parseErrors) {
result.parseErrors.forEach((error) =>
result.warnings.push({
line: error.line,
column: error.column,
rule: error.stylelintType,
severity: 'error',
text: `${error.text} (${error.stylelintType})`,
}),
);
}
output += formatter(result.warnings, result.source || '');
return output;
}, output);
// Ensure consistent padding
output = output.trim();
if (output !== '') {
output = '\n' + output + '\n\n';
}
return output;
};