diff options
author | Bamieh <ahmadbamieh@gmail.com> | 2017-11-20 03:22:28 +0200 |
---|---|---|
committer | Anna Henningsen <anna@addaleax.net> | 2017-11-28 02:53:02 +0100 |
commit | 0319a5e1805bf7728d6116990cb9b7f00f726653 (patch) | |
tree | af9ce6989ec15771b10226bcb44e6aa053ab1756 /tools | |
parent | 2219859675743f158c46178464b2db042a6b3294 (diff) | |
download | node-new-0319a5e1805bf7728d6116990cb9b7f00f726653.tar.gz |
tools: add lint fixer for `require-buffer`
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 <targos@protonmail.com>
Diffstat (limited to 'tools')
-rw-r--r-- | tools/eslint-rules/require-buffer.js | 18 |
1 files changed, 17 insertions, 1 deletions
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 { |