summaryrefslogtreecommitdiff
path: root/tools/eslint-rules/non-ascii-character.js
blob: e67aac7cd91e822ebf655ce61b83bbc344e55fc7 (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
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
/**
 * @fileOverview Any non-ASCII characters in lib/ will increase the size
 *               of the compiled node binary. This linter rule ensures that
 *               any such character is reported.
 * @author Sarat Addepalli <sarat.addepalli@gmail.com>
 */

'use strict';

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const nonAsciiRegexPattern = /[^\r\n\x20-\x7e]/;
const suggestions = {
  '’': '\'',
  '‛': '\'',
  '‘': '\'',
  '“': '"',
  '‟': '"',
  '”': '"',
  '«': '"',
  '»': '"',
  '—': '-'
};

module.exports = (context) => {

  const reportIfError = (node, sourceCode) => {

    const matches = sourceCode.text.match(nonAsciiRegexPattern);

    if (!matches) return;

    const offendingCharacter = matches[0];
    const offendingCharacterPosition = matches.index;
    const suggestion = suggestions[offendingCharacter];

    let message = `Non-ASCII character '${offendingCharacter}' detected.`;

    message = suggestion ?
      `${message} Consider replacing with: ${suggestion}` :
      message;

    context.report({
      node,
      message,
      loc: sourceCode.getLocFromIndex(offendingCharacterPosition),
      fix: (fixer) => {
        return fixer.replaceText(
          node,
          suggestion ? `${suggestion}` : ''
        );
      }
    });
  };

  return {
    Program: (node) => reportIfError(node, context.getSourceCode())
  };
};