From 51f4ba227bd82c4cc70903c5dd26fc5a653c81e5 Mon Sep 17 00:00:00 2001 From: Kevin Grandon Date: Tue, 29 May 2018 12:04:26 -0700 Subject: [PATCH] feat: add fixer for requireValidFileAnnotation when always (#332) * Add fixer for requireValidFileAnnotation when always * Add autofix note in readme --- README.md | 2 ++ src/rules/requireValidFileAnnotation.js | 14 +++++++++- .../assertions/requireValidFileAnnotation.js | 27 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3bf06533..546725bb 100644 --- a/README.md +++ b/README.md @@ -2437,6 +2437,8 @@ This rule validates Flow file annotations. This rule can optionally report missing or missed placed annotations, common typos (e.g. `// @floww`), and enforce a consistant annotation style. +This rule is autofixable with the `--fix` argument. This will autofix files by adding missing flow annotations to the top of each file. To avoid autofixing this rule per-file, you can add a `// @noflow` annotation to the top of individual files. + #### Options diff --git a/src/rules/requireValidFileAnnotation.js b/src/rules/requireValidFileAnnotation.js index 9db7d623..4ffabd7b 100644 --- a/src/rules/requireValidFileAnnotation.js +++ b/src/rules/requireValidFileAnnotation.js @@ -49,6 +49,14 @@ const create = (context) => { Program (node) { const firstToken = node.tokens[0]; + const addAnnotation = () => { + return (fixer) => { + const annotation = ['line', 'none'].includes(style) ? '// @flow\n' : '/* @flow */\n'; + + return fixer.replaceTextRange([node.start, node.start], annotation); + }; + }; + const potentialFlowFileAnnotation = _.find(context.getAllComments(), (comment) => { return looksLikeFlowFileAnnotation(comment.value); }); @@ -70,7 +78,11 @@ const create = (context) => { context.report(potentialFlowFileAnnotation, 'Malformed Flow file annotation.'); } } else if (always) { - context.report(node, 'Flow file annotation is missing.'); + context.report({ + fix: addAnnotation(), + message: 'Flow file annotation is missing.', + node + }); } } }; diff --git a/tests/rules/assertions/requireValidFileAnnotation.js b/tests/rules/assertions/requireValidFileAnnotation.js index c28983f5..57c5c1a3 100644 --- a/tests/rules/assertions/requireValidFileAnnotation.js +++ b/tests/rules/assertions/requireValidFileAnnotation.js @@ -122,6 +122,33 @@ export default { annotationStyle: 'block' } ] + }, + { + code: 'a;', + errors: [ + { + message: 'Flow file annotation is missing.' + } + ], + options: [ + 'always' + ], + output: '// @flow\na;' + }, + { + code: 'a;', + errors: [ + { + message: 'Flow file annotation is missing.' + } + ], + options: [ + 'always', + { + annotationStyle: 'block' + } + ], + output: '/* @flow */\na;' } ], misconfigured: [