-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathdisallowImportsRule.ts
46 lines (41 loc) · 1.39 KB
/
disallowImportsRule.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
import { findImports, ImportKind } from 'tsutils';
import * as ts from 'typescript';
import * as Lint from 'tslint';
export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: 'disallow-imports',
description: Lint.Utils.dedent`Disallows importing by pattern.`,
rationale: Lint.Utils.dedent`
Useful for lerna-driven projects to avoid mistakes imports from compiled or source code`,
optionsDescription: 'A list of mistakes patterns',
options: {
type: 'array',
items: {
type: 'string',
},
},
optionExamples: [true, [true, 'rxjs/observable', '@angular/platform-browser', '@angular/core/testing']],
type: 'functionality',
typescriptOnly: false,
};
public static FAILURE_STRING = 'import from this paths disallowed';
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, this.ruleArguments);
}
}
function walk(ctx: Lint.WalkContext<string[]>) {
for (const name of findImports(ctx.sourceFile, ImportKind.All)) {
if (isBlackListed(name.text, ctx.options)) {
ctx.addFailureAtNode(name, Rule.FAILURE_STRING);
}
}
}
function isBlackListed(path: string, blacklist: string[]): boolean {
for (const option of blacklist) {
if (path === option || path.includes(`${option}/`)) {
return true;
}
}
return false;
}