forked from sindresorhus/eslint-plugin-unicorn
/
no-new-buffer.js
94 lines (83 loc) · 2.16 KB
/
no-new-buffer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const {getStaticValue} = require('eslint-utils');
const {newExpressionSelector} = require('./selectors/index.js');
const {switchNewExpressionToCallExpression} = require('./fix/index.js');
const ERROR = 'error';
const ERROR_UNKNOWN = 'error-unknown';
const SUGGESTION = 'suggestion';
const messages = {
[ERROR]: '`new Buffer()` is deprecated, use `Buffer.{{method}}()` instead.',
[ERROR_UNKNOWN]: '`new Buffer()` is deprecated, use `Buffer.alloc()` or `Buffer.from()` instead.',
[SUGGESTION]: 'Switch to `Buffer.{{method}}()`.',
};
const inferMethod = (bufferArguments, scope) => {
if (bufferArguments.length !== 1) {
return 'from';
}
const [firstArgument] = bufferArguments;
if (firstArgument.type === 'SpreadElement') {
return;
}
if (firstArgument.type === 'ArrayExpression' || firstArgument.type === 'TemplateLiteral') {
return 'from';
}
const staticResult = getStaticValue(firstArgument, scope);
if (staticResult) {
const {value} = staticResult;
if (typeof value === 'number') {
return 'alloc';
}
if (
typeof value === 'string'
|| Array.isArray(value)
) {
return 'from';
}
}
};
function fix(node, sourceCode, method) {
return function * (fixer) {
yield fixer.insertTextAfter(node.callee, `.${method}`);
yield * switchNewExpressionToCallExpression(node, sourceCode, fixer);
};
}
const create = context => {
const sourceCode = context.getSourceCode();
return {
[newExpressionSelector('Buffer')]: node => {
const method = inferMethod(node.arguments, context.getScope());
if (method) {
return {
node,
messageId: ERROR,
data: {method},
fix: fix(node, sourceCode, method),
};
}
return {
node,
messageId: ERROR_UNKNOWN,
suggest: ['from', 'alloc'].map(method => ({
messageId: SUGGESTION,
data: {method},
fix: fix(node, sourceCode, method),
})),
};
},
};
};
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'problem',
docs: {
description: 'Enforce the use of `Buffer.from()` and `Buffer.alloc()` instead of the deprecated `new Buffer()`.',
},
fixable: 'code',
hasSuggestions: true,
messages,
},
};