|
| 1 | +const Lint = require('tslint'); |
| 2 | +const path = require('path'); |
| 3 | +const buildConfig = require('../../build-config'); |
| 4 | + |
| 5 | +/** Paths to the directories that are public packages and should be validated. */ |
| 6 | +const packageDirs = [ |
| 7 | + path.join(buildConfig.packagesDir, 'lib'), |
| 8 | + path.join(buildConfig.packagesDir, 'cdk') |
| 9 | +]; |
| 10 | + |
| 11 | +/** License banner that is placed at the top of every public TypeScript file. */ |
| 12 | +const licenseBanner = buildConfig.licenseBanner; |
| 13 | + |
| 14 | +/** Failure message that will be shown if a license banner is missing. */ |
| 15 | +const ERROR_MESSAGE = 'Missing license header in this TypeScript file. ' + |
| 16 | + 'Every TypeScript file of the library needs to have the Google license banner at the top.'; |
| 17 | + |
| 18 | +/** TSLint fix that can be used to add the license banner easily. */ |
| 19 | +const tslintFix = Lint.Replacement.appendText(0, licenseBanner + '\n\n'); |
| 20 | + |
| 21 | +/** |
| 22 | + * Rule that walks through all TypeScript files of public packages and shows failures if a |
| 23 | + * file does not have the license banner at the top of the file. |
| 24 | + */ |
| 25 | +class Rule extends Lint.Rules.AbstractRule { |
| 26 | + |
| 27 | + apply(sourceFile) { |
| 28 | + return this.applyWithWalker(new RequireLicenseBannerWalker(sourceFile, this.getOptions())); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +class RequireLicenseBannerWalker extends Lint.RuleWalker { |
| 33 | + |
| 34 | + visitSourceFile(sourceFile) { |
| 35 | + const filePath = path.join(buildConfig.projectDir, sourceFile.fileName); |
| 36 | + |
| 37 | + // Do not check TypeScript source files that are not inside of a public package. |
| 38 | + if (!packageDirs.some(packageDir => filePath.includes(packageDir))) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + // Do not check source files inside of public packages that are spec or definition files. |
| 43 | + if (filePath.endsWith('.spec.ts') || filePath.endsWith('.d.ts')) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + const fileContent = sourceFile.getFullText(); |
| 48 | + const licenseCommentPos = fileContent.indexOf(licenseBanner); |
| 49 | + |
| 50 | + if (licenseCommentPos !== 0) { |
| 51 | + return this.addFailureAt(0, 0, ERROR_MESSAGE, tslintFix); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +exports.Rule = Rule; |
0 commit comments