-
-
Notifications
You must be signed in to change notification settings - Fork 384
/
Copy pathno-console-spaces.js
87 lines (76 loc) · 2.13 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 toLocation = require('./utils/to-location.js');
const {isStringLiteral, isMethodCall} = require('./ast/index.js');
const MESSAGE_ID = 'no-console-spaces';
const messages = {
[MESSAGE_ID]: 'Do not use {{position}} space between `console.{{method}}` parameters.',
};
// 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.at(-1) === ' ' && value.at(-2) !== ' ';
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const {sourceCode} = context;
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 {
* CallExpression(node) {
if (
!isMethodCall(node, {
object: 'console',
methods: [
'log',
'debug',
'info',
'warn',
'error',
],
minimumArguments: 1,
optionalCall: false,
optionalMember: false,
})
) {
return;
}
const method = node.callee.property.name;
const {arguments: messages} = node;
const {length} = messages;
for (const [index, node] of messages.entries()) {
if (!isStringLiteral(node) && node.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.',
recommended: true,
},
fixable: 'code',
messages,
},
};