Skip to content

build: write custom tslint rules in typescript #6650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@
"stylelint": "^7.12.0",
"ts-node": "^3.0.4",
"tsconfig-paths": "^2.2.0",
"tslint": "~5.6.0",
"tslint": "^5.7.0",
"tsutils": "^2.6.0",
"typescript": "~2.2.1",
"uglify-js": "^2.8.14",
Expand Down
15 changes: 13 additions & 2 deletions tools/gulp/tasks/lint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {red} from 'chalk';

// These types lack of type definitions
const madge = require('madge');
const resolveBin = require('resolve-bin');

/** Glob that matches all SCSS or CSS files that should be linted. */
const stylesGlob = '+(tools|src)/**/!(*.bundle).+(css|scss)';
Expand All @@ -27,10 +28,10 @@ task('stylelint', execNodeTask(
));

/** Task to run TSLint against the e2e/ and src/ directories. */
task('tslint', execNodeTask('tslint', tsLintBaseFlags));
task('tslint', execTsLintTask());

/** Task that automatically fixes TSLint warnings. */
task('tslint:fix', execNodeTask('tslint', [...tsLintBaseFlags, '--fix']));
task('tslint:fix', execTsLintTask('--fix'));

/** Task that runs madge to detect circular dependencies. */
task('madge', ['material:clean-build'], () => {
Expand All @@ -50,3 +51,13 @@ task('madge', ['material:clean-build'], () => {
function formatMadgeCircularModules(circularModules: string[][]): string {
return circularModules.map((modulePaths: string[]) => `\n - ${modulePaths.join(' > ')}`).join('');
}

/** Creates a gulp task function that will run TSLint together with ts-node. */
function execTsLintTask(...flags: string[]) {
const tslintBinPath = resolveBin.sync('tslint');
const tsNodeOptions = ['-O', '{"module": "commonjs"}'];

// TS-Node needs the module compiler option to be set to `commonjs` because the transpiled
// TypeScript files will be running inside of NodeJS.
return execNodeTask('ts-node', [...tsNodeOptions, tslintBinPath, ...tsLintBaseFlags, ...flags]);
}
Original file line number Diff line number Diff line change
@@ -1,54 +1,56 @@
const path = require('path');
const Lint = require('tslint');
const minimatch = require('minimatch');

// Since the packaging is based on TypeScript and is only compiled at run-time using ts-node, the
// custom TSLint rule is not able to read the map of rollup globals. Because the custom rules
// for TSLint are written in JavaScript we also need to use ts-node here to read the globals.
require('ts-node').register({
project: path.join(__dirname, '../gulp/tsconfig.json')
});

/**
* Rule that enforces that the specified external packages have been included in our Rollup config.
* Usage: [true, './path/to/rollup/config.json']
*/
class Rule extends Lint.Rules.AbstractRule {
apply(file) {
return this.applyWithWalker(new Walker(file, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {
constructor(file, options) {
super(...arguments);

if (!options.ruleArguments.length) {
throw Error('missing-rollup-globals: The Rollup config path has to be specified.');
}

const [configPath, ...fileGlobs] = options.ruleArguments;

// Relative path for the current TypeScript source file.
const relativeFilePath = path.relative(process.cwd(), file.fileName);

this._configPath = path.resolve(process.cwd(), configPath);
this._config = require(this._configPath).rollupGlobals;
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
}

visitImportDeclaration(node) {
// Parse out the module name. The first and last characters are the quote marks.
const module = node.moduleSpecifier.getText().slice(1, -1);
const isExternal = !module.startsWith('.') && !module.startsWith('/');

// Check whether the module is external and whether it's in our config.
if (this._enabled && isExternal && !this._config[module]) {
this.addFailureAtNode(node, `Module "${module}" is missing from file ${this._configPath}.`);
}

super.visitImportDeclaration(node);
}
}

exports.Rule = Rule;
import * as path from 'path';
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as minimatch from 'minimatch';

/**
* Rule that enforces that the specified external packages have been included in our Rollup config.
* Usage: [true, './path/to/rollup/config.json']
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile) {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {

/** Path to the rollup globals configuration file. */
private _configPath: string;

/** Rollup globals configuration object. */
private _config: {[globalName: string]: string};

/** Whether the walker should check the current source file. */
private _enabled: boolean;

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

if (!options.ruleArguments.length) {
throw Error('missing-rollup-globals: The Rollup config path has to be specified.');
}

const [configPath, ...fileGlobs] = options.ruleArguments;

// Relative path for the current TypeScript source file.
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);

this._configPath = path.resolve(process.cwd(), configPath);
this._config = require(this._configPath).rollupGlobals;
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
}

visitImportDeclaration(node: ts.ImportDeclaration) {
// Parse out the module name. The first and last characters are the quote marks.
const module = node.moduleSpecifier.getText().slice(1, -1);
const isExternal = !module.startsWith('.') && !module.startsWith('/');

// Check whether the module is external and whether it's in our config.
if (this._enabled && isExternal && !this._config[module]) {
this.addFailureAtNode(node, `Module "${module}" is missing from file ${this._configPath}.`);
}

super.visitImportDeclaration(node);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const ts = require('typescript');
const utils = require('tsutils');
const Lint = require('tslint');
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as utils from 'tsutils';

const ERROR_MESSAGE =
'A TODO may only appear in inline (//) style comments. ' +
Expand All @@ -11,18 +11,18 @@ const ERROR_MESSAGE =
* detects TODO's inside of multi-line comments. TODOs need to be placed inside of single-line
* comments.
*/
class Rule extends Lint.Rules.AbstractRule {
export class Rule extends Lint.Rules.AbstractRule {

apply(sourceFile) {
apply(sourceFile: ts.SourceFile) {
return this.applyWithWalker(new NoExposedTodoWalker(sourceFile, this.getOptions()));
}
}

class NoExposedTodoWalker extends Lint.RuleWalker {

visitSourceFile(sourceFile) {
utils.forEachComment(sourceFile, (fullText, commentRange) => {
let isTodoComment = fullText.substring(commentRange.pos, commentRange.end).includes('TODO');
visitSourceFile(sourceFile: ts.SourceFile) {
utils.forEachComment(sourceFile, (text, commentRange) => {
const isTodoComment = text.substring(commentRange.pos, commentRange.end).includes('TODO:');

if (commentRange.kind === ts.SyntaxKind.MultiLineCommentTrivia && isTodoComment) {
this.addFailureAt(commentRange.pos, commentRange.end - commentRange.pos, ERROR_MESSAGE);
Expand All @@ -32,5 +32,3 @@ class NoExposedTodoWalker extends Lint.RuleWalker {
super.visitSourceFile(sourceFile);
}
}

exports.Rule = Rule;
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
const Lint = require('tslint');
const minimatch = require('minimatch');
const path = require('path');

const ERROR_MESSAGE = 'Uses of RxJS patch imports are forbidden.';

/**
* Rule that prevents uses of RxJS patch imports (e.g. `import 'rxjs/add/operator/map').
* Supports whitelisting via `"no-patch-imports": [true, "\.spec\.ts$"]`.
*/
class Rule extends Lint.Rules.AbstractRule {
apply(file) {
return this.applyWithWalker(new Walker(file, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {
constructor(file, options) {
super(...arguments);

// Globs that are used to determine which files to lint.
const fileGlobs = options.ruleArguments || [];

// Relative path for the current TypeScript source file.
const relativeFilePath = path.relative(process.cwd(), file.fileName);

// Whether the file should be checked at all.
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
}

visitImportDeclaration(node) {
// Walk through the imports and check if they start with `rxjs/add`.
if (this._enabled && node.moduleSpecifier.getText().startsWith('rxjs/add', 1)) {
this.addFailureAtNode(node, ERROR_MESSAGE);
}

super.visitImportDeclaration(node);
}
}

exports.Rule = Rule;
import * as path from 'path';
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as minimatch from 'minimatch';

const ERROR_MESSAGE = 'Uses of RxJS patch imports are forbidden.';

/**
* Rule that prevents uses of RxJS patch imports (e.g. `import 'rxjs/add/operator/map').
* Supports whitelisting via `"no-patch-imports": [true, "\.spec\.ts$"]`.
*/
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile) {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {

/** Whether the walker should check the current source file. */
private _enabled: boolean;

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

// Globs that are used to determine which files to lint.
const fileGlobs = options.ruleArguments || [];

// Relative path for the current TypeScript source file.
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);

// Whether the file should be checked at all.
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
}

visitImportDeclaration(node: ts.ImportDeclaration) {
// Walk through the imports and check if they start with `rxjs/add`.
if (this._enabled && node.moduleSpecifier.getText().startsWith('rxjs/add', 1)) {
this.addFailureAtNode(node, ERROR_MESSAGE);
}

super.visitImportDeclaration(node);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Lint = require('tslint');
const path = require('path');
const minimatch = require('minimatch');
import * as path from 'path';
import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as minimatch from 'minimatch';

const ERROR_MESSAGE = 'Components must turn off view encapsulation.';

Expand All @@ -10,28 +11,34 @@ const ERROR_MESSAGE = 'Components must turn off view encapsulation.';
* Rule that enforces that view encapsulation is turned off on all components.
* Files can be whitelisted via `"no-view-encapsulation": [true, "\.spec\.ts$"]`.
*/
class Rule extends Lint.Rules.AbstractRule {
apply(file) {
return this.applyWithWalker(new Walker(file, this.getOptions()));
export class Rule extends Lint.Rules.AbstractRule {
apply(sourceFile: ts.SourceFile) {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

class Walker extends Lint.RuleWalker {
constructor(file, options) {
super(...arguments);

/** Whether the walker should check the current source file. */
private _enabled: boolean;

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

// Globs that are used to determine which files to lint.
const fileGlobs = options.ruleArguments || [];

// Relative path for the current TypeScript source file.
const relativeFilePath = path.relative(process.cwd(), file.fileName);
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);

// Whether the file should be checked at all.
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
}

visitClassDeclaration(node) {
if (!this._enabled || !node.decorators) return;
if (!this._enabled || !node.decorators) {
return;
}

node.decorators
.map(decorator => decorator.expression)
Expand All @@ -50,5 +57,3 @@ class Walker extends Lint.RuleWalker {
}

}

exports.Rule = Rule;
Loading