forked from prettier/eslint-plugin-prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheslint-plugin-prettier.js
410 lines (380 loc) · 12.2 KB
/
eslint-plugin-prettier.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* @fileoverview Runs `prettier` as an ESLint rule.
* @author Andres Suarez
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const diff = require('fast-diff');
const docblock = require('jest-docblock');
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
// Preferred Facebook style.
const FB_PRETTIER_OPTIONS = {
singleQuote: true,
trailingComma: 'all',
bracketSpacing: false,
jsxBracketSameLine: true,
parser: 'flow'
};
const LINE_ENDING_RE = /\r\n|[\r\n\u2028\u2029]/;
const OPERATION_INSERT = 'insert';
const OPERATION_DELETE = 'delete';
const OPERATION_REPLACE = 'replace';
// ------------------------------------------------------------------------------
// Privates
// ------------------------------------------------------------------------------
// Lazily-loaded Prettier.
let prettier;
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Gets the location of a given index in the source code for a given context.
* @param {RuleContext} context - The ESLint rule context.
* @param {number} index - An index in the source code.
* @returns {Object} An object containing numeric `line` and `column` keys.
*/
function getLocFromIndex(context, index) {
// If `sourceCode.getLocFromIndex` is available from ESLint, use it - added
// in ESLint 3.16.0.
const sourceCode = context.getSourceCode();
if (typeof sourceCode.getLocFromIndex === 'function') {
return sourceCode.getLocFromIndex(index);
}
const text = sourceCode.getText();
if (typeof index !== 'number') {
throw new TypeError('Expected `index` to be a number.');
}
if (index < 0 || index > text.length) {
throw new RangeError('Index out of range.');
}
// Loosely based on
// https://github.com/eslint/eslint/blob/18a519fa/lib/ast-utils.js#L408-L438
const lineEndingPattern = /\r\n|[\r\n\u2028\u2029]/g;
let offset = 0;
let line = 0;
let match;
while ((match = lineEndingPattern.exec(text))) {
const next = match.index + match[0].length;
if (index < next) {
break;
}
line++;
offset = next;
}
return {
line: line + 1,
column: index - offset
};
}
/**
* Converts invisible characters to a commonly recognizable visible form.
* @param {string} str - The string with invisibles to convert.
* @returns {string} The converted string.
*/
function showInvisibles(str) {
let ret = '';
for (let i = 0; i < str.length; i++) {
switch (str[i]) {
case ' ':
ret += '·'; // Middle Dot, \u00B7
break;
case '\n':
ret += '⏎'; // Return Symbol, \u23ce
break;
case '\t':
ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9
break;
default:
ret += str[i];
break;
}
}
return ret;
}
/**
* Generate results for differences between source code and formatted version.
* @param {string} source - The original source.
* @param {string} prettierSource - The Prettier formatted source.
* @returns {Array} - An array contains { operation, offset, insertText, deleteText }
*/
function generateDifferences(source, prettierSource) {
// fast-diff returns the differences between two texts as a series of
// INSERT, DELETE or EQUAL operations. The results occur only in these
// sequences:
// /-> INSERT -> EQUAL
// EQUAL | /-> EQUAL
// \-> DELETE |
// \-> INSERT -> EQUAL
// Instead of reporting issues at each INSERT or DELETE, certain sequences
// are batched together and are reported as a friendlier "replace" operation:
// - A DELETE immediately followed by an INSERT.
// - Any number of INSERTs and DELETEs where the joining EQUAL of one's end
// and another's beginning does not have line endings (i.e. issues that occur
// on contiguous lines).
const results = diff(source, prettierSource);
const differences = [];
const batch = [];
let offset = 0; // NOTE: INSERT never advances the offset.
while (results.length) {
const result = results.shift();
const op = result[0];
const text = result[1];
switch (op) {
case diff.INSERT:
case diff.DELETE:
batch.push(result);
break;
case diff.EQUAL:
if (results.length) {
if (batch.length) {
if (LINE_ENDING_RE.test(text)) {
flush();
offset += text.length;
} else {
batch.push(result);
}
} else {
offset += text.length;
}
}
break;
default:
throw new Error(`Unexpected fast-diff operation "${op}"`);
}
if (batch.length && !results.length) {
flush();
}
}
return differences;
function flush() {
let aheadDeleteText = '';
let aheadInsertText = '';
while (batch.length) {
const next = batch.shift();
const op = next[0];
const text = next[1];
switch (op) {
case diff.INSERT:
aheadInsertText += text;
break;
case diff.DELETE:
aheadDeleteText += text;
break;
case diff.EQUAL:
aheadDeleteText += text;
aheadInsertText += text;
break;
}
}
if (aheadDeleteText && aheadInsertText) {
differences.push({
offset,
operation: OPERATION_REPLACE,
insertText: aheadInsertText,
deleteText: aheadDeleteText
});
} else if (!aheadDeleteText && aheadInsertText) {
differences.push({
offset,
operation: OPERATION_INSERT,
insertText: aheadInsertText
});
} else if (aheadDeleteText && !aheadInsertText) {
differences.push({
offset,
operation: OPERATION_DELETE,
deleteText: aheadDeleteText
});
}
offset += aheadDeleteText.length;
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
/**
* Reports an "Insert ..." issue where text must be inserted.
* @param {RuleContext} context - The ESLint rule context.
* @param {number} offset - The source offset where to insert text.
* @param {string} text - The text to be inserted.
* @returns {void}
*/
function reportInsert(context, offset, text) {
const pos = getLocFromIndex(context, offset);
const range = [offset, offset];
context.report({
message: 'Insert `{{ code }}`',
data: { code: showInvisibles(text) },
loc: { start: pos, end: pos },
fix(fixer) {
return fixer.insertTextAfterRange(range, text);
}
});
}
/**
* Reports a "Delete ..." issue where text must be deleted.
* @param {RuleContext} context - The ESLint rule context.
* @param {number} offset - The source offset where to delete text.
* @param {string} text - The text to be deleted.
* @returns {void}
*/
function reportDelete(context, offset, text) {
const start = getLocFromIndex(context, offset);
const end = getLocFromIndex(context, offset + text.length);
const range = [offset, offset + text.length];
context.report({
message: 'Delete `{{ code }}`',
data: { code: showInvisibles(text) },
loc: { start, end },
fix(fixer) {
return fixer.removeRange(range);
}
});
}
/**
* Reports a "Replace ... with ..." issue where text must be replaced.
* @param {RuleContext} context - The ESLint rule context.
* @param {number} offset - The source offset where to replace deleted text
with inserted text.
* @param {string} deleteText - The text to be deleted.
* @param {string} insertText - The text to be inserted.
* @returns {void}
*/
function reportReplace(context, offset, deleteText, insertText) {
const start = getLocFromIndex(context, offset);
const end = getLocFromIndex(context, offset + deleteText.length);
const range = [offset, offset + deleteText.length];
context.report({
message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`',
data: {
deleteCode: showInvisibles(deleteText),
insertCode: showInvisibles(insertText)
},
loc: { start, end },
fix(fixer) {
return fixer.replaceTextRange(range, insertText);
}
});
}
// ------------------------------------------------------------------------------
// Module Definition
// ------------------------------------------------------------------------------
module.exports = {
showInvisibles,
generateDifferences,
configs: {
recommended: {
extends: ['prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error'
}
}
},
rules: {
prettier: {
meta: {
fixable: 'code',
schema: [
// Prettier options:
{
anyOf: [
{ enum: [null, 'fb'] },
{ type: 'object', properties: {}, additionalProperties: true }
]
},
// Pragma:
{ type: 'string', pattern: '^@\\w+$' }
]
},
create(context) {
const pragma = context.options[1]
? context.options[1].slice(1) // Remove leading @
: null;
const sourceCode = context.getSourceCode();
const source = sourceCode.text;
// The pragma is only valid if it is found in a block comment at the very
// start of the file.
if (pragma) {
// ESLint 3.x reports the shebang as a "Line" node, while ESLint 4.x
// reports it as a "Shebang" node. This works for both versions:
const hasShebang = source.startsWith('#!');
const allComments = sourceCode.getAllComments();
const firstComment = hasShebang ? allComments[1] : allComments[0];
if (
!(
firstComment &&
firstComment.type === 'Block' &&
firstComment.loc.start.line === (hasShebang ? 2 : 1) &&
firstComment.loc.start.column === 0
)
) {
return {};
}
const parsed = docblock.parse(firstComment.value);
if (parsed[pragma] !== '') {
return {};
}
}
if (prettier && prettier.clearConfigCache) {
prettier.clearConfigCache();
}
return {
Program() {
if (!prettier) {
// Prettier is expensive to load, so only load it if needed.
prettier = require('prettier');
}
const eslintPrettierOptions =
context.options[0] === 'fb'
? FB_PRETTIER_OPTIONS
: context.options[0];
const prettierRcOptions =
prettier.resolveConfig && prettier.resolveConfig.sync
? prettier.resolveConfig.sync(context.getFilename())
: null;
const prettierOptions = Object.assign(
{},
prettierRcOptions,
eslintPrettierOptions
);
const prettierSource = prettier.format(source, prettierOptions);
if (source !== prettierSource) {
const differences = generateDifferences(source, prettierSource);
differences.forEach(difference => {
switch (difference.operation) {
case OPERATION_INSERT:
reportInsert(
context,
difference.offset,
difference.insertText
);
break;
case OPERATION_DELETE:
reportDelete(
context,
difference.offset,
difference.deleteText
);
break;
case OPERATION_REPLACE:
reportReplace(
context,
difference.offset,
difference.deleteText,
difference.insertText
);
break;
}
});
}
}
};
}
}
}
};