/
prevent-abbreviations.js
727 lines (609 loc) · 17 KB
/
prevent-abbreviations.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
'use strict';
const astUtils = require('eslint-ast-utils');
const defaultsDeep = require('lodash.defaultsdeep');
const toPairs = require('lodash.topairs');
const camelCase = require('lodash.camelcase');
const kebabCase = require('lodash.kebabcase');
const upperfirst = require('lodash.upperfirst');
const getDocsUrl = require('./utils/get-docs-url');
const avoidCapture = require('./utils/avoid-capture');
const pascalCase = string => upperfirst(camelCase(string));
const isPascalCase = string => string === pascalCase(string);
const isUpperCase = string => string === string.toUpperCase();
const defaultReplacements = {
err: {
error: true
},
cb: {
callback: true
},
opts: {
options: true
},
str: {
string: true
},
obj: {
object: true
},
num: {
number: true
},
val: {
value: true
},
e: {
event: true,
error: true
},
evt: {
event: true
},
el: {
element: true
},
req: {
request: true
},
res: {
response: true,
result: true
},
btn: {
button: true
},
msg: {
message: true
},
len: {
length: true
},
env: {
environment: true
},
dev: {
development: true
},
prod: {
production: true
},
tmp: {
temporary: true
},
arg: {
argument: true
},
args: {
arguments: true
},
tbl: {
table: true
},
db: {
database: true
},
ctx: {
context: true
},
mod: {
module: true
},
prop: {
property: true
},
arr: {
array: true
},
ret: {
returnValue: true
},
retval: {
returnValue: true
},
ext: {
extension: true
},
exts: {
extensions: true
},
lib: {
library: true
},
dir: {
directory: true
},
dirs: {
directories: true
},
ref: {
reference: true
},
refs: {
references: true
},
pkg: {
package: true
},
sep: {
separator: true
},
doc: {
document: true
},
docs: {
documents: true
},
elem: {
element: true
},
src: {
source: true
},
dest: {
destination: true
},
prev: {
previous: true
},
rel: {
relative: true,
related: true,
relationship: true
},
conf: {
config: true
},
temp: {
temporary: true
},
props: {
properties: true
},
attr: {
attribute: true
},
attrs: {
attributes: true
}
};
const defaultWhitelist = {
propTypes: true,
defaultProps: true,
getDerivedStateFromProps: true,
stdDev: true
};
const prepareOptions = ({
checkProperties = true,
checkVariables = true,
checkDefaultAndNamespaceImports = false,
checkShorthandImports = false,
checkShorthandProperties = false,
extendDefaultReplacements = true,
replacements = {},
extendDefaultWhitelist = true,
whitelist = {}
} = {}) => {
const mergedReplacements = extendDefaultReplacements ?
defaultsDeep({}, replacements, defaultReplacements) :
replacements;
const mergedWhitelist = extendDefaultWhitelist ?
defaultsDeep({}, whitelist, defaultWhitelist) :
whitelist;
return {
checkProperties,
checkVariables,
checkDefaultAndNamespaceImports,
checkShorthandImports,
checkShorthandProperties,
replacements: new Map(toPairs(mergedReplacements).map(([discouragedName, replacements]) => {
return [discouragedName, new Map(toPairs(replacements))];
})),
whitelist: new Map(toPairs(mergedWhitelist))
};
};
const normalizeName = name => {
let originalLeadingUnderscores;
let originalTrailingUnderscores;
([, originalLeadingUnderscores, name, originalTrailingUnderscores] = /^(_*)(.*?)(_*)$/.exec(name));
const originalIsInPascalCase = isPascalCase(name);
if (originalIsInPascalCase) {
name = camelCase(name);
}
return {
originalLeadingUnderscores,
originalTrailingUnderscores,
originalIsInPascalCase,
normalizedName: name
};
};
const createApplyOriginalUnderscores = (originalLeadingUnderscores, originalTrailingUnderscores) => name => {
return originalLeadingUnderscores + name + originalTrailingUnderscores;
};
const splitNormalizedName = normalizedName => {
return kebabCase(normalizedName).split('-');
};
const getWordReplacements = (replacements, word) => {
const wordReplacements = replacements.get(word);
if (!wordReplacements) {
return [];
}
return [...wordReplacements.keys()].filter(name => wordReplacements.get(name));
};
/*
* This function has terrible big O complexity, so we limit it by `limit`.
* This is fine since result of the function is used only to check if there is zero, one or more
* replacements and when formating the message.
* Example: `[[1, 2], [3, 4]]` -> `[[1, 3], [1, 4], [2, 3], [2, 4]]`
*/
const getWordByWordReplacementsCombinations = (wordByWordReplacements, limit = 16) => {
if (wordByWordReplacements.length === 0) {
return [];
}
if (wordByWordReplacements.length === 1) {
return wordByWordReplacements[0];
}
if (limit <= 1) {
return wordByWordReplacements[0];
}
const [wordReplacements, ...tailWordReplacements] = wordByWordReplacements;
const tailCombinations = getWordByWordReplacementsCombinations(tailWordReplacements, limit / wordReplacements.length);
const result = [];
for (const name of wordReplacements) {
for (const combination of tailCombinations) {
result.push([name].concat(combination));
}
}
return result;
};
const getWordByWordReplacements = (replacements, normalizedName, originalIsInPascalCase) => {
const words = splitNormalizedName(normalizedName);
let wordByWordReplacements = words.map(word => getWordReplacements(replacements, word));
const someWordsHaveReplacements = wordByWordReplacements.some(wordReplacements => wordReplacements.length > 0);
if (!someWordsHaveReplacements) {
return [];
}
wordByWordReplacements = wordByWordReplacements
.map((wordReplacements, i) => wordReplacements.length > 0 ? wordReplacements : [words[i]]);
return getWordByWordReplacementsCombinations(wordByWordReplacements)
.map(originalIsInPascalCase ? pascalCase : camelCase)
.sort();
};
const getExactReplacements = (replacements, normalizedName, originalIsInPascalCase) => {
const variableNameReplacements = replacements.get(normalizedName);
if (!variableNameReplacements) {
return [];
}
return [...variableNameReplacements.keys()]
.filter(name => variableNameReplacements.get(name))
.map(originalIsInPascalCase ? pascalCase : name => name)
.sort();
};
const getNameReplacements = (replacements, whitelist, name) => {
if (whitelist.get(name)) {
return [];
}
if (isUpperCase(name)) {
return [];
}
const {
originalLeadingUnderscores,
originalTrailingUnderscores,
originalIsInPascalCase,
normalizedName
} = normalizeName(name);
const applyOriginalUnderscores = createApplyOriginalUnderscores(originalLeadingUnderscores, originalTrailingUnderscores);
const exactReplacements = getExactReplacements(replacements, normalizedName, originalIsInPascalCase);
if (exactReplacements.length > 0) {
return exactReplacements.map(applyOriginalUnderscores);
}
return getWordByWordReplacements(replacements, normalizedName, originalIsInPascalCase).map(applyOriginalUnderscores);
};
const anotherNameMessage = 'A more descriptive name will do too.';
const formatMessage = (discouragedName, replacements, nameTypeText, replacementsLimit = 3) => {
const message = [];
if (replacements.length === 1) {
message.push(`The ${nameTypeText} \`${discouragedName}\` should be named \`${replacements[0]}\`.`);
} else {
let replacementsText = replacements.slice(0, replacementsLimit)
.map(replacement => `\`${replacement}\``)
.join(', ');
const omittedReplacementsCount = replacements.length - replacementsLimit;
if (omittedReplacementsCount > 0) {
replacementsText += `, ... (${omittedReplacementsCount} more omitted)`;
}
message.push(`Please rename the ${nameTypeText} \`${discouragedName}\`.`);
message.push(`Suggested names are: ${replacementsText}.`);
}
message.push(anotherNameMessage);
return message.join(' ');
};
const variableIdentifiers = variable => [...(new Set([
...variable.identifiers,
...variable.references
.map(reference => reference.identifier)
])).values()];
const isExportedIdentifier = identifier => {
if (identifier.parent.type === 'VariableDeclarator' &&
identifier.parent.id === identifier
) {
return identifier.parent.parent.type === 'VariableDeclaration' &&
identifier.parent.parent.parent.type === 'ExportNamedDeclaration';
}
if (identifier.parent.type === 'FunctionDeclaration' &&
identifier.parent.id === identifier
) {
return identifier.parent.parent.type === 'ExportNamedDeclaration';
}
if (identifier.parent.type === 'ClassDeclaration' &&
identifier.parent.id === identifier
) {
return identifier.parent.parent.type === 'ExportNamedDeclaration';
}
return false;
};
const shouldFix = variable => {
return !variableIdentifiers(variable).some(isExportedIdentifier);
};
const isShorthandPropertyIdentifier = identifier => {
return identifier.parent.type === 'Property' &&
identifier.parent.shorthand;
};
const isShorthandImportIdentifier = identifier => {
return identifier.parent.type === 'ImportSpecifier' &&
identifier.parent.imported.name === identifier.name &&
identifier.parent.local.name === identifier.name;
};
const isShorthandExportIdentifier = identifier => {
return identifier.parent.type === 'ExportSpecifier' &&
identifier.parent.exported.name === identifier.name &&
identifier.parent.local.name === identifier.name;
};
const fixIdentifier = (fixer, replacement) => identifier => {
if (isShorthandPropertyIdentifier(identifier)) {
return fixer.replaceText(identifier, `${identifier.name}: ${replacement}`);
}
if (isShorthandImportIdentifier(identifier)) {
return fixer.replaceText(identifier, `${identifier.name} as ${replacement}`);
}
if (isShorthandExportIdentifier(identifier)) {
return fixer.replaceText(identifier, `${replacement} as ${identifier.name}`);
}
return fixer.replaceText(identifier, replacement);
};
const isDefaultOrNamespaceImportName = identifier => {
if (identifier.parent.type === 'ImportDefaultSpecifier' &&
identifier.parent.local === identifier
) {
return true;
}
if (identifier.parent.type === 'ImportNamespaceSpecifier' &&
identifier.parent.local === identifier
) {
return true;
}
if (identifier.parent.type === 'ImportSpecifier' &&
identifier.parent.local === identifier &&
identifier.parent.imported.type === 'Identifier' &&
identifier.parent.imported.name === 'default'
) {
return true;
}
if (identifier.parent.type === 'VariableDeclarator' &&
identifier.parent.id === identifier &&
astUtils.isStaticRequire(identifier.parent.init)
) {
return true;
}
return false;
};
const isClassVariable = variable => {
if (variable.defs.length !== 1) {
return false;
}
const [definition] = variable.defs;
return definition.type === 'ClassName';
};
const shouldReportIdentifierAsProperty = identifier => {
if (identifier.parent.type === 'MemberExpression' &&
identifier.parent.property === identifier &&
!identifier.parent.computed &&
identifier.parent.parent.type === 'AssignmentExpression' &&
identifier.parent.parent.left === identifier.parent
) {
return true;
}
if (identifier.parent.type === 'Property' &&
identifier.parent.key === identifier &&
!identifier.parent.computed &&
!identifier.parent.shorthand && // Shorthand properties are reported and fixed as variables
identifier.parent.parent.type === 'ObjectExpression'
) {
return true;
}
if (identifier.parent.type === 'ExportSpecifier' &&
identifier.parent.exported === identifier &&
identifier.parent.local !== identifier // Same as shorthand properties above
) {
return true;
}
if (identifier.parent.type === 'MethodDefinition' &&
identifier.parent.key === identifier &&
!identifier.parent.computed
) {
return true;
}
if (identifier.parent.type === 'ClassProperty' &&
identifier.parent.key === identifier &&
!identifier.parent.computed
) {
return true;
}
return false;
};
const create = context => {
const {
ecmaVersion
} = context.parserOptions;
const options = prepareOptions(context.options[0]);
// A `class` declaration produces two variables in two scopes:
// the inner class scope, and the outer one (whereever the class is declared).
// This map holds the outer ones to be later processed when the inner one is encountered.
// For why this is not a eslint issue see https://github.com/eslint/eslint-scope/issues/48#issuecomment-464358754
const identifierToOuterClassVariable = new WeakMap();
const checkPossiblyWeirdClassVariable = variable => {
if (isClassVariable(variable)) {
if (variable.scope.type === 'class') { // The inner class variable
const [definition] = variable.defs;
const outerClassVariable = identifierToOuterClassVariable.get(definition.name);
if (!outerClassVariable) {
return checkVariable(variable);
}
// Create a normal-looking variable (like a `var` or a `function`)
// For which a single `variable` holds all references, unline with `class`
const combinedReferencesVariable = {
name: variable.name,
scope: variable.scope,
defs: variable.defs,
identifiers: variable.identifiers,
references: variable.references.concat(outerClassVariable.references)
};
// Call the common checker with the newly forged normalized class variable
return checkVariable(combinedReferencesVariable);
}
// The outer class variable, we save it for later, when it's inner counterpart is encountered
const [definition] = variable.defs;
identifierToOuterClassVariable.set(definition.name, variable);
return;
}
return checkVariable(variable);
};
// Holds a map from a `Scope` to a `Set` of new variable names generated by our fixer.
// Used to avoid generating duplicate names, see for instance `let errCb, errorCb` test.
const scopeToNamesGeneratedByFixer = new WeakMap();
const isSafeName = (name, scopes) => scopes.every(scope => {
const generatedNames = scopeToNamesGeneratedByFixer.get(scope);
return !generatedNames || !generatedNames.has(name);
});
const checkVariable = variable => {
if (variable.defs.length === 0) {
return;
}
const [definition] = variable.defs;
if (!options.checkDefaultAndNamespaceImports && isDefaultOrNamespaceImportName(definition.name)) {
return;
}
if (!options.checkShorthandImports && isShorthandImportIdentifier(definition.name)) {
return;
}
if (!options.checkShorthandProperties && isShorthandPropertyIdentifier(definition.name)) {
return;
}
const variableReplacements = getNameReplacements(options.replacements, options.whitelist, variable.name);
if (variableReplacements.length === 0) {
return;
}
const scopes = variable.references.map(reference => reference.from).concat(variable.scope);
const problem = {
node: definition.name,
message: formatMessage(definition.name.name, variableReplacements, 'variable')
};
if (variableReplacements.length === 1 && shouldFix(variable)) {
const [replacement] = variableReplacements;
const captureAvoidingReplacement = avoidCapture(replacement, scopes, ecmaVersion, isSafeName);
for (const scope of scopes) {
if (!scopeToNamesGeneratedByFixer.has(scope)) {
scopeToNamesGeneratedByFixer.set(scope, new Set());
}
const generatedNames = scopeToNamesGeneratedByFixer.get(scope);
generatedNames.add(captureAvoidingReplacement);
}
problem.fix = fixer => {
return variableIdentifiers(variable)
.map(fixIdentifier(fixer, captureAvoidingReplacement));
};
}
context.report(problem);
};
const checkVariables = scope => {
scope.variables.forEach(checkPossiblyWeirdClassVariable);
};
const checkChildScopes = scope => {
scope.childScopes.forEach(checkScope);
};
const checkScope = scope => {
checkVariables(scope);
return checkChildScopes(scope);
};
return {
Identifier(node) {
if (!options.checkProperties) {
return;
}
if (node.name === '__proto__') {
return;
}
const identifierReplacements = getNameReplacements(options.replacements, options.whitelist, node.name);
if (identifierReplacements.length === 0) {
return;
}
if (!shouldReportIdentifierAsProperty(node)) {
return;
}
const problem = {
node,
message: formatMessage(node.name, identifierReplacements, 'property')
};
context.report(problem);
},
'Program:exit'() {
if (!options.checkVariables) {
return;
}
checkScope(context.getScope());
}
};
};
const schema = [{
type: 'object',
properties: {
checkProperties: {type: 'boolean'},
checkVariables: {type: 'boolean'},
checkDefaultAndNamespaceImports: {type: 'boolean'},
checkShorthandImports: {type: 'boolean'},
checkShorthandProperties: {type: 'boolean'},
extendDefaultReplacements: {type: 'boolean'},
replacements: {$ref: '#/items/0/definitions/abbreviations'},
extendDefaultWhitelist: {type: 'boolean'},
whitelist: {$ref: '#/items/0/definitions/booleanObject'}
},
additionalProperties: false,
definitions: {
abbreviations: {
type: 'object',
additionalProperties: {$ref: '#/items/0/definitions/replacements'}
},
replacements: {
anyOf: [
{
enum: [false]
},
{$ref: '#/items/0/definitions/booleanObject'}
]
},
booleanObject: {
type: 'object',
additionalProperties: {type: 'boolean'}
}
}
}];
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocsUrl(__filename)
},
fixable: 'code',
schema
}
};