How to use the tslint.Rules function in tslint

To help you get started, we’ve selected a few tslint examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / tslint-microsoft-contrib / src / noBackboneGetSetOutsideModelRule.ts View on Github external
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';

import { AstUtils } from './utils/AstUtils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';

export class Rule extends Lint.Rules.AbstractRule {
    public static metadata: ExtendedMetadata = {
        ruleName: 'no-backbone-get-set-outside-model',
        type: 'maintainability',
        description: "Avoid using `model.get('x')` and `model.set('x', value)` Backbone accessors outside of the owning model.",
        options: null, // tslint:disable-line:no-null-keyword
        optionsDescription: '',
        typescriptOnly: true,
        issueClass: 'Non-SDL',
        issueType: 'Warning',
        severity: 'Important',
        level: 'Opportunity for Excellence',
        group: 'Correctness',
        commonWeaknessEnumeration: '398, 710'
    };

    public static GET_FAILURE_STRING: string = 'Backbone get() called outside of owning model: ';
github intershop / intershop-pwa / tslint-rules / src / noSuspiciousVariableInitInTestsRule.ts View on Github external
import * as Lint from 'tslint';
import * as ts from 'typescript';

import { RuleHelpers } from './ruleHelpers';

export class Rule extends Lint.Rules.AbstractRule {
  // TODO: excludes currently only supported for 'variable X is not re-initialized in beforeEach'
  excludes: string[] = [];
  interestingVariables: ts.Node[];
  correctlyReinitializedVariables: string[];

