/
directiveClassSuffixRule.ts
56 lines (49 loc) · 1.76 KB
/
directiveClassSuffixRule.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
47
48
49
50
51
52
53
54
55
56
import * as Lint from 'tslint';
import * as ts from 'typescript';
import {sprintf} from 'sprintf-js';
import {NgWalker} from './angular/ngWalker';
import {DirectiveMetadata} from './angular/metadata';
export class Rule extends Lint.Rules.AbstractRule {
public static metadata: Lint.IRuleMetadata = {
ruleName: 'directive-class-suffix',
type: 'style',
description: `Classes decorated with @Directive must have suffix "Directive" (or custom) in their name.`,
descriptionDetails: `See more at https://angular.io/styleguide#!#02-03.`,
rationale: `Consistent conventions make it easy to quickly identify and reference assets of different types.`,
options: {
type: 'array',
items: {
type: 'string',
}
},
optionExamples: [
`true`,
`[true, "Directive", "MySuffix"]`,
],
optionsDescription: `Supply a list of allowed component suffixes. Defaults to "Directive".`,
typescriptOnly: true,
};
static FAILURE:string = 'The name of the class %s should end with the suffix %s ($$02-03$$)';
static validate(className: string, suffix: string):boolean {
return className.endsWith(suffix);
}
public apply(sourceFile:ts.SourceFile):Lint.RuleFailure[] {
return this.applyWithWalker(
new ClassMetadataWalker(sourceFile,
this.getOptions()));
}
}
export class ClassMetadataWalker extends NgWalker {
visitNgDirective(meta: DirectiveMetadata) {
let name = meta.controller.name;
let className:string = name.text;
const suffix = this.getOptions()[0] || 'Directive';
if (!Rule.validate(className, suffix)) {
this.addFailure(
this.createFailure(
name.getStart(),
name.getWidth(),
sprintf.apply(this, [Rule.FAILURE, className, suffix])));
}
}
}