Skip to content

Commit

Permalink
fix(eslint-plugin): collect references when visiting the program node
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesse Trinity committed Jun 19, 2019
1 parent e0ee130 commit 786a0a2
Showing 1 changed file with 30 additions and 25 deletions.
55 changes: 30 additions & 25 deletions packages/eslint-plugin/src/rules/no-reference-import.ts
@@ -1,10 +1,10 @@
import * as util from '../util';
import { AST_NODE_TYPES } from '@typescript-eslint/typescript-estree';
import {
Literal,
Node,
TSExternalModuleReference,
} from '@typescript-eslint/typescript-estree/dist/ts-estree/ts-estree';
import { TSESTree } from '@typescript-eslint/typescript-estree';

export default util.createRule({
name: 'no-reference-import',
Expand All @@ -24,49 +24,54 @@ export default util.createRule({
defaultOptions: [],
create(context) {
let programNode: Node;
const sourceCode = context.getSourceCode();
const references: ({
comment: TSESTree.Comment;
importName: string;
})[] = [];

function hasMatchingReference(source: Literal) {
const referenceRegExp = /^\/\s*<reference\s*types="(.*)"/;
const sourceCode = context.getSourceCode();
const commentsBefore = sourceCode.getCommentsBefore(programNode);

commentsBefore.forEach(comment => {
if (comment.type !== 'Line') {
return;
}
const referenceResult = referenceRegExp.exec(comment.value);

if (referenceResult && source.value === referenceResult[1]) {
references.forEach(reference => {
if (reference.importName === source.value) {
context.report({
node: comment,
node: reference.comment,
messageId: 'noReferenceImport',
data: {
module: referenceResult[1],
module: reference.importName,
},
});
}
});
}
return {
ImportDeclaration(node) {
if (node.type === AST_NODE_TYPES.ImportDeclaration) {
if (programNode) {
let source = node.source as Literal;
hasMatchingReference(source);
}
if (programNode) {
const source = node.source as Literal;
hasMatchingReference(source);
}
},
TSImportEqualsDeclaration(node) {
if (node.type === AST_NODE_TYPES.TSImportEqualsDeclaration) {
if (programNode) {
let source = (node.moduleReference as TSExternalModuleReference)
.expression as Literal;
hasMatchingReference(source);
}
if (programNode) {
const source = (node.moduleReference as TSExternalModuleReference)
.expression as Literal;
hasMatchingReference(source);
}
},
Program(node) {
programNode = node;
const referenceRegExp = /^\/\s*<reference\s*types="(.*)"/;
const commentsBefore = sourceCode.getCommentsBefore(programNode);

commentsBefore.forEach(comment => {
if (comment.type !== 'Line') {
return;
}
const referenceResult = referenceRegExp.exec(comment.value);

if (referenceResult && referenceResult[1]) {
references.push({ comment, importName: referenceResult[1] });
}
});
},
};
},
Expand Down

0 comments on commit 786a0a2

Please sign in to comment.