/
stringFormatter.js
313 lines (250 loc) · 7.05 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
'use strict';
const path = require('path');
const stringWidth = require('string-width');
const table = require('table');
const { yellow, dim, underline, blue, red, green } = require('picocolors');
const pluralize = require('../utils/pluralize');
const { assertNumber } = require('../utils/validateTypes');
const terminalLink = require('./terminalLink');
const MARGIN_WIDTHS = 9;
/**
* @param {string} s
* @returns {string}
*/
function nope(s) {
return s;
}
const levelColors = {
info: blue,
warning: yellow,
error: red,
success: nope,
};
const symbols = {
info: blue('ℹ'),
warning: yellow('⚠'),
error: red('✖'),
success: green('✔'),
};
/**
* @param {import('stylelint').LintResult[]} results
* @returns {string}
*/
function deprecationsFormatter(results) {
const allDeprecationWarnings = results.flatMap((result) => result.deprecations);
if (allDeprecationWarnings.length === 0) {
return '';
}
const seenText = new Set();
return allDeprecationWarnings.reduce((output, warning) => {
if (seenText.has(warning.text)) return output;
seenText.add(warning.text);
output += yellow('Deprecation Warning: ');
output += warning.text;
if (warning.reference) {
output += dim(' See: ');
output += dim(underline(warning.reference));
}
return `${output}\n`;
}, '\n');
}
/**
* @param {import('stylelint').LintResult[]} results
* @return {string}
*/
function invalidOptionsFormatter(results) {
const allInvalidOptionWarnings = results.flatMap((result) =>
result.invalidOptionWarnings.map((warning) => warning.text),
);
const uniqueInvalidOptionWarnings = [...new Set(allInvalidOptionWarnings)];
return uniqueInvalidOptionWarnings.reduce((output, warning) => {
output += red('Invalid Option: ');
output += warning;
return `${output}\n`;
}, '\n');
}
/**
* @param {string} fromValue
* @param {string} cwd
* @return {string}
*/
function logFrom(fromValue, cwd) {
if (fromValue.startsWith('<')) {
return underline(fromValue);
}
const filePath = path.relative(cwd, fromValue).split(path.sep).join('/');
return terminalLink(filePath, `file://${fromValue}`);
}
/**
* @param {{[k: number]: number}} columnWidths
* @return {number}
*/
function getMessageWidth(columnWidths) {
const width = columnWidths[3];
assertNumber(width);
if (!process.stdout.isTTY) {
return width;
}
const availableWidth = process.stdout.columns < 80 ? 80 : process.stdout.columns;
const fullWidth = Object.values(columnWidths).reduce((a, b) => a + b);
// 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 width;
}
return availableWidth - (fullWidth - width + MARGIN_WIDTHS);
}
/**
* @param {import('stylelint').Warning[]} messages
* @param {string} source
* @param {string} cwd
* @return {string}
*/
function formatter(messages, source, cwd) {
if (!messages.length) return '';
const orderedMessages = [...messages].sort((a, b) => {
// positionless first
if (!a.line && b.line) return -1;
// positionless first
if (a.line && !b.line) return 1;
if (a.line < b.line) return -1;
if (a.line > b.line) return 1;
if (a.column < b.column) return -1;
if (a.column > b.column) return 1;
return 0;
});
/**
* 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]}
*/
function calculateWidths(columns) {
for (const [key, value] of Object.entries(columns)) {
const normalisedValue = value ? value.toString() : value;
const width = columnWidths[key];
assertNumber(width);
columnWidths[key] = Math.max(width, stringWidth(normalisedValue));
}
return columns;
}
let output = '\n';
if (source) {
output += `${logFrom(source, cwd)}\n`;
}
/**
* @param {import('stylelint').Warning} message
* @return {string}
*/
function formatMessageText(message) {
let result = message.text;
result = result
// Remove all control characters (newline, tab and etc)
.replace(/[\u0001-\u001A]+/g, ' ') // eslint-disable-line no-control-regex
.replace(/\.$/, '');
const ruleString = ` (${message.rule})`;
if (result.endsWith(ruleString)) {
result = result.slice(0, result.lastIndexOf(ruleString));
}
return result;
}
const cleanedMessages = orderedMessages.map((message) => {
const { line, column, severity } = message;
/**
* @type {[string, string, string, string, string]}
*/
const row = [
line ? line.toString() : '',
column ? column.toString() : '',
symbols[severity] ? levelColors[severity](symbols[severity]) : severity,
formatMessageText(message),
dim(message.rule || ''),
];
calculateWidths(row);
return row;
});
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) => dim(`${p1}:${p2}`)),
)
.join('\n');
return output;
}
/**
* @type {import('stylelint').Formatter}
*/
module.exports = function stringFormatter(results, returnValue) {
let output = invalidOptionsFormatter(results);
output += deprecationsFormatter(results);
let errorCount = 0;
let warningCount = 0;
output = results.reduce((accum, result) => {
// Treat parseErrors as warnings
if (result.parseErrors) {
for (const error of result.parseErrors) {
result.warnings.push({
line: error.line,
column: error.column,
rule: error.stylelintType,
severity: 'error',
text: `${error.text} (${error.stylelintType})`,
});
errorCount += 1;
}
}
accum += formatter(
result.warnings,
result.source || '',
(returnValue && returnValue.cwd) || process.cwd(),
);
for (const warning of result.warnings) {
switch (warning.severity) {
case 'error':
errorCount += 1;
break;
case 'warning':
warningCount += 1;
break;
default:
throw new Error(`Unknown severity: "${warning.severity}"`);
}
}
return accum;
}, output);
// Ensure consistent padding
output = output.trim();
if (output !== '') {
output = `\n${output}\n\n`;
const total = errorCount + warningCount;
if (total > 0) {
const error = red(`${errorCount} ${pluralize('error', errorCount)}`);
const warning = yellow(`${warningCount} ${pluralize('warning', warningCount)}`);
const tally = `${total} ${pluralize('problem', total)} (${error}, ${warning})`;
output += `${tally}\n\n`;
}
}
return output;
};