|
| 1 | +import * as ts from 'typescript'; |
| 2 | +import * as Lint from 'tslint'; |
| 3 | +import * as utils from 'tsutils'; |
| 4 | +import * as path from 'path'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Rule ensuring that deletion targets have not expired. |
| 8 | + * The current version is taken from the `package.json`. |
| 9 | + */ |
| 10 | +export class Rule extends Lint.Rules.AbstractRule { |
| 11 | + apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { |
| 12 | + const packageVersion = require(path.join(process.cwd(), 'package.json')).version; |
| 13 | + |
| 14 | + return this.applyWithFunction(sourceFile, (ctx: Lint.WalkContext<any>) => { |
| 15 | + utils.forEachComment(ctx.sourceFile, (file, {pos, end}) => { |
| 16 | + const commentText = file.substring(pos, end); |
| 17 | + |
| 18 | + if (commentText.indexOf('@deletion-target') === -1) { |
| 19 | + return; |
| 20 | + } |
| 21 | + |
| 22 | + const version = commentText.match(/\d+\.\d+\.\d+/); |
| 23 | + |
| 24 | + if (!version) { |
| 25 | + ctx.addFailure(pos, end, '@deletion-target must have a version.'); |
| 26 | + } else if (this._hasExpired(packageVersion, version[0])) { |
| 27 | + ctx.addFailure(pos, end, `Deletion target at ${version[0]} is due to be deleted. ` + |
| 28 | + `Current version is ${packageVersion}.`); |
| 29 | + } |
| 30 | + }); |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Checks whether a version has expired, based on the current version. |
| 36 | + * @param currentVersion Current version of the package. |
| 37 | + * @param deletionTarget Version that is being checked. |
| 38 | + */ |
| 39 | + private _hasExpired(currentVersion: string, deletionTarget: string) { |
| 40 | + if (currentVersion === deletionTarget) { |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | + const current = this._parseVersion(currentVersion); |
| 45 | + const target = this._parseVersion(deletionTarget); |
| 46 | + |
| 47 | + return target.major < current.major || |
| 48 | + (target.major === current.major && target.minor < current.minor) || |
| 49 | + ( |
| 50 | + target.major === current.major && |
| 51 | + target.minor === current.minor && |
| 52 | + target.patch < current.patch |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + /** Converts a version string into an object. */ |
| 57 | + private _parseVersion(version: string) { |
| 58 | + const [major = 0, minor = 0, patch = 0] = version.split('.').map(segment => parseInt(segment)); |
| 59 | + return {major, minor, patch}; |
| 60 | + } |
| 61 | +} |
0 commit comments