summaryrefslogtreecommitdiff
path: root/tools/eslint-rules/require-buffer.js
blob: c6040b43a181fbcd9e164ea4daca6b8bdf5b0e70 (plain)
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
'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);
      }
    }
  };
};