mirror of
https://github.com/nodejs/node.git
synced 2024-12-01 16:10:02 +01:00
0319a5e180
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>
36 lines
990 B
JavaScript
36 lines
990 B
JavaScript
'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({
|
|
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 {
|
|
'Program:exit': function() {
|
|
const globalScope = context.getScope();
|
|
const variable = globalScope.set.get('Buffer');
|
|
if (variable) {
|
|
variable.references.forEach(flagIt);
|
|
}
|
|
}
|
|
};
|
|
};
|