  constructor(options: Lint.IOptions) {
    super(options);

    if (options.ruleArguments && options.ruleArguments[0] && options.ruleArguments[0].exclude) {
      this.excludes = options.ruleArguments[0].exclude;
    }
    this.interestingVariables = [];
    this.correctlyReinitializedVariables = [];
  }
  apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    if (!sourceFile.fileName.endsWith('.spec.ts')) {
github intershop / intershop-pwa / tslint-rules / dist / ishNoObjectLiteralTypeAssertionRule.js View on Github external
}
        return _this;
    }
    Rule.prototype.apply = function (sourceFile) {
        if (new RegExp(this.includePattern).test(sourceFile.fileName)) {
            return Rule.RULE.apply(sourceFile);
        }
        return [];
    };
    Rule.RULE = new rule.Rule({
        ruleArguments: [],
        ruleSeverity: 'error',
        ruleName: 'ish-no-object-literal-type-assertion',
    });
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
github microsoft / vscode / build / lib / tslint / translationRemindRule.js View on Github external
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Lint = require("tslint");
var fs = require("fs");
var Rule = /** @class */ (function (_super) {
    __extends(Rule, _super);
    function Rule() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithWalker(new TranslationRemindRuleWalker(sourceFile, this.getOptions()));
    };
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var TranslationRemindRuleWalker = /** @class */ (function (_super) {
    __extends(TranslationRemindRuleWalker, _super);
    function TranslationRemindRuleWalker(file, opts) {
        return _super.call(this, file, opts) || this;
    }
    TranslationRemindRuleWalker.prototype.visitImportDeclaration = function (node) {
        var declaration = node.moduleSpecifier.getText();
        if (declaration !== "'" + TranslationRemindRuleWalker.NLS_MODULE + "'") {
            return;
        }
        this.visitImportLikeDeclaration(node);
    };
    TranslationRemindRuleWalker.prototype.visitImportEqualsDeclaration = function (node) {
        var reference = node.moduleReference.getText();
        if (reference !== "require('" + TranslationRemindRuleWalker.NLS_MODULE + "')") {
github microsoft / tslint-microsoft-contrib / noOctalLiteralRule.js View on Github external
Rule.metadata = {
        ruleName: 'no-octal-literal',
        type: 'maintainability',
        description: 'Do not use octal literals or escaped octal sequences',
        options: null,
        optionsDescription: '',
        typescriptOnly: true,
        issueClass: 'SDL',
        issueType: 'Error',
        severity: 'Critical',
        level: 'Mandatory',
        group: 'Security'
    };
    Rule.FAILURE_STRING = 'Octal literals should not be used: ';
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
function walk(ctx) {
    function cb(node) {
        if (tsutils.isStringLiteral(node) || node.kind === ts.SyntaxKind.FirstTemplateToken) {
            failOnOctalString(node);
        }
        return ts.forEachChild(node, cb);
    }
    return ts.forEachChild(ctx.sourceFile, cb);
    function failOnOctalString(node) {
        var match = /("|'|`)[^\\]*(\\+-?[0-7]{1,3}(?![0-9]))(?:.|\n|\t|\u2028|\u2029)*(?:\1)/g.exec(node.getText());
        if (match) {
            var octalValue = match[2];
            var backslashCount = octalValue.lastIndexOf('\\') + 1;
            if (backslashCount % 2 === 1) {
                octalValue = octalValue.substr(backslashCount - 1);
github intershop / intershop-pwa / tslint-rules / dist / lifecycleCyclomaticComplexityRule.js View on Github external
failures.forEach(function (f) {
                var methodIdentifier = tsutils_1.getTokenAtPosition(sourceFile, f.getStartPosition().getPosition());
                var methodIdentifierText = methodIdentifier.getText();
                if (methodIdentifierText.startsWith('ngOn')) {
                    var threshold = _this.complexity[methodIdentifierText] || 1;
                    var match = f.getFailure().match(new RegExp('has a cyclomatic complexity of ([0-9]+) which'));
                    var actualCC = Number.parseInt(match[1], 10) || 999;
                    if (actualCC > threshold) {
                        ctx.addFailureAtNode(methodIdentifier, "The function " + methodIdentifierText + " has a cyclomatic complexity of " + actualCC + " which is higher than the threshold of " + threshold);
                    }
                }
            });
        });
    };
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
github ajafff / tslint-consistent-codestyle / rules / preferWhileRule.ts View on Github external
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as utils from 'tsutils';

import { ForStatementWalker } from '../src/walker';

const FAIL_MESSAGE = `use while loop instead`;

export class Rule extends Lint.Rules.AbstractRule {
    public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
        return this.applyWithWalker(new ForWalker(sourceFile, this.getOptions()));
    }
}

class ForWalker extends ForStatementWalker {
    public visitForStatement(node: ts.ForStatement) {
        if (node.initializer === undefined && node.incrementor === undefined) {
            const sourceFile = this.getSourceFile();
            const start = node.getStart(sourceFile);
            const closeParenEnd = utils.getChildOfKind(node, ts.SyntaxKind.CloseParenToken, sourceFile)!.getEnd();
            const width = closeParenEnd - start;
            let fix: Lint.Fix;
            if (node.condition === undefined) {
                fix = this.createFix(new Lint.Replacement(start, width, 'while (true)'));
            } else {
github microsoft / dtslint / bin / rules / trimFileRule.js View on Github external
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Lint = require("tslint");
const util_1 = require("../util");
class Rule extends Lint.Rules.AbstractRule {
    apply(sourceFile) {
        return this.applyWithFunction(sourceFile, walk);
    }
}
Rule.metadata = {
    ruleName: "trim-file",
    description: "Forbids leading/trailing blank lines in a file. Allows file to end in '\n'.",
    optionsDescription: "Not configurable.",
    options: null,
    type: "style",
    typescriptOnly: false,
};
Rule.FAILURE_STRING_LEADING = util_1.failure(Rule.metadata.ruleName, "File should not begin with a blank line.");
Rule.FAILURE_STRING_TRAILING = util_1.failure(Rule.metadata.ruleName, "File should not end with a blank line. (Ending in one newline OK, ending in two newlines not OK.)");
exports.Rule = Rule;
function walk(ctx) {
github microsoft / tslint-microsoft-contrib / reactA11yMetaRule.js View on Github external
};
    Rule.metadata = {
        ruleName: 'react-a11y-meta',
        type: 'functionality',
        description: 'For accessibility of your website, HTML meta elements must not have http-equiv="refresh".',
        options: null,
        optionsDescription: '',
        typescriptOnly: true,
        issueClass: 'Ignored',
        issueType: 'Warning',
        severity: 'Low',
        level: 'Opportunity for Excellence',
        group: 'Accessibility'
    };
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
function walk(ctx) {
    function validateOpeningElement(parent, openElement) {
        if (openElement.tagName.getText() === 'meta') {
            var attributes = openElement.attributes;
            attributes.properties.forEach(function (parameter) {
                if (parameter.kind === ts.SyntaxKind.JsxAttribute) {
                    var attribute = parameter;
                    if (attribute.name.getText() === 'http-equiv') {
                        if (attribute.initializer !== undefined && isStringLiteral(attribute.initializer, 'refresh')) {
                            ctx.addFailureAt(parent.getStart(), openElement.getWidth(), FAILURE_STRING);
                        }
                    }
                }
            });
        }
github angular / angular-cli / etc / rules / defocusRule.ts View on Github external
* Copyright Google Inc. All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/*
 * Taken from https://github.com/Sergiioo/tslint-defocus
 * Copyright (c) 2016 Sergio Annecchiarico
 * MIT - https://github.com/Sergiioo/tslint-defocus/blob/master/LICENSE
 */

import * as Lint from 'tslint';
import * as ts from 'typescript';

export class Rule extends Lint.Rules.AbstractRule {

  public static metadata: Lint.IRuleMetadata = {
    ruleName: 'defocus',
    description: "Bans the use of `fdescribe` and 'fit' Jasmine functions.",
    rationale: 'It is all too easy to mistakenly commit a focussed Jasmine test suite or spec.',
    options: null,
    optionsDescription: 'Not configurable.',
    type: 'functionality',
    typescriptOnly: false,
  };

  public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    return this.applyWithFunction(sourceFile, walk);
  }
}