From a5f2cc73f62942b8228485a5aa52f718ca11ac41 Mon Sep 17 00:00:00 2001 From: ScottSWu Date: Thu, 23 Jun 2016 09:46:32 -0700 Subject: [PATCH] chore(lint): Add lint check for license headers Added a tslint check to make sure all source files begin with a license header (at the very beginning or after a `#!`). Relates to #9380 --- tools/tslint/enforceCopyrightHeaderRule.ts | 32 ++++++++++++++++++++++ tslint.json | 1 + 2 files changed, 33 insertions(+) create mode 100644 tools/tslint/enforceCopyrightHeaderRule.ts diff --git a/tools/tslint/enforceCopyrightHeaderRule.ts b/tools/tslint/enforceCopyrightHeaderRule.ts new file mode 100644 index 0000000000..5f82f1baac --- /dev/null +++ b/tools/tslint/enforceCopyrightHeaderRule.ts @@ -0,0 +1,32 @@ +import {RuleWalker} from 'tslint/lib/language/walker'; +import {RuleFailure} from 'tslint/lib/lint'; +import {AbstractRule} from 'tslint/lib/rules'; +import * as ts from 'typescript'; + +export class Rule extends AbstractRule { + public static FAILURE_STRING = 'missing copyright header'; + + public apply(sourceFile: ts.SourceFile): RuleFailure[] { + const walker = new EnforceCopyrightHeaderWalker(sourceFile, this.getOptions()); + return this.applyWithWalker(walker); + } +} + +class EnforceCopyrightHeaderWalker extends RuleWalker { + private regex: RegExp = /\/\*[\s\S]*?Copyright Google Inc\.[\s\S]*?\*\//; + + public visitSourceFile(node: ts.SourceFile) { + // check for a shebang + let text = node.getFullText(); + let offset = 0; + if (text.indexOf('#!') === 0) { + offset = text.indexOf('\n') + 1; + text = text.substring(offset); + } + // look for the copyright header + let match = text.match(this.regex); + if (!match || match.index !== 0) { + this.addFailure(this.createFailure(offset, offset + 1, Rule.FAILURE_STRING)); + } + } +} diff --git a/tslint.json b/tslint.json index 79d65cd341..6109b334c0 100644 --- a/tslint.json +++ b/tslint.json @@ -2,6 +2,7 @@ "rules": { "requireInternalWithUnderscore": true, "duplicateModuleImport": true, + "enforce-copyright-header": true, "semicolon": true, "variable-name": [true, "ban-keywords"] }