|
| 1 | +import {RuleFailure} from 'tslint/lib/lint'; |
| 2 | +import {AbstractRule} from 'tslint/lib/rules'; |
| 3 | +import {RuleWalker} from 'tslint/lib/language/walker'; |
| 4 | +import * as ts from 'tslint/node_modules/typescript'; |
| 5 | + |
| 6 | +export class Rule extends AbstractRule { |
| 7 | + public apply(sourceFile: ts.SourceFile): RuleFailure[] { |
| 8 | + const typedefWalker = new TypedefWalker(sourceFile, this.getOptions()); |
| 9 | + return this.applyWithWalker(typedefWalker); |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +class TypedefWalker extends RuleWalker { |
| 14 | + protected visitPropertyDeclaration(node: ts.PropertyDeclaration): void { |
| 15 | + this.assertInternalAnnotationPresent(node); |
| 16 | + super.visitPropertyDeclaration(node); |
| 17 | + } |
| 18 | + |
| 19 | + public visitMethodDeclaration(node: ts.MethodDeclaration): void { |
| 20 | + this.assertInternalAnnotationPresent(node); |
| 21 | + super.visitMethodDeclaration(node); |
| 22 | + } |
| 23 | + |
| 24 | + private hasInternalAnnotation(range: ts.CommentRange): boolean { |
| 25 | + let text = this.getSourceFile().text; |
| 26 | + let comment = text.substring(range.pos, range.end); |
| 27 | + return comment.indexOf("@internal") >= 0; |
| 28 | + } |
| 29 | + |
| 30 | + private assertInternalAnnotationPresent(node: ts.Declaration) { |
| 31 | + if (node.name.getText().charAt(0) !== '_') return; |
| 32 | + if (node.modifiers && node.modifiers.flags & ts.NodeFlags.Private) return; |
| 33 | + |
| 34 | + const ranges = ts.getLeadingCommentRanges(this.getSourceFile().text, node.pos); |
| 35 | + if (ranges) { |
| 36 | + for (let i = 0; i < ranges.length; i++) { |
| 37 | + if (this.hasInternalAnnotation(ranges[i])) return; |
| 38 | + } |
| 39 | + } |
| 40 | + this.addFailure(this.createFailure( |
| 41 | + node.getStart(), node.getWidth(), |
| 42 | + `module-private member ${node.name.getText()} must be annotated @internal`)); |
| 43 | + } |
| 44 | +} |
0 commit comments