/
regex-shorthand.js
100 lines (81 loc) · 2.1 KB
/
regex-shorthand.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
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
const cleanRegexp = require('clean-regexp');
const {optimize} = require('regexp-tree');
const getDocumentationUrl = require('./utils/get-documentation-url');
const quoteString = require('./utils/quote-string');
const message = 'Use regex shorthands to improve readability.';
const create = context => {
const {sortCharacterClasses} = context.options[0] || {};
const blacklist = [];
if (sortCharacterClasses === false) {
blacklist.push('charClassClassrangesMerge');
}
return {
'Literal[regex]': node => {
const {raw: original, regex} = node;
// Regular Expressions with `u` flag are not well handled by `regexp-tree`
// https://github.com/DmitrySoshnikov/regexp-tree/issues/162
if (regex.flags.includes('u')) {
return;
}
let optimized = original;
try {
optimized = optimize(original, undefined, {blacklist}).toString();
} catch (_) {}
if (original === optimized) {
return;
}
context.report({
node,
message: '{{original}} can be optimized to {{optimized}}',
data: {
original,
optimized
},
fix: fixer => fixer.replaceText(node, optimized)
});
},
'NewExpression[callee.name="RegExp"]': node => {
const arguments_ = node.arguments;
if (arguments_.length === 0 || arguments_[0].type !== 'Literal') {
return;
}
const hasRegExp = arguments_[0].regex;
if (hasRegExp) {
return;
}
const oldPattern = arguments_[0].value;
const flags = arguments_[1] && arguments_[1].type === 'Literal' ? arguments_[1].value : '';
const newPattern = cleanRegexp(oldPattern, flags);
if (oldPattern !== newPattern) {
// Escape backslash
const fixed = quoteString((newPattern || '').replace(/\\/g, '\\\\'));
context.report({
node,
message,
fix: fixer => fixer.replaceText(arguments_[0], fixed)
});
}
}
};
};
const schema = [{
type: 'object',
properties: {
sortCharacterClasses: {
type: 'boolean',
default: true
}
}
}];
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code',
schema
}
};