-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathnoInputPrefixRule.ts
More file actions
91 lines (74 loc) · 2.62 KB
/
noInputPrefixRule.ts
File metadata and controls
91 lines (74 loc) · 2.62 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { sprintf } from 'sprintf-js';
import { IOptions, IRuleMetadata, RuleFailure, Rules, Utils } from 'tslint/lib';
import { Decorator, PropertyDeclaration, SourceFile } from 'typescript';
import { NgWalker } from './angular/ngWalker';
export class Rule extends Rules.AbstractRule {
static readonly metadata: IRuleMetadata = {
description: 'Input names should not be prefixed by the configured disallowed prefixes.',
optionExamples: [[true, 'can', 'is', 'should']],
options: {
items: [
{
type: 'string',
},
],
minLength: 1,
type: 'array',
},
optionsDescription: 'Options accept a string array of disallowed input prefixes.',
rationale: Utils.dedent`
HTML attributes are not prefixed. It's considered best not to prefix Inputs.
* Example: 'enabled' is prefered over 'isEnabled'.
`,
ruleName: 'no-input-prefix',
type: 'maintainability',
typescriptOnly: true,
};
static readonly FAILURE_STRING = '@Inputs should not be prefixed by %s';
apply(sourceFile: SourceFile): RuleFailure[] {
const walker = new Walker(sourceFile, this.getOptions());
return this.applyWithWalker(walker);
}
isEnabled(): boolean {
const {
metadata: {
options: { minLength },
},
} = Rule;
const { length } = this.ruleArguments;
return super.isEnabled() && length >= minLength;
}
}
const getReadablePrefixes = (prefixes: string[]): string => {
const prefixesLength = prefixes.length;
if (prefixesLength === 1) {
return `"${prefixes[0]}"`;
}
return `${prefixes
.map((x) => `"${x}"`)
.slice(0, prefixesLength - 1)
.join(', ')} or "${[...prefixes].pop()}"`;
};
export const getFailureMessage = (prefixes: string[]): string => {
return sprintf(Rule.FAILURE_STRING, getReadablePrefixes(prefixes));
};
class Walker extends NgWalker {
private readonly blacklistedPrefixes: string[];
constructor(source: SourceFile, options: IOptions) {
super(source, options);
this.blacklistedPrefixes = options.ruleArguments;
}
protected visitNgInput(property: PropertyDeclaration, input: Decorator, args: string[]) {
this.validatePrefix(property);
super.visitNgInput(property, input, args);
}
private validatePrefix(property: PropertyDeclaration) {
const memberName = property.name.getText();
const isBlackListedPrefix = this.blacklistedPrefixes.some((x) => x === memberName || new RegExp(`^${x}[^a-z]`).test(memberName));
if (!isBlackListedPrefix) {
return;
}
const failure = getFailureMessage(this.blacklistedPrefixes);
this.addFailureAtNode(property, failure);
}
}