1 | import * as path from "path";
|
2 | import * as Lint from "tslint";
|
3 | import * as ts from "typescript";
|
4 |
|
5 | import { ConfigFactory } from "./config/ConfigFactory";
|
6 | import { Casing } from "./model/FilenamesRuleConfig";
|
7 | import { EnumUtils } from "./utils/EnumUtils";
|
8 | import { FilenameCasingUtils } from "./utils/FilenameCasingUtils";
|
9 | import { ImportRuleUtils } from "./utils/ImportRuleUtils";
|
10 |
|
11 | export const FILE_NAMES_RULE_ID = "tsf-folders-file-names";
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export class Rule extends Lint.Rules.AbstractRule {
|
17 | private static FAILURE_STRING(expectedCasings: Casing[]): string {
|
18 | const stylizedCasings = expectedCasings
|
19 | .map(casing => this.stylizedNameForCasing(casing))
|
20 | .join(" or ");
|
21 |
|
22 |
|
23 | return `File name must be ${stylizedCasings} (${FILE_NAMES_RULE_ID})`;
|
24 | }
|
25 |
|
26 | private static stylizedNameForCasing(casing: Casing): string {
|
27 | switch (casing) {
|
28 | case Casing.CamelCase:
|
29 | return "camelCase";
|
30 | case Casing.PascalCase:
|
31 | return "PascalCase";
|
32 | case Casing.KebabCase:
|
33 | return "kebab-case";
|
34 | case Casing.SnakeCase:
|
35 | return "snake_case";
|
36 | default:
|
37 | throw new Error(`unhandled casing ${casing}`);
|
38 | }
|
39 | }
|
40 |
|
41 | apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
42 | const config = ConfigFactory.createForFilenames(this.getOptions());
|
43 |
|
44 | if (
|
45 | ImportRuleUtils.shouldIgnorePath(sourceFile.fileName, config.ignorePaths)
|
46 | ) {
|
47 | return [];
|
48 | }
|
49 |
|
50 | const parsedPath = path.parse(sourceFile.fileName);
|
51 | const filename = parsedPath.name;
|
52 |
|
53 | const isAnAllowedCasing = config.casings.some(casingName => {
|
54 | const casing = EnumUtils.parseCasing(casingName);
|
55 |
|
56 | const isAllowed = FilenameCasingUtils.isCased(filename, casing);
|
57 |
|
58 | return isAllowed;
|
59 | });
|
60 |
|
61 | if (!isAnAllowedCasing) {
|
62 | return [
|
63 | new Lint.RuleFailure(
|
64 | sourceFile,
|
65 | 0,
|
66 | 0,
|
67 | Rule.FAILURE_STRING(config.casings),
|
68 | FILE_NAMES_RULE_ID
|
69 | )
|
70 | ];
|
71 | }
|
72 | return [];
|
73 | }
|
74 | }
|