/
tsfFoldersFileNamesRule.ts
71 lines (60 loc) · 2.4 KB
/
tsfFoldersFileNamesRule.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import * as path from "path";
import * as Lint from "tslint";
import * as ts from "typescript";
import { ConfigFactory } from "./config/ConfigFactory";
import { Casing } from "./model/FilenamesRuleConfig";
import { RuleId } from "./RuleId";
import { EnumUtils } from "./utils/EnumUtils";
import { FilenameCasingUtils } from "./utils/FilenameCasingUtils";
import { ImportRuleUtils } from "./utils/ImportRuleUtils";
/** Custom version of the standard file-name-casing rule, that allows for *multiple* casings.
* ref: https://github.com/palantir/tslint/blob/master/src/rules/fileNameCasingRule.ts
*/
export class Rule extends Lint.Rules.AbstractRule {
private static FAILURE_STRING(expectedCasings: Casing[]): string {
const stylizedCasings = expectedCasings
.map(casing => this.stylizedNameForCasing(casing))
.join(" or ");
// include the rule ID, to make it easier to disable
return `File name must be ${stylizedCasings} (${RuleId.TsfFoldersFileNames})`;
}
private static stylizedNameForCasing(casing: Casing): string {
switch (casing) {
case Casing.CamelCase:
return "camelCase";
case Casing.PascalCase:
return "PascalCase";
case Casing.KebabCase:
return "kebab-case";
case Casing.SnakeCase:
return "snake_case";
default:
throw new Error(`unhandled casing ${casing}`);
}
}
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
const config = ConfigFactory.createForFilenames(this.getOptions());
if (ImportRuleUtils.shouldIgnorePath(sourceFile.fileName, config.ignorePaths)) {
return [];
}
const parsedPath = path.parse(sourceFile.fileName);
const filename = parsedPath.name;
const isAnAllowedCasing = config.casings.some(casingName => {
const casing = EnumUtils.parseCasing(casingName);
const isAllowed = FilenameCasingUtils.isCased(filename, casing);
return isAllowed;
});
if (!isAnAllowedCasing) {
return [
new Lint.RuleFailure(
sourceFile,
0,
0,
Rule.FAILURE_STRING(config.casings),
RuleId.TsfFoldersFileNames
)
];
}
return [];
}
}