-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
271 lines (231 loc) · 7.88 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
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
import stylelint from 'stylelint';
import {showInvisibles, generateDifferences} from 'prettier-linter-helpers';
const prettierPromise = import('prettier');
const {INSERT, DELETE, REPLACE} = generateDifferences;
let prettier;
const ruleName = 'prettier/prettier';
const messages = stylelint.utils.ruleMessages(ruleName, {
insert: (code) => `Insert "${showInvisibles(code)}"`,
delete: (code) => `Delete "${showInvisibles(code)}"`,
replace: (deleteCode, insertCode) =>
`Replace "${showInvisibles(deleteCode)}" with "${showInvisibles(
insertCode
)}"`,
});
/** @type {stylelint.Rule} */
const ruleFunction = (expectation, options, context) => {
return async (root, result) => {
const validOptions = stylelint.utils.validateOptions(result, ruleName, {
actual: expectation,
});
if (!validOptions) {
return;
}
// Stylelint can handle css-in-js, in which it formats object literals.
// We don't want to run these extracts of JS through prettier
if (root.source.lang === 'object-literal') {
return;
}
const stylelintPrettierOptions = omitStylelintSpecificOptions(options);
if (!prettier) {
// Prettier is expensive to load, so only load it if needed.
prettier = await prettierPromise;
}
// Default to '<input>' if a filepath was not provided.
// This mimics eslint's behaviour
const filepath = root.source.input.file || '<input>';
const prettierRcOptions = await prettier.resolveConfig(filepath, {
editorconfig: true,
});
const prettierFileInfo = await prettier.getFileInfo(filepath, {
resolveConfig: true,
plugins:
prettierRcOptions?.plugins ?? stylelintPrettierOptions?.plugins ?? [],
ignorePath: '.prettierignore',
});
// Skip if file is ignored using a .prettierignore file
if (prettierFileInfo.ignored) {
return;
}
const initialOptions = {};
// If no filepath was provided then assume the CSS parser
// This is added to the options first, so that
// prettierRcOptions and stylelintPrettierOptions can still override
// the parser.
if (filepath == '<input>') {
initialOptions.parser = 'css';
}
// Stylelint supports languages that may contain multiple types of style
// languages, thus we can't rely on guessing the parser based off the
// filename.
// In all of the following cases stylelint extracts a part of a file to
// be formatted and there exists a prettier parser for the whole file.
// If you're interested in prettier you'll want a fully formatted file so
// you're about to run prettier over the whole file anyway.
// Therefore running prettier over just the style section is wasteful, so
// skip it.
const parserBlockList = [
'babel',
'flow',
'typescript',
'vue',
'markdown',
'html',
'angular', // .component.html files
'svelte',
'astro',
];
if (parserBlockList.indexOf(prettierFileInfo.inferredParser) !== -1) {
return;
}
const prettierOptions = Object.assign(
{},
initialOptions,
prettierRcOptions,
stylelintPrettierOptions,
{filepath}
);
let prettierSource;
const source = root.toString(result.opts.syntax);
try {
prettierSource = await prettier.format(source, prettierOptions);
} catch (err) {
if (!(err instanceof SyntaxError)) {
throw err;
}
let message = 'Parsing error: ' + err.message;
// Prettier's message contains a codeframe style preview of the
// invalid code and the line/column at which the error occurred.
// ESLint shows those pieces of information elsewhere already so
// remove them from the message
if (err.codeFrame) {
message = message.replace(`\n${err.codeFrame}`, '');
}
if (err.loc) {
message = message.replace(/ \(\d+:\d+\)$/, '');
}
stylelint.utils.report({
ruleName,
result,
message,
node: root,
index: getIndexFromLoc(source, err.loc.start),
});
return;
}
// Everything is the same. Nothing to do here;
if (source === prettierSource) {
return;
}
// Otherwise let's generate some differences
const differences = generateDifferences(source, prettierSource);
const report = (message, index, endIndex) => {
return stylelint.utils.report({
ruleName,
result,
message,
node: root,
index,
endIndex,
});
};
if (context.fix) {
// Fixes must be processed in reverse order, as an early delete shall
// change the modification offsets for anything after it
const rawData = differences.reverse().reduce((rawData, difference) => {
let insertText = '';
let deleteText = '';
switch (difference.operation) {
case INSERT:
insertText = difference.insertText;
break;
case DELETE:
deleteText = difference.deleteText;
break;
case REPLACE:
insertText = difference.insertText;
deleteText = difference.deleteText;
break;
}
return (
rawData.substring(0, difference.offset) +
insertText +
rawData.substring(difference.offset + deleteText.length)
);
}, source);
// If root.source.syntax exists then it means stylelint had to use
// postcss-syntax to guess the postcss parser that it should use based
// upon the input filename.
// In that case we want to use the parser that postcss-syntax picked.
// Otherwise use the syntax parser that was provided in the options
const syntax = root.source.syntax || result.opts.syntax;
const newRoot = syntax.parse(rawData);
// For reasons I don't really understand, when the original input does
// not have a trailing newline, newRoot generates a trailing newline but
// it does not get included in the output.
// Cleaning the root raws (to remove any existing whitespace), then
// adding the final new line into the root raws seems to fix this
root.removeAll();
root.cleanRaws();
root.append(newRoot);
// Use the EOL whitespace from the rawData, as it could be \n or \r\n
const trailingWhitespace = rawData.match(/[\s\uFEFF\xA0]+$/);
if (trailingWhitespace) {
root.raws.after = trailingWhitespace[0];
}
return;
}
// Report in the order the differences appear in the content
differences.forEach((difference) => {
const {offset, deleteText = ''} = difference;
switch (difference.operation) {
case INSERT:
report(
messages.insert(difference.insertText),
offset,
offset + deleteText.length
);
break;
case DELETE:
report(
messages.delete(difference.deleteText),
difference.offset,
offset + deleteText.length
);
break;
case REPLACE:
report(
messages.replace(difference.deleteText, difference.insertText),
difference.offset,
offset + deleteText.length
);
break;
}
});
};
};
ruleFunction.ruleName = ruleName;
ruleFunction.messages = messages;
export default stylelint.createPlugin(ruleName, ruleFunction);
function omitStylelintSpecificOptions(options) {
const prettierOptions = Object.assign({}, options);
delete prettierOptions.message;
delete prettierOptions.severity;
return prettierOptions;
}
function getIndexFromLoc(source, {line, column}) {
function nthIndex(str, searchValue, n) {
let i = -1;
while (n-- && i++ < str.length) {
i = str.indexOf(searchValue, i);
if (i < 0) {
break;
}
}
return i;
}
if (line === 1) {
return column - 1;
}
return nthIndex(source, '\n', line - 1) + column;
}