|
| 1 | +import _ from 'lodash'; |
| 2 | + |
| 3 | +const looksLikeFlowFileAnnotation = (comment) => { |
| 4 | + return /@(?:no)?flo/i.test(comment); |
| 5 | +}; |
| 6 | + |
| 7 | +const schema = [ |
| 8 | + { |
| 9 | + enum: ['always', 'always-windows', 'never'], |
| 10 | + type: 'string' |
| 11 | + } |
| 12 | +]; |
| 13 | + |
| 14 | +const create = (context) => { |
| 15 | + const mode = context.options[0]; |
| 16 | + const never = mode === 'never'; |
| 17 | + |
| 18 | + const newline = mode === 'always-windows' ? '\r\n' : '\n'; |
| 19 | + |
| 20 | + return { |
| 21 | + Program (node) { |
| 22 | + const sourceCode = context.getSourceCode(); |
| 23 | + |
| 24 | + const potentialFlowFileAnnotation = _.find( |
| 25 | + context.getAllComments(), |
| 26 | + (comment) => { |
| 27 | + return looksLikeFlowFileAnnotation(comment.value); |
| 28 | + } |
| 29 | + ); |
| 30 | + |
| 31 | + if (potentialFlowFileAnnotation) { |
| 32 | + const line = potentialFlowFileAnnotation.loc.end.line; |
| 33 | + const nextLineIsEmpty = sourceCode.lines[line] === ''; |
| 34 | + |
| 35 | + if (!never && !nextLineIsEmpty) { |
| 36 | + context.report({ |
| 37 | + fix: (fixer) => { |
| 38 | + return fixer.insertTextAfter( |
| 39 | + potentialFlowFileAnnotation, |
| 40 | + newline |
| 41 | + ); |
| 42 | + }, |
| 43 | + message: 'Expected newline after flow annotation', |
| 44 | + node |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + if (never && nextLineIsEmpty) { |
| 49 | + context.report({ |
| 50 | + fix: (fixer) => { |
| 51 | + const lineBreak = sourceCode.text[potentialFlowFileAnnotation.end]; |
| 52 | + |
| 53 | + return fixer.replaceTextRange( |
| 54 | + [ |
| 55 | + potentialFlowFileAnnotation.end, |
| 56 | + potentialFlowFileAnnotation.end + ( |
| 57 | + lineBreak === '\r' ? 2 : 1 |
| 58 | + ) |
| 59 | + ], |
| 60 | + '' |
| 61 | + ); |
| 62 | + }, |
| 63 | + message: 'Expected no newline after flow annotation', |
| 64 | + node |
| 65 | + }); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + }; |
| 70 | +}; |
| 71 | + |
| 72 | +export default { |
| 73 | + create, |
| 74 | + schema |
| 75 | +}; |
| 76 | + |
0 commit comments