|
| 1 | +import {RuleFailure} from 'tslint/lib/lint'; |
| 2 | +import {AbstractRule} from 'tslint/lib/rules'; |
| 3 | +import {RuleWalker} from 'tslint/lib/language/walker'; |
| 4 | +import * as ts from 'typescript'; |
| 5 | + |
| 6 | +export class Rule extends AbstractRule { |
| 7 | + public static FAILURE_STRING = "duplicate module import"; |
| 8 | + |
| 9 | + public apply(sourceFile: ts.SourceFile): RuleFailure[] { |
| 10 | + const typedefWalker = new ModuleImportWalker(sourceFile, this.getOptions()); |
| 11 | + return this.applyWithWalker(typedefWalker); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +class ModuleImportWalker extends RuleWalker { |
| 16 | + importModulesSeen: string[] = []; |
| 17 | + |
| 18 | + protected visitImportDeclaration(node: ts.ImportDeclaration): void { |
| 19 | + this.visitModuleSpecifier(node.moduleSpecifier); |
| 20 | + super.visitImportDeclaration(node); |
| 21 | + } |
| 22 | + |
| 23 | + protected visitImportEqualsDeclaration(node: ts.ImportEqualsDeclaration): void { |
| 24 | + this.visitModuleSpecifier(node.moduleReference); |
| 25 | + super.visitImportEqualsDeclaration(node); |
| 26 | + } |
| 27 | + |
| 28 | + private checkTypeAnnotation(location: number, typeAnnotation: ts.TypeNode, name?: ts.Node) { |
| 29 | + if (typeAnnotation == null) { |
| 30 | + let ns = "<name missing>"; |
| 31 | + if (name != null && name.kind === ts.SyntaxKind.Identifier) { |
| 32 | + ns = (<ts.Identifier>name).text; |
| 33 | + } |
| 34 | + if (ns.charAt(0) === '_') return; |
| 35 | + let failure = this.createFailure(location, 1, "expected parameter " + ns + " to have a type"); |
| 36 | + this.addFailure(failure); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private visitModuleSpecifier(moduleSpecifier: ts.Node) { |
| 41 | + var text = moduleSpecifier.getText(); |
| 42 | + if (this.importModulesSeen.indexOf(text) >= 0) { |
| 43 | + let failure = |
| 44 | + this.createFailure(moduleSpecifier.getEnd(), 1, "Duplicate imports from module " + text); |
| 45 | + this.addFailure(failure); |
| 46 | + } |
| 47 | + this.importModulesSeen.push(text); |
| 48 | + } |
| 49 | +} |
0 commit comments