commentFormatRule.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. };
  83. /* tslint:enable:object-literal-sort-keys */
  84. Rule.LOWERCASE_FAILURE = "comment must start with lowercase letter";
  85. Rule.UPPERCASE_FAILURE = "comment must start with uppercase letter";
  86. Rule.LEADING_SPACE_FAILURE = "comment must start with a space";
  87. Rule.IGNORE_WORDS_FAILURE_FACTORY = function (words) { return " or the word(s): " + words.join(", "); };
  88. Rule.IGNORE_PATTERN_FAILURE_FACTORY = function (pattern) { return " or its start must match the regex pattern \"" + pattern + "\""; };
  89. return Rule;
  90. }(Lint.Rules.AbstractRule));
  91. exports.Rule = Rule;
  92. function parseOptions(options) {
  93. return tslib_1.__assign({ case: options.indexOf(OPTION_LOWERCASE) !== -1
  94. ? 1 /* Lower */
  95. : options.indexOf(OPTION_UPPERCASE) !== -1
  96. ? 2 /* Upper */
  97. : 0 /* None */, failureSuffix: "", space: options.indexOf(OPTION_SPACE) !== -1 }, composeExceptions(options[options.length - 1]));
  98. }
  99. function composeExceptions(option) {
  100. if (typeof option !== "object") {
  101. return undefined;
  102. }
  103. var ignorePattern = option["ignore-pattern"];
  104. if (ignorePattern !== undefined) {
  105. return {
  106. exceptions: new RegExp("^\\s*(" + ignorePattern + ")"),
  107. failureSuffix: Rule.IGNORE_PATTERN_FAILURE_FACTORY(ignorePattern),
  108. };
  109. }
  110. var ignoreWords = option["ignore-words"];
  111. if (ignoreWords !== undefined && ignoreWords.length !== 0) {
  112. return {
  113. exceptions: new RegExp("^\\s*(?:" + ignoreWords.map(function (word) { return utils_1.escapeRegExp(word.trim()); }).join("|") + ")\\b"),
  114. failureSuffix: Rule.IGNORE_WORDS_FAILURE_FACTORY(ignoreWords),
  115. };
  116. }
  117. return undefined;
  118. }
  119. function walk(ctx) {
  120. utils.forEachComment(ctx.sourceFile, function (fullText, _a) {
  121. var kind = _a.kind, pos = _a.pos, end = _a.end;
  122. var start = pos + 2;
  123. if (kind !== ts.SyntaxKind.SingleLineCommentTrivia ||
  124. // exclude empty comments
  125. start === end ||
  126. // exclude /// <reference path="...">
  127. fullText[start] === "/" && ctx.sourceFile.referencedFiles.some(function (ref) { return ref.pos >= pos && ref.end <= end; })) {
  128. return;
  129. }
  130. // skip all leading slashes
  131. while (fullText[start] === "/") {
  132. ++start;
  133. }
  134. if (start === end) {
  135. return;
  136. }
  137. var commentText = fullText.slice(start, end);
  138. // whitelist //#region and //#endregion and JetBrains IDEs' "//noinspection ..."
  139. if (/^(?:#(?:end)?region|noinspection\s)/.test(commentText)) {
  140. return;
  141. }
  142. if (ctx.options.space && commentText[0] !== " ") {
  143. ctx.addFailure(start, end, Rule.LEADING_SPACE_FAILURE);
  144. }
  145. if (ctx.options.case === 0 /* None */ ||
  146. ctx.options.exceptions !== undefined && ctx.options.exceptions.test(commentText) ||
  147. enableDisableRules_1.ENABLE_DISABLE_REGEX.test(commentText)) {
  148. return;
  149. }
  150. // search for first non-space character to check if lower or upper
  151. var charPos = commentText.search(/\S/);
  152. if (charPos === -1) {
  153. return;
  154. }
  155. if (ctx.options.case === 1 /* Lower */) {
  156. if (!utils_1.isLowerCase(commentText[charPos])) {
  157. ctx.addFailure(start, end, Rule.LOWERCASE_FAILURE + ctx.options.failureSuffix);
  158. }
  159. }
  160. else if (!utils_1.isUpperCase(commentText[charPos])) {
  161. ctx.addFailure(start, end, Rule.UPPERCASE_FAILURE + ctx.options.failureSuffix);
  162. }
  163. });
  164. }
  165. var templateObject_1;