|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google Inc. All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.io/license |
| 7 | + */ |
| 8 | +import * as Lint from 'tslint'; |
| 9 | +import * as ts from 'typescript'; |
| 10 | + |
| 11 | + |
| 12 | +export class Rule extends Lint.Rules.AbstractRule { |
| 13 | + public static metadata: Lint.IRuleMetadata = { |
| 14 | + ruleName: 'no-global-tslint-disable', |
| 15 | + type: 'style', |
| 16 | + description: `Ensure global tslint disable are only used for unit tests.`, |
| 17 | + rationale: `Some projects want to disallow tslint disable and only use per-line ones.`, |
| 18 | + options: null, |
| 19 | + optionsDescription: `Not configurable.`, |
| 20 | + typescriptOnly: false, |
| 21 | + }; |
| 22 | + |
| 23 | + public static FAILURE_STRING = 'tslint:disable is not allowed in this context.'; |
| 24 | + |
| 25 | + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { |
| 26 | + return this.applyWithWalker(new Walker(sourceFile, this.getOptions())); |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | + |
| 31 | +class Walker extends Lint.RuleWalker { |
| 32 | + private _findComments(node: ts.Node): ts.CommentRange[] { |
| 33 | + return ([] as ts.CommentRange[]).concat( |
| 34 | + ts.getLeadingCommentRanges(node.getFullText(), 0) || [], |
| 35 | + ts.getTrailingCommentRanges(node.getFullText(), 0) || [], |
| 36 | + node.getChildren().reduce((acc, n) => { |
| 37 | + return acc.concat(this._findComments(n)); |
| 38 | + }, [] as ts.CommentRange[]), |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + walk(sourceFile: ts.SourceFile) { |
| 43 | + super.walk(sourceFile); |
| 44 | + |
| 45 | + // Ignore spec files. |
| 46 | + if (sourceFile.fileName.match(/_spec.ts$/)) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + // Find all comment nodes. |
| 51 | + const ranges = this._findComments(sourceFile); |
| 52 | + ranges.forEach(range => { |
| 53 | + const text = sourceFile.getFullText().substring(range.pos, range.end); |
| 54 | + let i = text.indexOf('tslint:disable:'); |
| 55 | + |
| 56 | + while (i != -1) { |
| 57 | + this.addFailureAt(range.pos + i + 1, range.pos + i + 15, Rule.FAILURE_STRING); |
| 58 | + i = text.indexOf('tslint:disable:', i + 1); |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
| 62 | +} |
0 commit comments