/
no-console-spaces.js
87 lines (75 loc) · 2.06 KB
/
no-console-spaces.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
'use strict';
const {methodCallSelector} = require('./selectors/index.js');
const toLocation = require('./utils/to-location.js');
const MESSAGE_ID = 'no-console-spaces';
const messages = {
[MESSAGE_ID]: 'Do not use {{position}} space between `console.{{method}}` parameters.',
};
const methods = [
'log',
'debug',
'info',
'warn',
'error',
];
const selector = methodCallSelector({
methods,
minimumArguments: 1,
object: 'console',
});
// Find exactly one leading space, allow exactly one space
const hasLeadingSpace = value => value.length > 1 && value.charAt(0) === ' ' && value.charAt(1) !== ' ';
// Find exactly one trailing space, allow exactly one space
const hasTrailingSpace = value => value.length > 1 && value.charAt(value.length - 1) === ' ' && value.charAt(value.length - 2) !== ' ';
const create = context => {
const sourceCode = context.getSourceCode();
const getProblem = (node, method, position) => {
const index = position === 'leading'
? node.range[0] + 1
: node.range[1] - 2;
const range = [index, index + 1];
return {
loc: toLocation(range, sourceCode),
messageId: MESSAGE_ID,
data: {method, position},
fix: fixer => fixer.removeRange(range),
};
};
return {
* [selector](node) {
const method = node.callee.property.name;
const {arguments: messages} = node;
const {length} = messages;
for (const [index, node] of messages.entries()) {
const {type, value} = node;
if (
!(type === 'Literal' && typeof value === 'string')
&& type !== 'TemplateLiteral'
) {
continue;
}
const raw = sourceCode.getText(node).slice(1, -1);
if (index !== 0 && hasLeadingSpace(raw)) {
yield getProblem(node, method, 'leading');
}
if (index !== length - 1 && hasTrailingSpace(raw)) {
yield getProblem(node, method, 'trailing');
}
}
},
};
};
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Do not use leading/trailing space between `console.log` parameters.',
},
fixable: 'code',
messages,
},
};