-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
plugin-test-formatting.ts
589 lines (525 loc) · 16.6 KB
/
plugin-test-formatting.ts
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import { getContextualType } from '@typescript-eslint/type-utils';
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils';
import { format, resolveConfig } from 'prettier';
import { createRule } from '../util';
/*
The strings that are used for eslint plugins will not be checked for formatting.
This can lead to diff noise as one contributor adjusts formatting, uses different quotes, etc.
This rule just enforces the following:
- all code samples are formatted with prettier
- all single line tests do not use backticks
- all multiline tests have:
- no code on the first line
- no code on the last line
- the closing backtick indentation === property indentation
- one of the following indentations:
- no indentation at all
- indentation of 1 + object indent
eg:
[
'const a = 1;',
`
const a = 1;
`,
`
const a = 1;
`,
{
code: 'const a = 1',
}
{
code: `
const a = 1;
`,
}
{
code: `
const a = 1;
`,
}
]
*/
const prettierConfig = resolveConfig.sync(__dirname) ?? {};
const START_OF_LINE_WHITESPACE_MATCHER = /^([ ]*)/;
const BACKTICK_REGEX = /`/g;
const TEMPLATE_EXPR_OPENER = /\$\{/g;
function getExpectedIndentForNode(
node: TSESTree.Node,
sourceCodeLines: string[],
): number {
const lineIdx = node.loc.start.line - 1;
const indent = START_OF_LINE_WHITESPACE_MATCHER.exec(
sourceCodeLines[lineIdx],
)![1];
return indent.length;
}
function doIndent(line: string, indent: number): string {
for (let i = 0; i < indent; i += 1) {
line = ' ' + line;
}
return line;
}
function getQuote(code: string): "'" | '"' | null {
const hasSingleQuote = code.includes("'");
const hasDoubleQuote = code.includes('"');
if (hasSingleQuote && hasDoubleQuote) {
// be lazy and make them fix and escape the quotes manually
return null;
}
return hasSingleQuote ? '"' : "'";
}
function escapeTemplateString(code: string): string {
let fixed = code;
fixed = fixed.replace(BACKTICK_REGEX, '\\`');
fixed = fixed.replace(TEMPLATE_EXPR_OPENER, '\\${');
return fixed;
}
type Options = [
{
// This option exists so that rules like type-annotation-spacing can exist without every test needing a prettier-ignore
formatWithPrettier?: boolean;
},
];
type MessageIds =
| 'invalidFormatting'
| 'invalidFormattingErrorTest'
| 'singleLineQuotes'
| 'templateLiteralEmptyEnds'
| 'templateLiteralLastLineIndent'
| 'templateStringRequiresIndent'
| 'templateStringMinimumIndent'
| 'prettierException';
export default createRule<Options, MessageIds>({
name: 'plugin-test-formatting',
meta: {
type: 'problem',
docs: {
description: `Enforces that eslint-plugin test snippets are correctly formatted`,
recommended: 'error',
requiresTypeChecking: true,
},
fixable: 'code',
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
formatWithPrettier: {
type: 'boolean',
},
},
},
],
messages: {
invalidFormatting:
'This snippet should be formatted correctly. Use the fixer to format the code.',
invalidFormattingErrorTest:
'This snippet should be formatted correctly. Use the fixer to format the code. Note that the automated fixer may break your test locations.',
singleLineQuotes: 'Use quotes (\' or ") for single line tests.',
templateLiteralEmptyEnds:
'Template literals must start and end with an empty line.',
templateLiteralLastLineIndent:
'The closing line of the template literal must be indented to align with its parent.',
templateStringRequiresIndent:
'Test code should either have no indent, or be indented {{indent}} spaces.',
templateStringMinimumIndent:
'Test code should be indented at least {{indent}} spaces.',
prettierException:
'Prettier was unable to format this snippet: {{message}}',
},
},
defaultOptions: [
{
formatWithPrettier: true,
},
],
create(context, [{ formatWithPrettier }]) {
const sourceCode = context.getSourceCode();
const { program, esTreeNodeToTSNodeMap } =
ESLintUtils.getParserServices(context);
const checker = program.getTypeChecker();
const checkedObjects = new Set<TSESTree.ObjectExpression>();
function prettierFormat(
code: string,
location: TSESTree.Node,
): string | null {
if (formatWithPrettier === false) {
return null;
}
try {
return format(code, {
...prettierConfig,
parser: 'typescript',
}).trimEnd(); // prettier will insert a new line at the end of the code
} catch (ex) {
// adapted from https://github.com/prettier/eslint-plugin-prettier/blob/185b1064d3dd674538456fb2fad97fbfcde49e0d/eslint-plugin-prettier.js#L242-L257
if (!(ex instanceof SyntaxError)) {
throw ex;
}
const err = ex as Error & {
codeFrame: string;
loc?: unknown;
};
let message = err.message;
if (err.codeFrame) {
message = message.replace(`\n${err.codeFrame}`, '');
}
if (err.loc) {
message = message.replace(/ \(\d+:\d+\)$/, '');
}
context.report({
node: location,
messageId: 'prettierException',
data: {
message,
},
});
return null;
}
}
function checkExpression(node: TSESTree.Node, isErrorTest: boolean): void {
switch (node.type) {
case AST_NODE_TYPES.Literal:
checkLiteral(node, isErrorTest);
break;
case AST_NODE_TYPES.TemplateLiteral:
checkTemplateLiteral(node, isErrorTest);
break;
case AST_NODE_TYPES.TaggedTemplateExpression:
checkTaggedTemplateExpression(node, isErrorTest);
break;
case AST_NODE_TYPES.CallExpression:
checkCallExpression(node, isErrorTest);
break;
}
}
function checkLiteral(
literal: TSESTree.Literal,
isErrorTest: boolean,
quoteIn?: string,
): void {
if (typeof literal.value === 'string') {
const output = prettierFormat(literal.value, literal);
if (output && output !== literal.value) {
context.report({
node: literal,
messageId: isErrorTest
? 'invalidFormattingErrorTest'
: 'invalidFormatting',
fix(fixer) {
if (output.includes('\n')) {
// formatted string is multiline, then have to use backticks
return fixer.replaceText(
literal,
`\`${escapeTemplateString(output)}\``,
);
}
const quote = quoteIn ?? getQuote(output);
if (quote == null) {
return null;
}
return fixer.replaceText(literal, `${quote}${output}${quote}`);
},
});
}
}
}
function checkTemplateLiteral(
literal: TSESTree.TemplateLiteral,
isErrorTest: boolean,
isNoFormatTagged = false,
): void {
if (literal.quasis.length > 1) {
// ignore template literals with ${expressions} for simplicity
return;
}
const text = literal.quasis[0].value.cooked;
if (literal.loc.end.line === literal.loc.start.line) {
// don't use template strings for single line tests
return context.report({
node: literal,
messageId: 'singleLineQuotes',
fix(fixer) {
const quote = getQuote(text);
if (quote == null) {
return null;
}
return [
fixer.replaceTextRange(
[literal.range[0], literal.range[0] + 1],
quote,
),
fixer.replaceTextRange(
[literal.range[1] - 1, literal.range[1]],
quote,
),
];
},
});
}
const lines = text.split('\n');
const lastLine = lines[lines.length - 1];
// prettier will trim out the end of line on save, but eslint will check before then
const isStartEmpty = lines[0].trimEnd() === '';
// last line can be indented
const isEndEmpty = lastLine.trimStart() === '';
if (!isStartEmpty || !isEndEmpty) {
// multiline template strings must have an empty first/last line
return context.report({
node: literal,
messageId: 'templateLiteralEmptyEnds',
*fix(fixer) {
if (!isStartEmpty) {
yield fixer.replaceTextRange(
[literal.range[0], literal.range[0] + 1],
'`\n',
);
}
if (!isEndEmpty) {
yield fixer.replaceTextRange(
[literal.range[1] - 1, literal.range[1]],
'\n`',
);
}
},
});
}
const parentIndent = getExpectedIndentForNode(literal, sourceCode.lines);
if (lastLine.length !== parentIndent) {
return context.report({
node: literal,
messageId: 'templateLiteralLastLineIndent',
fix(fixer) {
return fixer.replaceTextRange(
[literal.range[1] - lastLine.length - 1, literal.range[1]],
doIndent('`', parentIndent),
);
},
});
}
// remove the empty lines
lines.pop();
lines.shift();
// +2 because we expect the string contents are indented one level
const expectedIndent = parentIndent + 2;
const firstLineIndent = START_OF_LINE_WHITESPACE_MATCHER.exec(
lines[0],
)![1];
const requiresIndent = firstLineIndent.length > 0;
if (requiresIndent) {
if (firstLineIndent.length !== expectedIndent) {
return context.report({
node: literal,
messageId: 'templateStringRequiresIndent',
data: {
indent: expectedIndent,
},
});
}
// quick-and-dirty validation that lines are roughly indented correctly
for (const line of lines) {
if (line.length === 0) {
// empty lines are valid
continue;
}
const matches = START_OF_LINE_WHITESPACE_MATCHER.exec(line)!;
const indent = matches[1];
if (indent.length < expectedIndent) {
return context.report({
node: literal,
messageId: 'templateStringMinimumIndent',
data: {
indent: expectedIndent,
},
});
}
}
// trim the lines to remove expectedIndent characters from the start
// this makes it easier to check formatting
for (let i = 0; i < lines.length; i += 1) {
lines[i] = lines[i].substring(expectedIndent);
}
}
if (isNoFormatTagged) {
return;
}
const code = lines.join('\n');
const formatted = prettierFormat(code, literal);
if (formatted && formatted !== code) {
const formattedIndented = requiresIndent
? formatted
.split('\n')
.map(l => doIndent(l, expectedIndent))
.join('\n')
: formatted;
return context.report({
node: literal,
messageId: isErrorTest
? 'invalidFormattingErrorTest'
: 'invalidFormatting',
fix(fixer) {
return fixer.replaceText(
literal,
`\`\n${escapeTemplateString(formattedIndented)}\n${doIndent(
'',
parentIndent,
)}\``,
);
},
});
}
}
function isNoFormatTemplateTag(
tag: TSESTree.LeftHandSideExpression,
): boolean {
return tag.type === AST_NODE_TYPES.Identifier && tag.name === 'noFormat';
}
function checkTaggedTemplateExpression(
expr: TSESTree.TaggedTemplateExpression,
isErrorTest: boolean,
): void {
if (!isNoFormatTemplateTag(expr.tag)) {
return;
}
if (expr.loc.start.line === expr.loc.end.line) {
// all we do on single line test cases is check format, but there's no formatting to do
return;
}
checkTemplateLiteral(
expr.quasi,
isErrorTest,
isNoFormatTemplateTag(expr.tag),
);
}
function checkCallExpression(
callExpr: TSESTree.CallExpression,
isErrorTest: boolean,
): void {
if (callExpr.callee.type !== AST_NODE_TYPES.MemberExpression) {
return;
}
const memberExpr = callExpr.callee;
// handle cases like 'aa'.trimRight and `aa`.trimRight()
checkExpression(memberExpr.object, isErrorTest);
}
function checkInvalidTest(
test: TSESTree.ObjectExpression,
isErrorTest = true,
): void {
if (checkedObjects.has(test)) {
return;
}
checkedObjects.add(test);
for (const prop of test.properties) {
if (
prop.type !== AST_NODE_TYPES.Property ||
prop.computed ||
prop.key.type !== AST_NODE_TYPES.Identifier
) {
continue;
}
if (prop.key.name === 'code') {
checkExpression(prop.value, isErrorTest);
}
}
}
function checkValidTest(tests: TSESTree.ArrayExpression): void {
for (const test of tests.elements) {
switch (test.type) {
case AST_NODE_TYPES.ObjectExpression:
// delegate object-style tests to the invalid checker
checkInvalidTest(test, false);
break;
default:
checkExpression(test, false);
break;
}
}
}
return {
// valid
'CallExpression > ObjectExpression > Property[key.name = "valid"] > ArrayExpression':
checkValidTest,
// invalid - errors
[[
AST_NODE_TYPES.CallExpression,
AST_NODE_TYPES.ObjectExpression,
'Property[key.name = "invalid"]',
AST_NODE_TYPES.ArrayExpression,
AST_NODE_TYPES.ObjectExpression,
].join(' > ')]: checkInvalidTest,
// special case for our batchedSingleLineTests utility
'CallExpression[callee.name = "batchedSingleLineTests"] > ObjectExpression':
checkInvalidTest,
/**
* generic, type-aware handling for any old object
* this is a fallback to handle random variables people declare or object
* literals that are passed via array maps, etc
*/
ObjectExpression(node): void {
if (checkedObjects.has(node)) {
return;
}
const type = getContextualType(
checker,
esTreeNodeToTSNodeMap.get(node),
);
if (!type) {
return;
}
const typeString = checker.typeToString(type);
if (/^RunTests\b/.test(typeString)) {
checkedObjects.add(node);
for (const prop of node.properties) {
if (
prop.type === AST_NODE_TYPES.SpreadElement ||
prop.computed ||
prop.key.type !== AST_NODE_TYPES.Identifier ||
prop.value.type !== AST_NODE_TYPES.ArrayExpression
) {
continue;
}
switch (prop.key.name) {
case 'valid':
checkValidTest(prop.value);
break;
case 'invalid':
for (const element of prop.value.elements) {
if (element.type === AST_NODE_TYPES.ObjectExpression) {
checkInvalidTest(element);
}
}
break;
}
}
return;
}
if (/^ValidTestCase\b/.test(typeString)) {
checkInvalidTest(node);
return;
}
if (/^InvalidTestCase\b/.test(typeString)) {
checkInvalidTest(node);
for (const testProp of node.properties) {
if (
testProp.type === AST_NODE_TYPES.SpreadElement ||
testProp.computed ||
testProp.key.type !== AST_NODE_TYPES.Identifier ||
testProp.key.name !== 'errors' ||
testProp.value.type !== AST_NODE_TYPES.ArrayExpression
) {
continue;
}
for (const errorElement of testProp.value.elements) {
if (errorElement.type !== AST_NODE_TYPES.ObjectExpression) {
continue;
}
checkInvalidTest(errorElement);
}
}
}
},
};
},
});