|
| 1 | +/** |
| 2 | + * @fileoverview runs `prettier` as an eslint rule |
| 3 | + * @author Teddy Katz |
| 4 | + */ |
| 5 | +'use strict'; |
| 6 | +const util = require('util'); |
| 7 | +const prettier = require('prettier'); |
| 8 | +const astUtils = require('eslint/lib/ast-utils'); |
| 9 | + |
| 10 | +// ------------------------------------------------------------------------------ |
| 11 | +// Rule Definition |
| 12 | +// ------------------------------------------------------------------------------ |
| 13 | +module.exports = { |
| 14 | + meta: { fixable: 'code', schema: [ { type: 'object' } ] }, |
| 15 | + create(context) { |
| 16 | + const sourceCode = context.getSourceCode(); |
| 17 | + |
| 18 | + return { |
| 19 | + Program() { |
| 20 | + // This isn't really very performant (prettier needs to reparse the text). |
| 21 | + // However, I don't think it's possible to run `prettier` on an ESTree AST. |
| 22 | + const desiredText = prettier.format( |
| 23 | + sourceCode.text, |
| 24 | + context.options[0] |
| 25 | + ); |
| 26 | + |
| 27 | + if (sourceCode.text !== desiredText) { |
| 28 | + // Find the first character that differs |
| 29 | + const firstBadIndex = Array |
| 30 | + .from(desiredText) |
| 31 | + .findIndex((char, index) => char !== sourceCode.text[index]); |
| 32 | + const expectedChar = firstBadIndex === -1 |
| 33 | + ? 'EOF' |
| 34 | + : desiredText[firstBadIndex]; |
| 35 | + const foundChar = firstBadIndex >= sourceCode.text.length |
| 36 | + ? 'EOF' |
| 37 | + : firstBadIndex === -1 |
| 38 | + ? sourceCode.text[desiredText.length] |
| 39 | + : sourceCode.text[firstBadIndex]; |
| 40 | + |
| 41 | + context.report({ |
| 42 | + loc: astUtils.getLocationFromRangeIndex( |
| 43 | + sourceCode, |
| 44 | + firstBadIndex === -1 ? desiredText.length : firstBadIndex |
| 45 | + ), |
| 46 | + message: 'Follow `prettier` formatting (expected {{expectedChar}} but found {{foundChar}}).', |
| 47 | + data: { |
| 48 | + expectedChar: util.inspect(expectedChar), |
| 49 | + foundChar: util.inspect(foundChar) |
| 50 | + }, |
| 51 | + fix: fixer => |
| 52 | + fixer.replaceTextRange([ 0, sourceCode.text.length ], desiredText) |
| 53 | + }); |
| 54 | + } |
| 55 | + } |
| 56 | + }; |
| 57 | + } |
| 58 | +}; |
0 commit comments