All files readonlyKeywordRule.ts

100% Statements 20/20
100% Branches 11/11
100% Functions 6/6
100% Lines 18/18
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 641x 1x 1x           1x 1x 10x     10x       1x           865x             865x         161x     61x         100x 19x   81x   81x 81x                       765x    
import * as ts from "typescript";
import * as Lint from "tslint";
import * as Shared from "./readonly-shared";
 
/**
 * This rule checks that the readonly keyword is used in all PropertySignature and
 * IndexerSignature nodes (which are the only places that the readonly keyword can exist).
 */
export class Rule extends Lint.Rules.AbstractRule {
  public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    return this.applyWithFunction(
      sourceFile,
      (ctx: Lint.WalkContext<Shared.Options>) =>
        Shared.walk(ctx, checkNode, "A readonly modifier is required."),
      Shared.parseOptions(this.ruleArguments)
    );
  }
}
 
function checkNode(
  node: ts.Node,
  ctx: Lint.WalkContext<Shared.Options>
): ReadonlyArray<Shared.InvalidNode> {
  return checkPropertySignatureAndIndexSignature(node, ctx);
}
 
function checkPropertySignatureAndIndexSignature(
  node: ts.Node,
  ctx: Lint.WalkContext<Shared.Options>
): ReadonlyArray<Shared.InvalidNode> {
  if (
    node.kind === ts.SyntaxKind.PropertySignature ||
    node.kind === ts.SyntaxKind.IndexSignature ||
    node.kind === ts.SyntaxKind.PropertyDeclaration
  ) {
    if (
      !(
        node.modifiers &&
        node.modifiers.filter(m => m.kind === ts.SyntaxKind.ReadonlyKeyword)
          .length > 0
      )
    ) {
      // Check if ignore-prefix applies
      if (Shared.shouldIgnorePrefix(node, ctx.options, ctx.sourceFile)) {
        return [];
      }
      const length = node.getWidth(ctx.sourceFile);
      // const fulltext = node.getText(ctx.sourceFile);
      const fulltext = node.getText(ctx.sourceFile);
      return [
        Shared.createInvalidNode(
          node,
          new Lint.Replacement(
            node.end - length,
            length,
            `readonly ${fulltext}`
          )
        )
      ];
    }
  }
  return [];
}