How to use tslint - 10 common examples

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 / vscode / build / gulpfile.hygiene.js View on Github external
let formatted = result.dest.replace(/\r\n/gm, '\n');

			if (original !== formatted) {
				console.error("File not formatted. Run the 'Format Document' command to fix it:", file.relative);
				errorCount++;
			}
			cb(null, file);

		}, err => {
			cb(err);
		});
	});

	const tslintConfiguration = tslint.Configuration.findConfiguration('tslint.json', '.');
	const tslintOptions = { fix: false, formatter: 'json' };
	const tsLinter = new tslint.Linter(tslintOptions);

	const tsl = es.through(function (file) {
		const contents = file.contents.toString('utf8');
		tsLinter.lint(file.relative, contents, tslintConfiguration.results);
		this.emit('data', file);
	});

	let input;

	if (Array.isArray(some) || typeof some === 'string' || !some) {
		const options = { base: '.', follow: true, allowEmpty: true };
		if (some) {
			input = vfs.src(some, options).pipe(filter(all)); // split this up to not unnecessarily filter all a second time
		} else {
			input = vfs.src(all, options);
		}
github microsoft / vscode / build / lib / tslint / noNlsInStandaloneEditorRule.js View on Github external
const Lint = require("tslint");
const path_1 = require("path");
class Rule extends Lint.Rules.AbstractRule {
    apply(sourceFile) {
        if (/vs(\/|\\)editor(\/|\\)standalone(\/|\\)/.test(sourceFile.fileName)
            || /vs(\/|\\)editor(\/|\\)common(\/|\\)standalone(\/|\\)/.test(sourceFile.fileName)
            || /vs(\/|\\)editor(\/|\\)editor.api/.test(sourceFile.fileName)
            || /vs(\/|\\)editor(\/|\\)editor.main/.test(sourceFile.fileName)
            || /vs(\/|\\)editor(\/|\\)editor.worker/.test(sourceFile.fileName)) {
            return this.applyWithWalker(new NoNlsInStandaloneEditorRuleWalker(sourceFile, this.getOptions()));
        }
        return [];
    }
}
exports.Rule = Rule;
class NoNlsInStandaloneEditorRuleWalker extends Lint.RuleWalker {
    constructor(file, opts) {
        super(file, opts);
    }
    visitImportEqualsDeclaration(node) {
        if (node.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference) {
            this._validateImport(node.moduleReference.expression.getText(), node);
        }
    }
    visitImportDeclaration(node) {
        this._validateImport(node.moduleSpecifier.getText(), node);
    }
    visitCallExpression(node) {
        super.visitCallExpression(node);
        // import('foo') statements inside the code
        if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
            const [path] = node.arguments;
github angular / material-update-tool / src / rules / switchStylesheetsRule.ts View on Github external
* A glob string needs to be transferred from the CLI process to the child process of TSLint.
 * This is the environment variable, which will be set if the `--extra-stylesheets` option is set.
 */
export const EXTRA_STYLESHEETS_GLOB_KEY = 'MD_EXTRA_STYLESHEETS_GLOB';

/**
 * Message that is being sent to TSLint if there is something in the stylesheet that still use an
 * outdated prefix.
 */
const failureMessage = 'Stylesheet uses outdated Material prefix.';

/**
 * Rule that walks through every component decorator and updates their inline or external
 * stylesheets.
 */
export class Rule extends Rules.AbstractRule {

  apply(sourceFile: ts.SourceFile): RuleFailure[] {
    return this.applyWithWalker(new SwitchStylesheetsWalker(sourceFile, this.getOptions()));
  }
}

export class SwitchStylesheetsWalker extends ComponentWalker {

  constructor(sourceFile: ts.SourceFile, options: IOptions) {
    super(sourceFile, options);

    // This is a special feature. In some applications, developers will have global stylesheets
    // that are not specified in any Angular component. Those stylesheets can be also migrated
    // if the developer specifies the `--extra-stylesheets` option which accepts a glob for files.
    if (process.env[EXTRA_STYLESHEETS_GLOB_KEY]) {
      process.env[EXTRA_STYLESHEETS_GLOB_KEY].split(' ')
github angular / angular-cli / scripts / lint.ts View on Github external
export default async function(options: ParsedArgs, logger: logging.Logger) {
  _buildRules(logger);

  const lintOptions: ILinterOptions = {
    fix: options.fix,
  };

  const program = Linter.createProgram(path.join(__dirname, '../tsconfig.json'));
  const linter = new Linter(lintOptions, program);
  const tsLintPath = path.join(__dirname, '../tslint.json');
  const tsLintConfig = Configuration.loadConfigurationFromPath(tsLintPath);

  // Remove comments from the configuration, ie. keys that starts with "//".
  [...tsLintConfig.rules.keys()]
    .filter(x => x.startsWith('//'))
    .forEach(key => tsLintConfig.rules.delete(key));

  // Console is used directly by tslint, and when finding a rule that doesn't exist it's considered
  // a warning by TSLint but _only_ shown on the console and impossible to see through the API.
  // In order to see any warnings that happen from TSLint itself, we hook into console.warn() and
  // record any calls.
  const oldWarn = console.warn;
  let warnings = false;
  console.warn = (...args) => {
    warnings = true;
github nativescript-vue / vue-cli-plugin-nativescript-vue / lib / tslint.js View on Github external
linter.lint(
      // append .ts so that tslint apply TS rules
      filePath,
      '',
      // use Vue config to ignore blank lines
      isVue ? vueConfig : config
    );
    restoreWriteFile();
  };

  const files = args._ && args._.length ? args._ : ['src/**/*.ts', 'src/**/*.vue', 'src/**/*.tsx', 'tests/**/*.ts', 'tests/**/*.tsx'];

  // respect linterOptions.exclude from tslint.json
  if (config.linterOptions && config.linterOptions.exclude) {
    // use the raw tslint.json data because config contains absolute paths
    const rawTslintConfig = tslint.Configuration.readConfigurationFile(tslintConfigPath);
    const excludedGlobs = rawTslintConfig.linterOptions.exclude;
    excludedGlobs.forEach((g) => files.push('!' + g));
  }

  return globby(files, { cwd }).then((files) => {
    files.forEach(lint);
    if (silent) return;
    const result = linter.getResult();
    if (result.output.trim()) {
      process.stdout.write(result.output);
    } else if (result.fixes.length) {
      // some formatters do not report fixes.
      const f = new tslint.Formatters.ProseFormatter();
      process.stdout.write(f.format(result.failures, result.fixes));
    } else if (!result.failures.length) {
      console.log(`No lint errors found.\n`);
github neoclide / coc-tslint / server / index.ts View on Github external
traceConfigurationFile(configuration.linterConfiguration)
  }

  // tslint writes warnings using console.warn, capture these warnings and send them to the client
  let originalConsoleWarn = console.warn
  let captureWarnings = (message?: any) => {
    conn.sendNotification(StatusNotification.type, { state: Status.warn })
    originalConsoleWarn(message)
  }
  console.warn = captureWarnings

  try {
    // protect against tslint crashes
    let linter = getLinterFromLibrary(library)
    if (isTsLintVersion4(library)) {
      let program = settings.run == 'onSave' ? Linter.createProgram(settings.tsConfigFile) : undefined
      let tslint = new linter(options, program)
      trace(`Linting: start linting with tslint > version 4`)
      tslint.lint(fsPath, contents, configuration.linterConfiguration)
      result = tslint.getResult()
      trace(`Linting: ended linting`)
    }
    // support for linting js files is only available in tslint > 4.0
    else if (!isJsDocument(document)) {
      (options as any).configuration = configuration.linterConfiguration
      trace(`Linting: with tslint < version 4`)
      let tslint = new (linter as any)(fsPath, contents, options)
      result = tslint.lint()
      trace(`Linting: ended linting`)
    } else {
      trace(`No linting: JS linting not supported in tslint < version 4`)
      return diagnostics
github GrimoireGL / GrimoireJS / lint / rules / noUnprivateMethodWithoutCommentRule.js View on Github external
function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ts = require("typescript");
var Lint = require("tslint/lib/lint");
var Rule = (function (_super) {
    __extends(Rule, _super);
    function Rule() {
        _super.apply(this, arguments);
    }
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithWalker(new NoPublicMemberWithoutCommentWalker(sourceFile, this.getOptions()));
    };
    Rule.FAILURE_STRING = "public or protected method must have doc comment";
    return Rule;
})(Lint.Rules.AbstractRule);
exports.Rule = Rule;
// The walker takes care of all the work.
var NoPublicMemberWithoutCommentWalker = (function (_super) {
    __extends(NoPublicMemberWithoutCommentWalker, _super);
    function NoPublicMemberWithoutCommentWalker() {
        _super.apply(this, arguments);
    }
    NoPublicMemberWithoutCommentWalker.prototype.visitMethodDeclaration = function (node) {
        if (this._isPublic(node) || this._isProtected(node)) {
            var modifiers = this.sourceFile.text.substring(node.pos, node.modifiers.end);
            if (!/\/\*\*/m.test(modifiers)) {
                this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING + " at: " + node.name.text));
            }
        }
        // call the base version of this visitor to actually parse this node
        _super.prototype.visitMethodDeclaration.call(this, node);
github mgechev / codelyzer / ts / web-linter.ts View on Github external
if (sourceFile === undefined) {
            throw new Error(`Invalid source file: ${fileName}. Ensure that the files supplied to lint have a .ts or .tsx extension.`);
        }

        // walk the code first to find all the intervals where rules are disabled
        const rulesWalker = new EnableDisableRulesWalker(sourceFile, {
            disabledIntervals: [],
            ruleName: '',
        });
        rulesWalker.walk(sourceFile);
        const enableDisableRuleMap = rulesWalker.enableDisableRuleMap;

        for (let rule of enabledRules) {
            let ruleFailures: Linter.RuleFailure[] = [];
            if (rule instanceof Linter.Rules.TypedRule) {
                console.error('Does not support TypedRules');
            } else {
                ruleFailures = rule.apply(sourceFile);
            }
            for (let ruleFailure of ruleFailures) {
                if (!this.containsRule(this.failures, ruleFailure)) {
                    this.failures.push(ruleFailure);
                }
            }
        }
    }
github GrimoireGL / GrimoireJS / lint / rules / noImplicitReturnTypeRule.js View on Github external
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint/lib/lint");
var Rule = (function (_super) {
    __extends(Rule, _super);
    function Rule() {
        _super.apply(this, arguments);
    }
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithWalker(new NoImplicitReturnTypeWalker(sourceFile, this.getOptions()));
    };
    Rule.FAILURE_STRING = "No implicit return value type is forbidden";
    return Rule;
})(Lint.Rules.AbstractRule);
exports.Rule = Rule;
// The walker takes care of all the work.
var NoImplicitReturnTypeWalker = (function (_super) {
    __extends(NoImplicitReturnTypeWalker, _super);
    function NoImplicitReturnTypeWalker() {
        _super.apply(this, arguments);
    }
    NoImplicitReturnTypeWalker.prototype.visitMethodDeclaration = function (node) {
        if (!node.type) {
            this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING + " at: " + node.name.text));
        }
        //if(node.type)console.log(this.sourceFile.text.substring(node.type.pos,node.type.end));
        // call the base version of this visitor to actually parse this node
        _super.prototype.visitMethodDeclaration.call(this, node);
    };
    NoImplicitReturnTypeWalker.prototype.visitPropertyDeclaration = function (node) {
github vuejs / vue-cli / packages / @vue / cli-plugin-typescript / lib / tslint.js View on Github external
return globby(patterns, { cwd }).then(files => {
    files.forEach(lintFile)
    if (silent) return
    const result = linter.getResult()
    if (result.output.trim()) {
      process.stdout.write(result.output)
    } else if (result.fixes.length) {
      // some formatters do not report fixes.
      const f = new tslint.Formatters.ProseFormatter()
      process.stdout.write(f.format(result.failures, result.fixes))
    } else if (!result.failures.length) {
      console.log(`No lint errors found.\n`)
    }

    if (result.failures.length && !args.force) {
      process.exitCode = 1
    }
  })
}