From 0319a5e1805bf7728d6116990cb9b7f00f726653 Mon Sep 17 00:00:00 2001 From: Bamieh Date: Mon, 20 Nov 2017 03:22:28 +0200 Subject: tools: add lint fixer for `require-buffer` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds `require-buffer` lint fixer. If the buffer module is not required while `Buffer` is used, require the `buffer` module. If the file has a `'use strict';` line, add the require after it on a separate line. If the file does not have any (currently impossible with the `strict` rule) add it after the first comment (before the real code starts). Fixes: https://github.com/nodejs/node/issues/16636 PR-URL: https://github.com/nodejs/node/pull/17144 Reviewed-By: Michaƫl Zasso --- tools/eslint-rules/require-buffer.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'tools') diff --git a/tools/eslint-rules/require-buffer.js b/tools/eslint-rules/require-buffer.js index c9818cb758..c6040b43a1 100644 --- a/tools/eslint-rules/require-buffer.js +++ b/tools/eslint-rules/require-buffer.js @@ -1,10 +1,26 @@ 'use strict'; +const BUFFER_REQUIRE = 'const { Buffer } = require(\'buffer\');\n'; module.exports = function(context) { + function flagIt(reference) { const msg = 'Use const Buffer = require(\'buffer\').Buffer; ' + 'at the beginning of this file'; - context.report(reference.identifier, msg); + + context.report({ + node: reference.identifier, + message: msg, + fix: (fixer) => { + const sourceCode = context.getSourceCode(); + + const useStrict = /'use strict';\n\n?/g; + const hasUseStrict = !!useStrict.exec(sourceCode.text); + const firstLOC = sourceCode.ast.range[0]; + const rangeNeedle = hasUseStrict ? useStrict.lastIndex : firstLOC; + + return fixer.insertTextBeforeRange([rangeNeedle], BUFFER_REQUIRE); + } + }); } return { -- cgit v1.2.3