Forked from dsherret/noDuplicateImportsFromSameFileRule.ts
Created
March 19, 2018 00:13
-
-
Save SteveStrong/523e6bc797072b79cc1da9674b8ab919 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as ts from "typescript"; | |
import * as Lint from "tslint/lib/lint"; | |
export class Rule extends Lint.Rules.AbstractRule { | |
static FAILURE_STRING = "duplicate imports from same file forbidden"; | |
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { | |
return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions())); | |
} | |
} | |
class NoDuplicateImportsFromSameFileWalker extends Lint.RuleWalker { | |
private fileImportsByFileName: { [fileName: string]: { [importName: string]: boolean } } = {}; | |
visitImportDeclaration(node: ts.ImportDeclaration) { | |
const sourceFile = node.parent as ts.SourceFile; | |
const fileImports = this.getFileImports(sourceFile.fileName); | |
const importPath = (node.moduleSpecifier as any).text as string; | |
if (fileImports[importPath] != null) { | |
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); | |
} | |
else { | |
fileImports[importPath] = true; | |
} | |
super.visitImportDeclaration(node); | |
} | |
private getFileImports(fileName: string) { | |
this.fileImportsByFileName[fileName] = this.fileImportsByFileName[fileName] || {}; | |
return this.fileImportsByFileName[fileName]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment