|
| 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: 'single-eof-line', |
| 15 | + type: 'style', |
| 16 | + description: `Ensure the file ends with a single new line.`, |
| 17 | + rationale: `This is similar to eofline, but ensure an exact count instead of just any new |
| 18 | + line.`, |
| 19 | + options: null, |
| 20 | + optionsDescription: `Two integers indicating minimum and maximum number of new lines.`, |
| 21 | + typescriptOnly: false, |
| 22 | + }; |
| 23 | + |
| 24 | + public static FAILURE_STRING = 'You need to have a single blank line at end of file.'; |
| 25 | + |
| 26 | + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { |
| 27 | + const length = sourceFile.text.length; |
| 28 | + if (length === 0) { |
| 29 | + // Allow empty files. |
| 30 | + return []; |
| 31 | + } |
| 32 | + |
| 33 | + const matchEof = /\r?\n((\r?\n)*)$/.exec(sourceFile.text); |
| 34 | + if (!matchEof) { |
| 35 | + const lines = sourceFile.getLineStarts(); |
| 36 | + const fix = Lint.Replacement.appendText( |
| 37 | + length, |
| 38 | + sourceFile.text[lines[1] - 2] === '\r' ? '\r\n' : '\n', |
| 39 | + ); |
| 40 | + |
| 41 | + return [ |
| 42 | + new Lint.RuleFailure(sourceFile, length, length, Rule.FAILURE_STRING, this.ruleName, fix), |
| 43 | + ]; |
| 44 | + } else if (matchEof[1]) { |
| 45 | + const lines = sourceFile.getLineStarts(); |
| 46 | + const fix = Lint.Replacement.replaceFromTo( |
| 47 | + matchEof.index, |
| 48 | + length, |
| 49 | + sourceFile.text[lines[1] - 2] === '\r' ? '\r\n' : '\n', |
| 50 | + ); |
| 51 | + |
| 52 | + return [ |
| 53 | + new Lint.RuleFailure(sourceFile, length, length, Rule.FAILURE_STRING, this.ruleName, fix), |
| 54 | + ]; |
| 55 | + } |
| 56 | + |
| 57 | + return []; |
| 58 | + } |
| 59 | +} |
0 commit comments