|
| 1 | +/** |
| 2 | + * @fileoverview Runs `prettier` as an ESLint rule. |
| 3 | + * @author Andres Suarez |
| 4 | + */ |
| 5 | + |
| 6 | +'use strict'; |
| 7 | + |
| 8 | +// ------------------------------------------------------------------------------ |
| 9 | +// Requirements |
| 10 | +// ------------------------------------------------------------------------------ |
| 11 | + |
| 12 | +const diff = require('fast-diff'); |
| 13 | +const docblock = require('jest-docblock'); |
| 14 | + |
| 15 | +// ------------------------------------------------------------------------------ |
| 16 | +// Constants |
| 17 | +// ------------------------------------------------------------------------------ |
| 18 | + |
| 19 | +// Preferred Facebook style. |
| 20 | +const FB_PRETTIER_OPTIONS = { |
| 21 | + singleQuote: true, |
| 22 | + trailingComma: 'all', |
| 23 | + bracketSpacing: false, |
| 24 | + jsxBracketSameLine: true, |
| 25 | + parser: 'flow' |
| 26 | +}; |
| 27 | + |
| 28 | +const LINE_ENDING_RE = /\r\n|[\r\n\u2028\u2029]/; |
| 29 | + |
| 30 | +// ------------------------------------------------------------------------------ |
| 31 | +// Privates |
| 32 | +// ------------------------------------------------------------------------------ |
| 33 | + |
| 34 | +// Lazily-loaded Prettier. |
| 35 | +let prettier; |
| 36 | + |
| 37 | +// ------------------------------------------------------------------------------ |
| 38 | +// Helpers |
| 39 | +// ------------------------------------------------------------------------------ |
| 40 | + |
| 41 | +/** |
| 42 | + * Gets the location of a given index in the source code for a given context. |
| 43 | + * @param {RuleContext} context - The ESLint rule context. |
| 44 | + * @param {number} index - An index in the source code. |
| 45 | + * @returns {Object} An object containing numeric `line` and `column` keys. |
| 46 | + */ |
| 47 | +function getLocFromIndex(context, index) { |
| 48 | + // If `sourceCode.getLocFromIndex` is available from ESLint, use it. |
| 49 | + // Otherwise, use the private version from eslint/lib/ast-utils. |
| 50 | + // `sourceCode.getLocFromIndex` was added in ESLint 3.16.0. |
| 51 | + const sourceCode = context.getSourceCode(); |
| 52 | + if (typeof sourceCode.getLocFromIndex === 'function') { |
| 53 | + return sourceCode.getLocFromIndex(index); |
| 54 | + } |
| 55 | + const astUtils = require('eslint/lib/ast-utils'); |
| 56 | + return astUtils.getLocationFromRangeIndex(sourceCode, index); |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Converts invisible characters to a commonly recognizable visible form. |
| 61 | + * @param {string} str - The string with invisibles to convert. |
| 62 | + * @returns {string} The converted string. |
| 63 | + */ |
| 64 | +function showInvisibles(str) { |
| 65 | + let ret = ''; |
| 66 | + for (let i = 0; i < str.length; i++) { |
| 67 | + switch (str[i]) { |
| 68 | + case ' ': |
| 69 | + ret += '·'; // Middle Dot, \u00B7 |
| 70 | + break; |
| 71 | + case '\n': |
| 72 | + ret += '⏎'; // Return Symbol, \u23ce |
| 73 | + break; |
| 74 | + case '\t': |
| 75 | + ret += '↹'; // Left Arrow To Bar Over Right Arrow To Bar, \u21b9 |
| 76 | + break; |
| 77 | + default: |
| 78 | + ret += str[i]; |
| 79 | + break; |
| 80 | + } |
| 81 | + } |
| 82 | + return ret; |
| 83 | +} |
| 84 | + |
| 85 | +// ------------------------------------------------------------------------------ |
| 86 | +// Rule Definition |
| 87 | +// ------------------------------------------------------------------------------ |
| 88 | + |
| 89 | +/** |
| 90 | + * Reports issues where the context's source code differs from the Prettier |
| 91 | + formatted version. |
| 92 | + * @param {RuleContext} context - The ESLint rule context. |
| 93 | + * @param {string} prettierSource - The Prettier formatted source. |
| 94 | + * @returns {void} |
| 95 | + */ |
| 96 | +function reportDifferences(context, prettierSource) { |
| 97 | + // fast-diff returns the differences between two texts as a series of |
| 98 | + // INSERT, DELETE or EQUAL operations. The results occur only in these |
| 99 | + // sequences: |
| 100 | + // /-> INSERT -> EQUAL |
| 101 | + // EQUAL | /-> EQUAL |
| 102 | + // \-> DELETE | |
| 103 | + // \-> INSERT -> EQUAL |
| 104 | + // Instead of reporting issues at each INSERT or DELETE, certain sequences |
| 105 | + // are batched together and are reported as a friendlier "replace" operation: |
| 106 | + // - A DELETE immediately followed by an INSERT. |
| 107 | + // - Any number of INSERTs and DELETEs where the joining EQUAL of one's end |
| 108 | + // and another's beginning does not have line endings (i.e. issues that occur |
| 109 | + // on contiguous lines). |
| 110 | + |
| 111 | + const source = context.getSourceCode().text; |
| 112 | + const results = diff(source, prettierSource); |
| 113 | + |
| 114 | + const batch = []; |
| 115 | + let offset = 0; // NOTE: INSERT never advances the offset. |
| 116 | + while (results.length) { |
| 117 | + const result = results.shift(); |
| 118 | + const op = result[0]; |
| 119 | + const text = result[1]; |
| 120 | + switch (op) { |
| 121 | + case diff.INSERT: |
| 122 | + case diff.DELETE: |
| 123 | + batch.push(result); |
| 124 | + break; |
| 125 | + case diff.EQUAL: |
| 126 | + if (results.length) { |
| 127 | + if (batch.length) { |
| 128 | + if (LINE_ENDING_RE.test(text)) { |
| 129 | + flush(); |
| 130 | + offset += text.length; |
| 131 | + } else { |
| 132 | + batch.push(result); |
| 133 | + } |
| 134 | + } else { |
| 135 | + offset += text.length; |
| 136 | + } |
| 137 | + } |
| 138 | + break; |
| 139 | + default: |
| 140 | + throw new Error(`Unexpected fast-diff operation "${op}"`); |
| 141 | + } |
| 142 | + if (batch.length && !results.length) { |
| 143 | + flush(); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + function flush() { |
| 148 | + let aheadDeleteText = ''; |
| 149 | + let aheadInsertText = ''; |
| 150 | + while (batch.length) { |
| 151 | + const next = batch.shift(); |
| 152 | + const op = next[0]; |
| 153 | + const text = next[1]; |
| 154 | + switch (op) { |
| 155 | + case diff.INSERT: |
| 156 | + aheadInsertText += text; |
| 157 | + break; |
| 158 | + case diff.DELETE: |
| 159 | + aheadDeleteText += text; |
| 160 | + break; |
| 161 | + case diff.EQUAL: |
| 162 | + aheadDeleteText += text; |
| 163 | + aheadInsertText += text; |
| 164 | + break; |
| 165 | + } |
| 166 | + } |
| 167 | + if (aheadDeleteText && aheadInsertText) { |
| 168 | + reportReplace(context, offset, aheadDeleteText, aheadInsertText); |
| 169 | + } else if (!aheadDeleteText && aheadInsertText) { |
| 170 | + reportInsert(context, offset, aheadInsertText); |
| 171 | + } else if (aheadDeleteText && !aheadInsertText) { |
| 172 | + reportDelete(context, offset, aheadDeleteText); |
| 173 | + } |
| 174 | + offset += aheadDeleteText.length; |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/** |
| 179 | + * Reports an "Insert ..." issue where text must be inserted. |
| 180 | + * @param {RuleContext} context - The ESLint rule context. |
| 181 | + * @param {number} offset - The source offset where to insert text. |
| 182 | + * @param {string} text - The text to be inserted. |
| 183 | + * @returns {void} |
| 184 | + */ |
| 185 | +function reportInsert(context, offset, text) { |
| 186 | + const pos = getLocFromIndex(context, offset); |
| 187 | + const range = [offset, offset]; |
| 188 | + context.report({ |
| 189 | + message: 'Insert `{{ code }}`', |
| 190 | + data: { code: showInvisibles(text) }, |
| 191 | + loc: { start: pos, end: pos }, |
| 192 | + fix(fixer) { |
| 193 | + return fixer.insertTextAfterRange(range, text); |
| 194 | + } |
| 195 | + }); |
| 196 | +} |
| 197 | + |
| 198 | +/** |
| 199 | + * Reports a "Delete ..." issue where text must be deleted. |
| 200 | + * @param {RuleContext} context - The ESLint rule context. |
| 201 | + * @param {number} offset - The source offset where to delete text. |
| 202 | + * @param {string} text - The text to be deleted. |
| 203 | + * @returns {void} |
| 204 | + */ |
| 205 | +function reportDelete(context, offset, text) { |
| 206 | + const start = getLocFromIndex(context, offset); |
| 207 | + const end = getLocFromIndex(context, offset + text.length); |
| 208 | + const range = [offset, offset + text.length]; |
| 209 | + context.report({ |
| 210 | + message: 'Delete `{{ code }}`', |
| 211 | + data: { code: showInvisibles(text) }, |
| 212 | + loc: { start, end }, |
| 213 | + fix(fixer) { |
| 214 | + return fixer.removeRange(range); |
| 215 | + } |
| 216 | + }); |
| 217 | +} |
| 218 | + |
| 219 | +/** |
| 220 | + * Reports a "Replace ... with ..." issue where text must be replaced. |
| 221 | + * @param {RuleContext} context - The ESLint rule context. |
| 222 | + * @param {number} offset - The source offset where to replace deleted text |
| 223 | + with inserted text. |
| 224 | + * @param {string} deleteText - The text to be deleted. |
| 225 | + * @param {string} insertText - The text to be inserted. |
| 226 | + * @returns {void} |
| 227 | + */ |
| 228 | +function reportReplace(context, offset, deleteText, insertText) { |
| 229 | + const start = getLocFromIndex(context, offset); |
| 230 | + const end = getLocFromIndex(context, offset + deleteText.length); |
| 231 | + const range = [offset, offset + deleteText.length]; |
| 232 | + context.report({ |
| 233 | + message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`', |
| 234 | + data: { |
| 235 | + deleteCode: showInvisibles(deleteText), |
| 236 | + insertCode: showInvisibles(insertText) |
| 237 | + }, |
| 238 | + loc: { start, end }, |
| 239 | + fix(fixer) { |
| 240 | + return fixer.replaceTextRange(range, insertText); |
| 241 | + } |
| 242 | + }); |
| 243 | +} |
| 244 | + |
| 245 | +// ------------------------------------------------------------------------------ |
| 246 | +// Module Definition |
| 247 | +// ------------------------------------------------------------------------------ |
| 248 | + |
| 249 | +module.exports.rules = { |
| 250 | + prettier: { |
| 251 | + meta: { |
| 252 | + fixable: 'code', |
| 253 | + schema: [ |
| 254 | + // Prettier options: |
| 255 | + { |
| 256 | + anyOf: [ |
| 257 | + { enum: [null, 'fb'] }, |
| 258 | + { type: 'object', properties: {}, additionalProperties: true } |
| 259 | + ] |
| 260 | + }, |
| 261 | + // Pragma: |
| 262 | + { type: 'string', pattern: '^@\\w+$' } |
| 263 | + ] |
| 264 | + }, |
| 265 | + create(context) { |
| 266 | + const prettierOptions = context.options[0] === 'fb' |
| 267 | + ? FB_PRETTIER_OPTIONS |
| 268 | + : context.options[0]; |
| 269 | + |
| 270 | + const pragma = context.options[1] |
| 271 | + ? context.options[1].slice(1) // Remove leading @ |
| 272 | + : null; |
| 273 | + |
| 274 | + const sourceCode = context.getSourceCode(); |
| 275 | + const source = sourceCode.text; |
| 276 | + |
| 277 | + // The pragma is only valid if it is found in a block comment at the very |
| 278 | + // start of the file. |
| 279 | + if (pragma) { |
| 280 | + // ESLint 3.x reports the shebang as a "Line" node, while ESLint 4.x |
| 281 | + // reports it as a "Shebang" node. This works for both versions: |
| 282 | + const hasShebang = source.startsWith('#!'); |
| 283 | + const allComments = sourceCode.getAllComments(); |
| 284 | + const firstComment = hasShebang ? allComments[1] : allComments[0]; |
| 285 | + if ( |
| 286 | + !(firstComment && |
| 287 | + firstComment.type === 'Block' && |
| 288 | + firstComment.loc.start.line === (hasShebang ? 2 : 1) && |
| 289 | + firstComment.loc.start.column === 0) |
| 290 | + ) { |
| 291 | + return {}; |
| 292 | + } |
| 293 | + const parsed = docblock.parse(firstComment.value); |
| 294 | + if (parsed[pragma] !== '') { |
| 295 | + return {}; |
| 296 | + } |
| 297 | + } |
| 298 | + |
| 299 | + return { |
| 300 | + Program() { |
| 301 | + if (!prettier) { |
| 302 | + // Prettier is expensive to load, so only load it if needed. |
| 303 | + prettier = require('prettier'); |
| 304 | + } |
| 305 | + const prettierSource = prettier.format(source, prettierOptions); |
| 306 | + if (source !== prettierSource) { |
| 307 | + reportDifferences(context, prettierSource); |
| 308 | + } |
| 309 | + } |
| 310 | + }; |
| 311 | + } |
| 312 | + } |
| 313 | +}; |
0 commit comments