Skip to content

Commit

Permalink
Fix no-new-buffer crash on TypeScript-ESLint (#560)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Feb 16, 2020
1 parent 048ddfc commit e4f4bb4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 14 additions & 2 deletions rules/no-new-buffer.js
@@ -1,15 +1,27 @@
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');

const inferMethod = arguments_ => (arguments_.length > 0 && typeof arguments_[0].value === 'number') ? 'alloc' : 'from';
const inferMethod = arguments_ => {
if (arguments_.length > 0) {
const [firstArgument] = arguments_;
if (
firstArgument.type === 'Literal' &&
typeof firstArgument.value === 'number'
) {
return 'alloc';
}
}

return 'from';
};

const create = context => {
return {
'NewExpression[callee.name="Buffer"]': node => {
const method = inferMethod(node.arguments);
const range = [
node.range[0],
node.callee.end
node.callee.range[1]
];

context.report({
Expand Down
15 changes: 15 additions & 0 deletions test/no-new-buffer.js
Expand Up @@ -12,6 +12,10 @@ const ruleTester = avaRuleTester(test, {
}
});

const typescriptRuleTester = avaRuleTester(test, {
parser: require.resolve('@typescript-eslint/parser')
});

const allocError = {
ruleId: 'no-new-buffer',
message: '`new Buffer()` is deprecated, use `Buffer.alloc()` instead.'
Expand Down Expand Up @@ -79,3 +83,14 @@ ruleTester.run('no-new-buffer', rule, {
}
]
});

typescriptRuleTester.run('no-new-buffer', rule, {
valid: [],
invalid: [
{
code: 'new Buffer(input, encoding);',
errors: [fromError],
output: 'Buffer.from(input, encoding);'
}
]
});

0 comments on commit e4f4bb4

Please sign in to comment.