Skip to content

Commit

Permalink
tools: add lint fixer for require-buffer
Browse files Browse the repository at this point in the history
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: #16636
PR-URL: #17144
Reviewed-By: Michaël Zasso <[email protected]>
  • Loading branch information
Bamieh authored and MylesBorins committed Dec 12, 2017
1 parent 06da8a7 commit b7f81ae
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
29 changes: 25 additions & 4 deletions test/parallel/test-eslint-require-buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,36 @@ const ruleTester = new RuleTester({
const message = "Use const Buffer = require('buffer').Buffer; " +
'at the beginning of this file';

const useStrict = '\'use strict\';\n\n';
const bufferModule = 'const { Buffer } = require(\'buffer\');\n';
const mockComment = '// Some Comment\n//\n// Another Comment\n\n';
const useBuffer = 'Buffer;';
ruleTester.run('require-buffer', rule, {
valid: [
'foo',
'const Buffer = require("Buffer"); Buffer;'
'const Buffer = require("Buffer"); Buffer;',
'const { Buffer } = require(\'buffer\'); Buffer;',
],
invalid: [
{
code: 'Buffer;',
errors: [{ message }]
}
code: useBuffer,
errors: [{ message }],
output: bufferModule + useBuffer,
},
{
code: useStrict + useBuffer,
errors: [{ message }],
output: useStrict + bufferModule + useBuffer,
},
{
code: mockComment + useBuffer,
errors: [{ message }],
output: mockComment + bufferModule + useBuffer,
},
{
code: mockComment + useStrict + useBuffer,
errors: [{ message }],
output: mockComment + useStrict + bufferModule + useBuffer,
},
]
});
18 changes: 17 additions & 1 deletion tools/eslint-rules/require-buffer.js
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down

0 comments on commit b7f81ae

Please sign in to comment.