From a087fe6a3c54ecf0b9d6e117b3bee9a6b5ccb906 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anton=20Str=C3=B6mkvist?= Date: Wed, 2 Nov 2016 14:08:55 +0100 Subject: [PATCH] feat: Add excludeVariableMatch option to require-variable-type Enable ignoring variables that match a certain regex --- .README/rules/require-variable-type.md | 21 ++++++++++++++++++ src/rules/requireVariableType.js | 9 +++++++- tests/rules/assertions/requireVariableType.js | 22 ++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/.README/rules/require-variable-type.md b/.README/rules/require-variable-type.md index 0665f2db..92745f2a 100644 --- a/.README/rules/require-variable-type.md +++ b/.README/rules/require-variable-type.md @@ -2,4 +2,25 @@ Requires that all variable declarators have type annotations. +#### Options + +You can exclude variables that match a certain regex by using `excludeVariableMatch`. + +This excludes all parameters that start with an underscore (`_`). +The default pattern is `a^`, which doesn't match anything, i.e., all parameters are checked. + +```js +{ + "rules": { + "flowtype/require-variable-type": [ + 2, + { + "excludeVariableMatch": "^_" + } + ] + } +} +``` + + diff --git a/src/rules/requireVariableType.js b/src/rules/requireVariableType.js index db324643..7d2ddd3d 100644 --- a/src/rules/requireVariableType.js +++ b/src/rules/requireVariableType.js @@ -11,13 +11,20 @@ export default (context) => { return () => {}; } + const excludeVariableMatch = new RegExp(_.get(context, 'options[0].excludeVariableMatch', 'a^')); + return { VariableDeclaration: (variableDeclaration) => { _.forEach(variableDeclaration.declarations, (variableDeclarator) => { const identifierNode = _.get(variableDeclarator, 'id'); - const typeAnnotation = _.get(identifierNode, 'typeAnnotation'); const identifierName = _.get(identifierNode, 'name'); + if (excludeVariableMatch.test(identifierName)) { + return; + } + + const typeAnnotation = _.get(identifierNode, 'typeAnnotation'); + if (!typeAnnotation) { context.report({ data: { diff --git a/tests/rules/assertions/requireVariableType.js b/tests/rules/assertions/requireVariableType.js index 7407bf25..3b08b66f 100644 --- a/tests/rules/assertions/requireVariableType.js +++ b/tests/rules/assertions/requireVariableType.js @@ -15,8 +15,20 @@ export default { message: 'Missing "bar" variable type annotation.' } ] + }, + { + code: 'var _foo = "bar", bar = 1', + errors: [ + { + message: 'Missing "bar" variable type annotation.' + } + ], + options: [ + { + excludeVariableMatch: '^_' + } + ] } - ], valid: [ { @@ -24,6 +36,14 @@ export default { }, { code: 'var foo : string = "bar", bar : number = 1' + }, + { + code: 'var _foo = "bar", bar : number = 1', + options: [ + { + excludeVariableMatch: '^_' + } + ] } ] };