4 * Copyright 2013 Palantir Technologies, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 Object.defineProperty(exports, "__esModule", { value: true });
19 var tslib_1 = require("tslib");
20 var utils = require("tsutils");
21 var ts = require("typescript");
22 var enableDisableRules_1 = require("../enableDisableRules");
23 var Lint = require("../index");
24 var utils_1 = require("../utils");
25 var OPTION_SPACE = "check-space";
26 var OPTION_LOWERCASE = "check-lowercase";
27 var OPTION_UPPERCASE = "check-uppercase";
28 var OPTION_ALLOW_TRAILING_LOWERCASE = "allow-trailing-lowercase";
29 var Rule = /** @class */ (function (_super) {
30 tslib_1.__extends(Rule, _super);
32 return _super !== null && _super.apply(this, arguments) || this;
34 Rule.prototype.apply = function (sourceFile) {
35 var commentFormatWalker = new CommentFormatWalker(sourceFile, this.ruleName, parseOptions(this.ruleArguments));
36 return this.applyWithWalker(commentFormatWalker);
38 /* tslint:disable:object-literal-sort-keys */
40 ruleName: "comment-format",
41 description: "Enforces formatting rules for single-line comments.",
42 rationale: "Helps maintain a consistent, readable style in your codebase.",
43 optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Four arguments may be optionally provided:\n\n * `\"", "\"` requires that all single-line comments must begin with a space, as in `// comment`\n * note that for comments starting with multiple slashes, e.g. `///`, leading slashes are ignored\n * TypeScript reference comments are ignored completely\n * `\"", "\"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n * `\"", "\"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n * `\"", "\"` allows that only the first comment of a series of comments needs to be uppercase.\n * requires `\"", "\"`\n * comments must start at the same position\n\n Exceptions to `\"", "\"` or `\"", "\"` can be managed with object that may be passed as last\n argument.\n\n One of two options can be provided in this object:\n\n * `\"ignore-words\"` - array of strings - words that will be ignored at the beginning of the comment.\n * `\"ignore-pattern\"` - string - RegExp pattern that will be ignored at the beginning of the comment.\n "], ["\n Four arguments may be optionally provided:\n\n * \\`\"", "\"\\` requires that all single-line comments must begin with a space, as in \\`// comment\\`\n * note that for comments starting with multiple slashes, e.g. \\`///\\`, leading slashes are ignored\n * TypeScript reference comments are ignored completely\n * \\`\"", "\"\\` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n * \\`\"", "\"\\` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n * \\`\"", "\"\\` allows that only the first comment of a series of comments needs to be uppercase.\n * requires \\`\"", "\"\\`\n * comments must start at the same position\n\n Exceptions to \\`\"", "\"\\` or \\`\"", "\"\\` can be managed with object that may be passed as last\n argument.\n\n One of two options can be provided in this object:\n\n * \\`\"ignore-words\"\\` - array of strings - words that will be ignored at the beginning of the comment.\n * \\`\"ignore-pattern\"\\` - string - RegExp pattern that will be ignored at the beginning of the comment.\n "])), OPTION_SPACE, OPTION_LOWERCASE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE, OPTION_UPPERCASE, OPTION_LOWERCASE, OPTION_UPPERCASE),
54 OPTION_ALLOW_TRAILING_LOWERCASE,
79 [true, OPTION_SPACE, OPTION_UPPERCASE, OPTION_ALLOW_TRAILING_LOWERCASE],
80 [true, OPTION_LOWERCASE, { "ignore-words": ["TODO", "HACK"] }],
81 [true, OPTION_LOWERCASE, { "ignore-pattern": "STD\\w{2,3}\\b" }],
84 typescriptOnly: false,
87 /* tslint:enable:object-literal-sort-keys */
88 Rule.LOWERCASE_FAILURE = "comment must start with lowercase letter";
89 Rule.SPACE_LOWERCASE_FAILURE = "comment must start with a space and lowercase letter";
90 Rule.UPPERCASE_FAILURE = "comment must start with uppercase letter";
91 Rule.SPACE_UPPERCASE_FAILURE = "comment must start with a space and uppercase letter";
92 Rule.LEADING_SPACE_FAILURE = "comment must start with a space";
93 Rule.IGNORE_WORDS_FAILURE_FACTORY = function (words) {
94 return " or the word(s): " + words.join(", ");
96 Rule.IGNORE_PATTERN_FAILURE_FACTORY = function (pattern) {
97 return " or its start must match the regex pattern \"" + pattern + "\"";
100 }(Lint.Rules.AbstractRule));
102 function parseOptions(options) {
103 return tslib_1.__assign({ allowTrailingLowercase: has(OPTION_ALLOW_TRAILING_LOWERCASE), case: options.indexOf(OPTION_LOWERCASE) !== -1
105 : options.indexOf(OPTION_UPPERCASE) !== -1
107 : 0 /* None */, failureSuffix: "", space: has(OPTION_SPACE) }, composeExceptions(options[options.length - 1]));
108 function has(option) {
109 return options.indexOf(option) !== -1;
112 function composeExceptions(option) {
113 if (typeof option !== "object") {
116 var ignorePattern = option["ignore-pattern"];
117 if (ignorePattern !== undefined) {
119 exceptions: new RegExp("^\\s*(" + ignorePattern + ")"),
120 failureSuffix: Rule.IGNORE_PATTERN_FAILURE_FACTORY(ignorePattern),
123 var ignoreWords = option["ignore-words"];
124 if (ignoreWords !== undefined && ignoreWords.length !== 0) {
126 exceptions: new RegExp("^\\s*(?:" + ignoreWords.map(function (word) { return utils_1.escapeRegExp(word.trim()); }).join("|") + ")\\b"),
127 failureSuffix: Rule.IGNORE_WORDS_FAILURE_FACTORY(ignoreWords),
132 var CommentFormatWalker = /** @class */ (function (_super) {
133 tslib_1.__extends(CommentFormatWalker, _super);
134 function CommentFormatWalker() {
135 return _super !== null && _super.apply(this, arguments) || this;
137 CommentFormatWalker.prototype.walk = function (sourceFile) {
139 utils.forEachComment(sourceFile, function (fullText, comment) {
140 var commentStatus = _this.checkComment(fullText, comment);
141 _this.handleFailure(commentStatus, comment.end);
142 // cache position of last comment
143 _this.prevComment = ts.getLineAndCharacterOfPosition(sourceFile, comment.pos);
144 _this.prevCommentIsValid = commentStatus.validForTrailingLowercase;
147 CommentFormatWalker.prototype.checkComment = function (fullText, _a) {
148 var kind = _a.kind, pos = _a.pos, end = _a.end;
151 leadingSpaceError: false,
152 lowercaseError: false,
155 uppercaseError: false,
156 validForTrailingLowercase: false,
158 if (kind !== ts.SyntaxKind.SingleLineCommentTrivia ||
159 // exclude empty comments
160 status.start === end ||
161 // exclude /// <reference path="...">
162 (fullText[status.start] === "/" &&
163 this.sourceFile.referencedFiles.some(function (ref) { return ref.pos >= pos && ref.end <= end; }))) {
166 // skip all leading slashes
167 while (fullText[status.start] === "/") {
170 if (status.start === end) {
173 status.text = fullText.slice(status.start, end);
174 // whitelist //#region and //#endregion and JetBrains IDEs' "//noinspection ...", "//region", "//endregion"
175 if (/^(?:#?(?:end)?region|noinspection\s)/.test(status.text)) {
178 if (this.options.space && status.text[0] !== " ") {
179 status.leadingSpaceError = true;
181 if (this.options.case === 0 /* None */ ||
182 (this.options.exceptions !== undefined && this.options.exceptions.test(status.text)) ||
183 enableDisableRules_1.ENABLE_DISABLE_REGEX.test(status.text)) {
186 // search for first non-space character to check if lower or upper
187 var charPos = status.text.search(/\S/);
188 if (charPos === -1) {
191 // All non-empty and not whitelisted comments are valid for the trailing lowercase rule
192 status.validForTrailingLowercase = true;
193 status.firstLetterPos = charPos;
194 if (this.options.case === 1 /* Lower */ && !utils_1.isLowerCase(status.text[charPos])) {
195 status.lowercaseError = true;
197 else if (this.options.case === 2 /* Upper */ && !utils_1.isUpperCase(status.text[charPos])) {
198 status.uppercaseError = true;
199 if (this.options.allowTrailingLowercase &&
200 this.prevComment !== undefined &&
201 this.prevCommentIsValid) {
202 var currentComment = ts.getLineAndCharacterOfPosition(this.sourceFile, pos);
203 if (this.prevComment.line + 1 === currentComment.line &&
204 this.prevComment.character === currentComment.character) {
205 status.uppercaseError = false;
211 CommentFormatWalker.prototype.handleFailure = function (status, end) {
212 // No failure detected
213 if (!status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) {
216 // Only whitespace failure
217 if (status.leadingSpaceError && !status.lowercaseError && !status.uppercaseError) {
218 this.addFailure(status.start, end, Rule.LEADING_SPACE_FAILURE, Lint.Replacement.appendText(status.start, " "));
223 if (status.lowercaseError) {
224 msg = status.leadingSpaceError ? Rule.SPACE_LOWERCASE_FAILURE : Rule.LOWERCASE_FAILURE;
225 firstLetterFix = status.text[status.firstLetterPos].toLowerCase();
228 msg = status.leadingSpaceError ? Rule.SPACE_UPPERCASE_FAILURE : Rule.UPPERCASE_FAILURE;
229 firstLetterFix = status.text[status.firstLetterPos].toUpperCase();
231 var fix = status.leadingSpaceError
232 ? new Lint.Replacement(status.start, 1, " " + firstLetterFix)
233 : new Lint.Replacement(status.start + status.firstLetterPos, 1, firstLetterFix);
234 this.addFailure(status.start, end, msg + this.options.failureSuffix, fix);
236 return CommentFormatWalker;
237 }(Lint.AbstractWalker));
238 var templateObject_1;