UNPKG

1.98 kBJavaScriptView Raw
1'use strict';
2const getDocumentationUrl = require('./utils/get-documentation-url');
3const methodSelector = require('./utils/method-selector');
4const replaceStringRaw = require('./utils/replace-string-raw');
5
6const message = 'Do not use leading/trailing space between `console.{{method}}` parameters.';
7
8const methods = [
9 'log',
10 'debug',
11 'info',
12 'warn',
13 'error'
14];
15
16const selector = methodSelector({
17 names: methods,
18 min: 1,
19 object: 'console'
20});
21
22// Find exactly one leading space, allow exactly one space
23const fixLeadingSpace = value =>
24 value.length > 1 && value.charAt(0) === ' ' && value.charAt(1) !== ' ' ?
25 value.slice(1) :
26 value;
27
28// Find exactly one trailing space, allow exactly one space
29const fixTrailingSpace = value =>
30 value.length > 1 && value.charAt(value.length - 1) === ' ' && value.charAt(value.length - 2) !== ' ' ?
31 value.slice(0, -1) :
32 value;
33
34const create = context => {
35 const sourceCode = context.getSourceCode();
36
37 const fixParamter = (node, index, parameters) => {
38 if (
39 !(node.type === 'Literal' && typeof node.value === 'string') &&
40 node.type !== 'TemplateLiteral'
41 ) {
42 return;
43 }
44
45 const raw = sourceCode.getText(node).slice(1, -1);
46
47 let fixed = raw;
48
49 if (index !== 0) {
50 fixed = fixLeadingSpace(fixed);
51 }
52
53 if (index !== parameters.length - 1) {
54 fixed = fixTrailingSpace(fixed);
55 }
56
57 if (raw !== fixed) {
58 return {
59 node,
60 fixed
61 };
62 }
63 };
64
65 return {
66 [selector](node) {
67 const method = node.callee.property.name;
68 const fixedParameters = node.arguments
69 .map((parameter, index) => fixParamter(parameter, index, node.arguments))
70 .filter(Boolean);
71
72 for (const {node, fixed} of fixedParameters) {
73 context.report({
74 node,
75 message,
76 data: {method},
77 fix: fixer => replaceStringRaw(fixer, node, fixed)
78 });
79 }
80 }
81 };
82};
83
84module.exports = {
85 create,
86 meta: {
87 type: 'suggestion',
88 docs: {
89 url: getDocumentationUrl(__filename)
90 },
91 fixable: 'code'
92 }
93};