Skip to content

Commit

Permalink
tools: auto fix custom eslint rule for buffer-constructor.js
Browse files Browse the repository at this point in the history
This implements a fixer method to fix the usage of Deprecated Buffer() constructor.

Also adds some more test cases to the eslint rule.

Refs: nodejs#16636
  • Loading branch information
shobhitchittora committed Nov 1, 2017
1 parent 46ca177 commit aebc0c5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
15 changes: 14 additions & 1 deletion test/parallel/test-eslint-buffer-constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,29 @@ const message = 'Use of the Buffer() constructor has been deprecated. ' +

new RuleTester().run('buffer-constructor', rule, {
valid: [
'Buffer.from(foo)'
'Buffer.from(foo)',
'Buffer.from(foo, bar)',
'Buffer.alloc(foo)',
'Buffer.alloc(foo, bar)',
'Buffer.allocUnsafe(foo)',
'Buffer.allocUnsafe(foo, bar)'
],
invalid: [
{
code: 'Buffer(foo)',
errors: [{ message }]
},
{
code: 'Buffer(foo, bar)',
errors: [{ message }]
},
{
code: 'new Buffer(foo)',
errors: [{ message }]
},
{
code: 'new Buffer(foo, bar)',
errors: [{ message }]
}
]
});
17 changes: 16 additions & 1 deletion tools/eslint-rules/buffer-constructor.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,22 @@ const msg = 'Use of the Buffer() constructor has been deprecated. ' +

function test(context, node) {
if (node.callee.name === 'Buffer') {
context.report(node, msg);
const sourceCode = context.getSourceCode();
const argumentList = [];
node.arguments.forEach((argumentNode) => {
argumentList.push(sourceCode.getText(argumentNode));
});

context.report({
node,
message: msg,
fix: (fixer) => {
return fixer.replaceText(
node,
`Buffer.from(${argumentList.join(', ')})`
);
}
});
}
}

Expand Down

0 comments on commit aebc0c5

Please sign in to comment.