Skip to content

Commit 9644840

Browse files
devversionjelbourn
authored andcommitted
build: write custom tslint rules in typescript (#6650)
Currently the custom TSLint rules of the repository had to be pushed as JavaScript files because TSLint was only able to run them as JavaScript files. Recently with TSLint 5.7.0 (palantir/tslint@90dd3f4), custom rules can be also loaded directly as TypeScript files in combination with ts-node.
1 parent 5d1ce9f commit 9644840

8 files changed

+164
-148
lines changed

package-lock.json

Lines changed: 11 additions & 11 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@
114114
"stylelint": "^7.12.0",
115115
"ts-node": "^3.0.4",
116116
"tsconfig-paths": "^2.2.0",
117-
"tslint": "~5.6.0",
117+
"tslint": "^5.7.0",
118118
"tsutils": "^2.6.0",
119119
"typescript": "~2.2.1",
120120
"uglify-js": "^2.8.14",

tools/gulp/tasks/lint.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {red} from 'chalk';
66

77
// These types lack of type definitions
88
const madge = require('madge');
9+
const resolveBin = require('resolve-bin');
910

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

2930
/** Task to run TSLint against the e2e/ and src/ directories. */
30-
task('tslint', execNodeTask('tslint', tsLintBaseFlags));
31+
task('tslint', execTsLintTask());
3132

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

3536
/** Task that runs madge to detect circular dependencies. */
3637
task('madge', ['material:clean-build'], () => {
@@ -50,3 +51,13 @@ task('madge', ['material:clean-build'], () => {
5051
function formatMadgeCircularModules(circularModules: string[][]): string {
5152
return circularModules.map((modulePaths: string[]) => `\n - ${modulePaths.join(' > ')}`).join('');
5253
}
54+
55+
/** Creates a gulp task function that will run TSLint together with ts-node. */
56+
function execTsLintTask(...flags: string[]) {
57+
const tslintBinPath = resolveBin.sync('tslint');
58+
const tsNodeOptions = ['-O', '{"module": "commonjs"}'];
59+
60+
// TS-Node needs the module compiler option to be set to `commonjs` because the transpiled
61+
// TypeScript files will be running inside of NodeJS.
62+
return execNodeTask('ts-node', [...tsNodeOptions, tslintBinPath, ...tsLintBaseFlags, ...flags]);
63+
}
Lines changed: 56 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,56 @@
1-
const path = require('path');
2-
const Lint = require('tslint');
3-
const minimatch = require('minimatch');
4-
5-
// Since the packaging is based on TypeScript and is only compiled at run-time using ts-node, the
6-
// custom TSLint rule is not able to read the map of rollup globals. Because the custom rules
7-
// for TSLint are written in JavaScript we also need to use ts-node here to read the globals.
8-
require('ts-node').register({
9-
project: path.join(__dirname, '../gulp/tsconfig.json')
10-
});
11-
12-
/**
13-
* Rule that enforces that the specified external packages have been included in our Rollup config.
14-
* Usage: [true, './path/to/rollup/config.json']
15-
*/
16-
class Rule extends Lint.Rules.AbstractRule {
17-
apply(file) {
18-
return this.applyWithWalker(new Walker(file, this.getOptions()));
19-
}
20-
}
21-
22-
class Walker extends Lint.RuleWalker {
23-
constructor(file, options) {
24-
super(...arguments);
25-
26-
if (!options.ruleArguments.length) {
27-
throw Error('missing-rollup-globals: The Rollup config path has to be specified.');
28-
}
29-
30-
const [configPath, ...fileGlobs] = options.ruleArguments;
31-
32-
// Relative path for the current TypeScript source file.
33-
const relativeFilePath = path.relative(process.cwd(), file.fileName);
34-
35-
this._configPath = path.resolve(process.cwd(), configPath);
36-
this._config = require(this._configPath).rollupGlobals;
37-
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
38-
}
39-
40-
visitImportDeclaration(node) {
41-
// Parse out the module name. The first and last characters are the quote marks.
42-
const module = node.moduleSpecifier.getText().slice(1, -1);
43-
const isExternal = !module.startsWith('.') && !module.startsWith('/');
44-
45-
// Check whether the module is external and whether it's in our config.
46-
if (this._enabled && isExternal && !this._config[module]) {
47-
this.addFailureAtNode(node, `Module "${module}" is missing from file ${this._configPath}.`);
48-
}
49-
50-
super.visitImportDeclaration(node);
51-
}
52-
}
53-
54-
exports.Rule = Rule;
1+
import * as path from 'path';
2+
import * as ts from 'typescript';
3+
import * as Lint from 'tslint';
4+
import * as minimatch from 'minimatch';
5+
6+
/**
7+
* Rule that enforces that the specified external packages have been included in our Rollup config.
8+
* Usage: [true, './path/to/rollup/config.json']
9+
*/
10+
export class Rule extends Lint.Rules.AbstractRule {
11+
apply(sourceFile: ts.SourceFile) {
12+
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
13+
}
14+
}
15+
16+
class Walker extends Lint.RuleWalker {
17+
18+
/** Path to the rollup globals configuration file. */
19+
private _configPath: string;
20+
21+
/** Rollup globals configuration object. */
22+
private _config: {[globalName: string]: string};
23+
24+
/** Whether the walker should check the current source file. */
25+
private _enabled: boolean;
26+
27+
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
28+
super(sourceFile, options);
29+
30+
if (!options.ruleArguments.length) {
31+
throw Error('missing-rollup-globals: The Rollup config path has to be specified.');
32+
}
33+
34+
const [configPath, ...fileGlobs] = options.ruleArguments;
35+
36+
// Relative path for the current TypeScript source file.
37+
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);
38+
39+
this._configPath = path.resolve(process.cwd(), configPath);
40+
this._config = require(this._configPath).rollupGlobals;
41+
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
42+
}
43+
44+
visitImportDeclaration(node: ts.ImportDeclaration) {
45+
// Parse out the module name. The first and last characters are the quote marks.
46+
const module = node.moduleSpecifier.getText().slice(1, -1);
47+
const isExternal = !module.startsWith('.') && !module.startsWith('/');
48+
49+
// Check whether the module is external and whether it's in our config.
50+
if (this._enabled && isExternal && !this._config[module]) {
51+
this.addFailureAtNode(node, `Module "${module}" is missing from file ${this._configPath}.`);
52+
}
53+
54+
super.visitImportDeclaration(node);
55+
}
56+
}
Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
const ts = require('typescript');
2-
const utils = require('tsutils');
3-
const Lint = require('tslint');
1+
import * as ts from 'typescript';
2+
import * as Lint from 'tslint';
3+
import * as utils from 'tsutils';
44

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

16-
apply(sourceFile) {
16+
apply(sourceFile: ts.SourceFile) {
1717
return this.applyWithWalker(new NoExposedTodoWalker(sourceFile, this.getOptions()));
1818
}
1919
}
2020

2121
class NoExposedTodoWalker extends Lint.RuleWalker {
2222

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

2727
if (commentRange.kind === ts.SyntaxKind.MultiLineCommentTrivia && isTodoComment) {
2828
this.addFailureAt(commentRange.pos, commentRange.end - commentRange.pos, ERROR_MESSAGE);
@@ -32,5 +32,3 @@ class NoExposedTodoWalker extends Lint.RuleWalker {
3232
super.visitSourceFile(sourceFile);
3333
}
3434
}
35-
36-
exports.Rule = Rule;
Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,44 @@
1-
const Lint = require('tslint');
2-
const minimatch = require('minimatch');
3-
const path = require('path');
4-
5-
const ERROR_MESSAGE = 'Uses of RxJS patch imports are forbidden.';
6-
7-
/**
8-
* Rule that prevents uses of RxJS patch imports (e.g. `import 'rxjs/add/operator/map').
9-
* Supports whitelisting via `"no-patch-imports": [true, "\.spec\.ts$"]`.
10-
*/
11-
class Rule extends Lint.Rules.AbstractRule {
12-
apply(file) {
13-
return this.applyWithWalker(new Walker(file, this.getOptions()));
14-
}
15-
}
16-
17-
class Walker extends Lint.RuleWalker {
18-
constructor(file, options) {
19-
super(...arguments);
20-
21-
// Globs that are used to determine which files to lint.
22-
const fileGlobs = options.ruleArguments || [];
23-
24-
// Relative path for the current TypeScript source file.
25-
const relativeFilePath = path.relative(process.cwd(), file.fileName);
26-
27-
// Whether the file should be checked at all.
28-
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
29-
}
30-
31-
visitImportDeclaration(node) {
32-
// Walk through the imports and check if they start with `rxjs/add`.
33-
if (this._enabled && node.moduleSpecifier.getText().startsWith('rxjs/add', 1)) {
34-
this.addFailureAtNode(node, ERROR_MESSAGE);
35-
}
36-
37-
super.visitImportDeclaration(node);
38-
}
39-
}
40-
41-
exports.Rule = Rule;
1+
import * as path from 'path';
2+
import * as ts from 'typescript';
3+
import * as Lint from 'tslint';
4+
import * as minimatch from 'minimatch';
5+
6+
const ERROR_MESSAGE = 'Uses of RxJS patch imports are forbidden.';
7+
8+
/**
9+
* Rule that prevents uses of RxJS patch imports (e.g. `import 'rxjs/add/operator/map').
10+
* Supports whitelisting via `"no-patch-imports": [true, "\.spec\.ts$"]`.
11+
*/
12+
export class Rule extends Lint.Rules.AbstractRule {
13+
apply(sourceFile: ts.SourceFile) {
14+
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
15+
}
16+
}
17+
18+
class Walker extends Lint.RuleWalker {
19+
20+
/** Whether the walker should check the current source file. */
21+
private _enabled: boolean;
22+
23+
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
24+
super(sourceFile, options);
25+
26+
// Globs that are used to determine which files to lint.
27+
const fileGlobs = options.ruleArguments || [];
28+
29+
// Relative path for the current TypeScript source file.
30+
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);
31+
32+
// Whether the file should be checked at all.
33+
this._enabled = fileGlobs.some(p => minimatch(relativeFilePath, p));
34+
}
35+
36+
visitImportDeclaration(node: ts.ImportDeclaration) {
37+
// Walk through the imports and check if they start with `rxjs/add`.
38+
if (this._enabled && node.moduleSpecifier.getText().startsWith('rxjs/add', 1)) {
39+
this.addFailureAtNode(node, ERROR_MESSAGE);
40+
}
41+
42+
super.visitImportDeclaration(node);
43+
}
44+
}

tools/tslint-rules/noViewEncapsulationRule.js renamed to tools/tslint-rules/noViewEncapsulationRule.ts

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
const Lint = require('tslint');
2-
const path = require('path');
3-
const minimatch = require('minimatch');
1+
import * as path from 'path';
2+
import * as ts from 'typescript';
3+
import * as Lint from 'tslint';
4+
import * as minimatch from 'minimatch';
45

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

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

1920
class Walker extends Lint.RuleWalker {
20-
constructor(file, options) {
21-
super(...arguments);
21+
22+
/** Whether the walker should check the current source file. */
23+
private _enabled: boolean;
24+
25+
constructor(sourceFile: ts.SourceFile, options: Lint.IOptions) {
26+
super(sourceFile, options);
2227

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

2631
// Relative path for the current TypeScript source file.
27-
const relativeFilePath = path.relative(process.cwd(), file.fileName);
32+
const relativeFilePath = path.relative(process.cwd(), sourceFile.fileName);
2833

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

3338
visitClassDeclaration(node) {
34-
if (!this._enabled || !node.decorators) return;
39+
if (!this._enabled || !node.decorators) {
40+
return;
41+
}
3542

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

5259
}
53-
54-
exports.Rule = Rule;

0 commit comments

Comments
 (0)