Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveStrong/523e6bc797072b79cc1da9674b8ab919 to your computer and use it in GitHub Desktop.
Save SteveStrong/523e6bc797072b79cc1da9674b8ab919 to your computer and use it in GitHub Desktop.
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