no-warning-comments.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /**
  2. * @fileoverview Rule that warns about used warning comments
  3. * @author Alexander Schmidt <https://github.com/lxanders>
  4. */
  5. "use strict";
  6. const escapeRegExp = require("escape-string-regexp");
  7. const astUtils = require("./utils/ast-utils");
  8. const CHAR_LIMIT = 40;
  9. //------------------------------------------------------------------------------
  10. // Rule Definition
  11. //------------------------------------------------------------------------------
  12. /** @type {import('../types').Rule.RuleModule} */
  13. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. defaultOptions: [
  17. {
  18. location: "start",
  19. terms: ["todo", "fixme", "xxx"],
  20. },
  21. ],
  22. docs: {
  23. description: "Disallow specified warning terms in comments",
  24. recommended: false,
  25. frozen: true,
  26. url: "https://eslint.org/docs/latest/rules/no-warning-comments",
  27. },
  28. schema: [
  29. {
  30. type: "object",
  31. properties: {
  32. terms: {
  33. type: "array",
  34. items: {
  35. type: "string",
  36. },
  37. },
  38. location: {
  39. enum: ["start", "anywhere"],
  40. },
  41. decoration: {
  42. type: "array",
  43. items: {
  44. type: "string",
  45. pattern: "^\\S$",
  46. },
  47. minItems: 1,
  48. uniqueItems: true,
  49. },
  50. },
  51. additionalProperties: false,
  52. },
  53. ],
  54. messages: {
  55. unexpectedComment:
  56. "Unexpected '{{matchedTerm}}' comment: '{{comment}}'.",
  57. },
  58. },
  59. create(context) {
  60. const sourceCode = context.sourceCode;
  61. const [{ decoration, location, terms: warningTerms }] = context.options;
  62. const escapedDecoration = escapeRegExp(
  63. decoration ? decoration.join("") : "",
  64. );
  65. const selfConfigRegEx = /\bno-warning-comments\b/u;
  66. /**
  67. * Convert a warning term into a RegExp which will match a comment containing that whole word in the specified
  68. * location ("start" or "anywhere"). If the term starts or ends with non word characters, then the match will not
  69. * require word boundaries on that side.
  70. * @param {string} term A term to convert to a RegExp
  71. * @returns {RegExp} The term converted to a RegExp
  72. */
  73. function convertToRegExp(term) {
  74. const escaped = escapeRegExp(term);
  75. /*
  76. * When matching at the start, ignore leading whitespace, and
  77. * there's no need to worry about word boundaries.
  78. *
  79. * These expressions for the prefix and suffix are designed as follows:
  80. * ^ handles any terms at the beginning of a comment.
  81. * e.g. terms ["TODO"] matches `//TODO something`
  82. * $ handles any terms at the end of a comment
  83. * e.g. terms ["TODO"] matches `// something TODO`
  84. * \b handles terms preceded/followed by word boundary
  85. * e.g. terms: ["!FIX", "FIX!"] matches `// FIX!something` or `// something!FIX`
  86. * terms: ["FIX"] matches `// FIX!` or `// !FIX`, but not `// fixed or affix`
  87. *
  88. * For location start:
  89. * [\s]* handles optional leading spaces
  90. * e.g. terms ["TODO"] matches `// TODO something`
  91. * [\s\*]* (where "\*" is the escaped string of decoration)
  92. * handles optional leading spaces or decoration characters (for "start" location only)
  93. * e.g. terms ["TODO"] matches `/**** TODO something ... `
  94. */
  95. const wordBoundary = "\\b";
  96. let prefix = "";
  97. if (location === "start") {
  98. prefix = `^[\\s${escapedDecoration}]*`;
  99. } else if (/^\w/u.test(term)) {
  100. prefix = wordBoundary;
  101. }
  102. const suffix = /\w$/u.test(term) ? wordBoundary : "";
  103. const flags = "iu"; // Case-insensitive with Unicode case folding.
  104. /*
  105. * For location "start", the typical regex is:
  106. * /^[\s]*ESCAPED_TERM\b/iu.
  107. * Or if decoration characters are specified (e.g. "*"), then any of
  108. * those characters may appear in any order at the start:
  109. * /^[\s\*]*ESCAPED_TERM\b/iu.
  110. *
  111. * For location "anywhere" the typical regex is
  112. * /\bESCAPED_TERM\b/iu
  113. *
  114. * If it starts or ends with non-word character, the prefix and suffix are empty, respectively.
  115. */
  116. return new RegExp(`${prefix}${escaped}${suffix}`, flags);
  117. }
  118. const warningRegExps = warningTerms.map(convertToRegExp);
  119. /**
  120. * Checks the specified comment for matches of the configured warning terms and returns the matches.
  121. * @param {string} comment The comment which is checked.
  122. * @returns {Array} All matched warning terms for this comment.
  123. */
  124. function commentContainsWarningTerm(comment) {
  125. const matches = [];
  126. warningRegExps.forEach((regex, index) => {
  127. if (regex.test(comment)) {
  128. matches.push(warningTerms[index]);
  129. }
  130. });
  131. return matches;
  132. }
  133. /**
  134. * Checks the specified node for matching warning comments and reports them.
  135. * @param {ASTNode} node The AST node being checked.
  136. * @returns {void} undefined.
  137. */
  138. function checkComment(node) {
  139. const comment = node.value;
  140. if (
  141. astUtils.isDirectiveComment(node) &&
  142. selfConfigRegEx.test(comment)
  143. ) {
  144. return;
  145. }
  146. const matches = commentContainsWarningTerm(comment);
  147. matches.forEach(matchedTerm => {
  148. let commentToDisplay = "";
  149. let truncated = false;
  150. for (const c of comment.trim().split(/\s+/u)) {
  151. const tmp = commentToDisplay
  152. ? `${commentToDisplay} ${c}`
  153. : c;
  154. if (tmp.length <= CHAR_LIMIT) {
  155. commentToDisplay = tmp;
  156. } else {
  157. truncated = true;
  158. break;
  159. }
  160. }
  161. context.report({
  162. node,
  163. messageId: "unexpectedComment",
  164. data: {
  165. matchedTerm,
  166. comment: `${commentToDisplay}${truncated ? "..." : ""}`,
  167. },
  168. });
  169. });
  170. }
  171. return {
  172. Program() {
  173. const comments = sourceCode.getAllComments();
  174. comments
  175. .filter(token => token.type !== "Shebang")
  176. .forEach(checkComment);
  177. },
  178. };
  179. },
  180. };