UNPKG

2.3 kBPlain TextView Raw
1import * as path from "path";
2import * as Lint from "tslint";
3import * as ts from "typescript";
4
5import { ConfigFactory } from "./config/ConfigFactory";
6import { Casing } from "./model/FilenamesRuleConfig";
7import { EnumUtils } from "./utils/EnumUtils";
8import { FilenameCasingUtils } from "./utils/FilenameCasingUtils";
9import { ImportRuleUtils } from "./utils/ImportRuleUtils";
10
11export const FILE_NAMES_RULE_ID = "tsf-folders-file-names";
12
13/** Custom version of the standard file-name-casing rule, that allows for *multiple* casings.
14 * ref: https://github.com/palantir/tslint/blob/master/src/rules/fileNameCasingRule.ts
15 */
16export 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 // include the rule ID, to make it easier to disable
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}