This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 198
/
importNameRule.ts
301 lines (264 loc) · 11.1 KB
/
importNameRule.ts
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
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';
import { Utils } from './utils/Utils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
import { isObject } from './utils/TypeGuard';
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: ExtendedMetadata = {
ruleName: 'import-name',
type: 'maintainability',
description: 'The name of the imported module must match the name of the thing being imported',
hasFix: true,
options: null, // tslint:disable-line:no-null-keyword
optionsDescription: '',
optionExamples: [
[true],
[true, { moduleName: 'importedName' }],
[true, { moduleName: 'importedName' }, ['moduleName1', 'moduleName2']],
[true, { moduleName: 'importedName' }, ['moduleName1', 'moduleName2'], { ignoreExternalModule: false }]
],
typescriptOnly: true,
issueClass: 'Ignored',
issueType: 'Warning',
severity: 'Low',
level: 'Opportunity for Excellence',
group: 'Clarity',
commonWeaknessEnumeration: '710'
};
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions()));
}
private parseOptions(options: Lint.IOptions): Option {
const result: Option = {
replacements: {},
ignoredList: [],
config: {
ignoreExternalModule: true,
case: StringCase.camel
}
};
if (options.ruleArguments instanceof Array) {
options.ruleArguments.forEach((opt: unknown, index: number) => {
if (index === 1 && isObject(opt)) {
result.replacements = this.extractReplacements(opt);
}
if (index === 2 && Array.isArray(opt)) {
result.ignoredList = this.extractIgnoredList(opt);
}
if (index === 3 && isObject(opt)) {
result.config = this.extractConfig(opt);
}
});
}
return result;
}
private extractReplacements(opt: Replacement | unknown): Replacement {
const result: Replacement = {};
if (isObject(opt)) {
Object.keys(opt).forEach(
(key: string): void => {
const value: unknown = opt[key];
if (typeof value === 'string') {
result[key] = value;
}
}
);
}
return result;
}
private extractIgnoredList(opt: IgnoredList): IgnoredList {
return opt.filter((moduleName: string) => typeof moduleName === 'string');
}
private extractConfig(opt: unknown): Config {
const result: Config = { ignoreExternalModule: true, case: StringCase.camel };
const configKeyList: ConfigKey[] = ['ignoreExternalModule', 'case'];
if (isObject(opt)) {
return Object.keys(opt).reduce(
(accum: Config, key: string) => {
if (configKeyList.filter((configKey: string) => configKey === key).length >= 1) {
accum[<ConfigKey>key] = <boolean | StringCase>opt[key];
return accum;
}
return accum;
},
{ ignoreExternalModule: true, case: StringCase.camel }
);
}
return result;
}
}
enum StringCase {
any = 'any-case',
pascal = 'PascalCase',
camel = 'camelCase'
}
type Replacement = { [index: string]: string };
type IgnoredList = string[];
type ConfigKey = 'ignoreExternalModule' | 'case';
type Config = {
ignoreExternalModule: boolean;
case: StringCase;
};
// This is for temporarily resolving type errors. Actual runtime Node, SourceFile object
// has those properties.
interface RuntimeSourceFile extends ts.SourceFile {
resolvedModules: Map<string, ts.ResolvedModuleFull>;
}
interface RuntimeNode extends ts.Node {
parent: RuntimeSourceFile;
}
type Option = {
replacements: Replacement;
ignoredList: IgnoredList;
config: Config;
};
function walk(ctx: Lint.WalkContext<Option>) {
const option = ctx.options;
function getNameNodeFromImportNode(node: ts.ImportEqualsDeclaration | ts.ImportDeclaration): ts.Node | undefined {
if (tsutils.isImportEqualsDeclaration(node)) {
return node.name;
}
const importClause = node.importClause;
return importClause === undefined ? undefined : importClause.name;
}
// Ignore NPM installed modules by checking its module path at runtime
function checkIgnoreExternalModule(moduleName: string, node: unknown, opt: Config): boolean {
const runtimeNode: RuntimeNode = <RuntimeNode>node;
if (opt.ignoreExternalModule === true && runtimeNode.parent !== undefined && runtimeNode.parent.resolvedModules !== undefined) {
let ignoreThisExternalModule = false;
runtimeNode.parent.resolvedModules.forEach((value: ts.ResolvedModuleFull, key: string) => {
if (key === moduleName && value.isExternalLibraryImport === true) {
ignoreThisExternalModule = true;
}
});
return ignoreThisExternalModule;
}
return false;
}
// Ignore array of strings that comes from third argument.
function checkIgnoredListExists(moduleName: string, ignoredList: IgnoredList): boolean {
return ignoredList.filter((ignoredModule: string) => ignoredModule === moduleName).length >= 1;
}
function checkReplacementsExist(
importedName: string,
expectedImportedName: string,
moduleName: string,
replacements: Replacement
): boolean {
// Allowed Replacement keys are specifiers that are allowed when overriding or adding exceptions
// to import-name rule.
// Example: for below import statement
// `import cgi from 'fs-util/cgi-common'`
// The Valid specifiers are: [cgiCommon, fs-util/cgi-common, cgi-common]
const allowedReplacementKeys: string[] = [
makeCamelCase(expectedImportedName),
makePascalCase(expectedImportedName),
moduleName,
moduleName.replace(/.*\//, '')
];
return Utils.exists(
Object.keys(replacements),
(replacementKey: string): boolean => {
for (let index = 0; allowedReplacementKeys.length > index; index = index + 1) {
if (replacementKey === allowedReplacementKeys[index]) {
return importedName === replacements[replacementKey];
}
}
return false;
}
);
}
function isImportNameValid(
importedName: string,
expectedImportedName: string,
moduleName: string,
node: ts.ImportEqualsDeclaration | ts.ImportDeclaration
): boolean {
if (transformName(expectedImportedName).indexOf(importedName) > -1) {
return true;
}
const isReplacementsExist = checkReplacementsExist(importedName, expectedImportedName, moduleName, option.replacements);
if (isReplacementsExist) {
return true;
}
const isIgnoredModuleExist = checkIgnoredListExists(moduleName, option.ignoredList);
if (isIgnoredModuleExist) {
return true;
}
const ignoreThisExternalModule = checkIgnoreExternalModule(moduleName, node, option.config);
if (ignoreThisExternalModule) {
return true;
}
return false;
}
function transformName(input: string) {
switch (option.config.case) {
case StringCase.camel:
return [makeCamelCase(input)];
case StringCase.pascal:
return [makePascalCase(input)];
case StringCase.any:
return [makeCamelCase(input), makePascalCase(input)];
default:
throw new Error(`Unknown case for import-name rule: "${option.config.case}"`);
}
}
function makeCamelCase(input: string): string {
return input.replace(
/[-|\.|_](.)/g, // tslint:disable-next-line:variable-name
(_match: string, group1: string): string => {
return group1.toUpperCase();
}
);
}
function makePascalCase(input: string): string {
return input.replace(/(?:^|[-|\.|_|])([a-z])/g, (_, group1) => group1.toUpperCase());
}
function validateImport(node: ts.ImportEqualsDeclaration | ts.ImportDeclaration, importedName: string, moduleName: string): void {
const expectedImportedName = moduleName.replace(/.*\//, ''); // chop off the path
if (expectedImportedName === '' || expectedImportedName === '.' || expectedImportedName === '..') {
return;
}
if (isImportNameValid(importedName, expectedImportedName, moduleName, node)) {
return;
}
const expectedImportedNames = transformName(expectedImportedName);
const expectedNames = expectedImportedNames.map(name => `'${name}'`).join(' or ');
const message: string = `Misnamed import. Import should be named ${expectedNames} but found '${importedName}'`;
const nameNode = getNameNodeFromImportNode(node);
if (nameNode === undefined) {
return;
}
const nameNodeStartPos = nameNode.getStart();
const fix = new Lint.Replacement(nameNodeStartPos, nameNode.end - nameNodeStartPos, expectedImportedNames[0]);
ctx.addFailureAt(node.getStart(), node.getWidth(), message, fix);
}
function cb(node: ts.Node): void {
if (tsutils.isImportEqualsDeclaration(node)) {
const name: string = node.name.text;
if (tsutils.isExternalModuleReference(node.moduleReference)) {
const moduleRef: ts.ExternalModuleReference = node.moduleReference;
if (tsutils.isStringLiteral(moduleRef.expression)) {
const moduleName: string = moduleRef.expression.text;
validateImport(node, name, moduleName);
}
} else if (tsutils.isQualifiedName(node.moduleReference)) {
let moduleName = node.moduleReference.getText();
moduleName = moduleName.replace(/.*\./, ''); // chop off the qualified parts
validateImport(node, name, moduleName);
}
}
if (tsutils.isImportDeclaration(node)) {
if (node.importClause !== undefined && node.importClause.name !== undefined) {
const name: string = node.importClause.name.text;
if (tsutils.isStringLiteral(node.moduleSpecifier)) {
const moduleName: string = node.moduleSpecifier.text;
validateImport(node, name, moduleName);
}
}
}
return ts.forEachChild(node, cb);
}
return ts.forEachChild(ctx.sourceFile, cb);
}