no-warning-comments.js 7.1 KB

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