commentFormatRule.js 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2013 Palantir Technologies, Inc.
  5. *
  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
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  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.
  17. */
  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 Rule = /** @class */ (function (_super) {
  29. tslib_1.__extends(Rule, _super);
  30. function Rule() {
  31. return _super !== null && _super.apply(this, arguments) || this;
  32. }
  33. Rule.prototype.apply = function (sourceFile) {
  34. return this.applyWithFunction(sourceFile, walk, parseOptions(this.ruleArguments));
  35. };
  36. /* tslint:disable:object-literal-sort-keys */
  37. Rule.metadata = {
  38. ruleName: "comment-format",
  39. description: "Enforces formatting rules for single-line comments.",
  40. rationale: "Helps maintain a consistent, readable style in your codebase.",
  41. optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Three arguments may be optionally provided:\n\n * `\"check-space\"` 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 * `\"check-lowercase\"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n * `\"check-uppercase\"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n\n Exceptions to `\"check-lowercase\"` or `\"check-uppercase\"` can be managed with object that may be passed as last 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 Three arguments may be optionally provided:\n\n * \\`\"check-space\"\\` 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 * \\`\"check-lowercase\"\\` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n * \\`\"check-uppercase\"\\` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n\n Exceptions to \\`\"check-lowercase\"\\` or \\`\"check-uppercase\"\\` can be managed with object that may be passed as last 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 "]))),
  42. options: {
  43. type: "array",
  44. items: {
  45. anyOf: [
  46. {
  47. type: "string",
  48. enum: [
  49. "check-space",
  50. "check-lowercase",
  51. "check-uppercase",
  52. ],
  53. },
  54. {
  55. type: "object",
  56. properties: {
  57. "ignore-words": {
  58. type: "array",
  59. items: {
  60. type: "string",
  61. },
  62. },
  63. "ignore-pattern": {
  64. type: "string",
  65. },
  66. },
  67. minProperties: 1,
  68. maxProperties: 1,
  69. },
  70. ],
  71. },
  72. minLength: 1,
  73. maxLength: 4,
  74. },
  75. optionExamples: [
  76. [true, "check-space", "check-uppercase"],
  77. [true, "check-lowercase", { "ignore-words": ["TODO", "HACK"] }],
  78. [true, "check-lowercase", { "ignore-pattern": "STD\\w{2,3}\\b" }],
  79. ],
  80. type: "style",
  81. typescriptOnly: false,
  82. hasFix: true,
  83. };
  84. /* tslint:enable:object-literal-sort-keys */
  85. Rule.LOWERCASE_FAILURE = "comment must start with lowercase letter";
  86. Rule.UPPERCASE_FAILURE = "comment must start with uppercase letter";
  87. Rule.LEADING_SPACE_FAILURE = "comment must start with a space";
  88. Rule.IGNORE_WORDS_FAILURE_FACTORY = function (words) { return " or the word(s): " + words.join(", "); };
  89. Rule.IGNORE_PATTERN_FAILURE_FACTORY = function (pattern) { return " or its start must match the regex pattern \"" + pattern + "\""; };
  90. return Rule;
  91. }(Lint.Rules.AbstractRule));
  92. exports.Rule = Rule;
  93. function parseOptions(options) {
  94. return tslib_1.__assign({ case: options.indexOf(OPTION_LOWERCASE) !== -1
  95. ? 1 /* Lower */
  96. : options.indexOf(OPTION_UPPERCASE) !== -1
  97. ? 2 /* Upper */
  98. : 0 /* None */, failureSuffix: "", space: options.indexOf(OPTION_SPACE) !== -1 }, composeExceptions(options[options.length - 1]));
  99. }
  100. function composeExceptions(option) {
  101. if (typeof option !== "object") {
  102. return undefined;
  103. }
  104. var ignorePattern = option["ignore-pattern"];
  105. if (ignorePattern !== undefined) {
  106. return {
  107. exceptions: new RegExp("^\\s*(" + ignorePattern + ")"),
  108. failureSuffix: Rule.IGNORE_PATTERN_FAILURE_FACTORY(ignorePattern),
  109. };
  110. }
  111. var ignoreWords = option["ignore-words"];
  112. if (ignoreWords !== undefined && ignoreWords.length !== 0) {
  113. return {
  114. exceptions: new RegExp("^\\s*(?:" + ignoreWords.map(function (word) { return utils_1.escapeRegExp(word.trim()); }).join("|") + ")\\b"),
  115. failureSuffix: Rule.IGNORE_WORDS_FAILURE_FACTORY(ignoreWords),
  116. };
  117. }
  118. return undefined;
  119. }
  120. function walk(ctx) {
  121. utils.forEachComment(ctx.sourceFile, function (fullText, _a) {
  122. var kind = _a.kind, pos = _a.pos, end = _a.end;
  123. var start = pos + 2;
  124. if (kind !== ts.SyntaxKind.SingleLineCommentTrivia ||
  125. // exclude empty comments
  126. start === end ||
  127. // exclude /// <reference path="...">
  128. fullText[start] === "/" && ctx.sourceFile.referencedFiles.some(function (ref) { return ref.pos >= pos && ref.end <= end; })) {
  129. return;
  130. }
  131. // skip all leading slashes
  132. while (fullText[start] === "/") {
  133. ++start;
  134. }
  135. if (start === end) {
  136. return;
  137. }
  138. var commentText = fullText.slice(start, end);
  139. // whitelist //#region and //#endregion and JetBrains IDEs' "//noinspection ..."
  140. if (/^(?:#(?:end)?region|noinspection\s)/.test(commentText)) {
  141. return;
  142. }
  143. if (ctx.options.space && commentText[0] !== " ") {
  144. ctx.addFailure(start, end, Rule.LEADING_SPACE_FAILURE, [Lint.Replacement.appendText(start, " ")]);
  145. }
  146. if (ctx.options.case === 0 /* None */ ||
  147. ctx.options.exceptions !== undefined && ctx.options.exceptions.test(commentText) ||
  148. enableDisableRules_1.ENABLE_DISABLE_REGEX.test(commentText)) {
  149. return;
  150. }
  151. // search for first non-space character to check if lower or upper
  152. var charPos = commentText.search(/\S/);
  153. if (charPos === -1) {
  154. return;
  155. }
  156. if (ctx.options.case === 1 /* Lower */) {
  157. if (!utils_1.isLowerCase(commentText[charPos])) {
  158. ctx.addFailure(start, end, Rule.LOWERCASE_FAILURE + ctx.options.failureSuffix);
  159. }
  160. }
  161. else if (!utils_1.isUpperCase(commentText[charPos])) {
  162. ctx.addFailure(start, end, Rule.UPPERCASE_FAILURE + ctx.options.failureSuffix);
  163. }
  164. });
  165. }
  166. var templateObject_1;