apply-disable-directives.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /**
  2. * @fileoverview A module that filters reported problems based on `eslint-disable` and `eslint-enable` comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const escapeRegExp = require("escape-string-regexp");
  7. /**
  8. * Compares the locations of two objects in a source file
  9. * @param {{line: number, column: number}} itemA The first object
  10. * @param {{line: number, column: number}} itemB The second object
  11. * @returns {number} A value less than 1 if itemA appears before itemB in the source file, greater than 1 if
  12. * itemA appears after itemB in the source file, or 0 if itemA and itemB have the same location.
  13. */
  14. function compareLocations(itemA, itemB) {
  15. return itemA.line - itemB.line || itemA.column - itemB.column;
  16. }
  17. /**
  18. * Groups a set of directives into sub-arrays by their parent comment.
  19. * @param {Directive[]} directives Unused directives to be removed.
  20. * @returns {Directive[][]} Directives grouped by their parent comment.
  21. */
  22. function groupByParentComment(directives) {
  23. const groups = new Map();
  24. for (const directive of directives) {
  25. const { unprocessedDirective: { parentComment } } = directive;
  26. if (groups.has(parentComment)) {
  27. groups.get(parentComment).push(directive);
  28. } else {
  29. groups.set(parentComment, [directive]);
  30. }
  31. }
  32. return [...groups.values()];
  33. }
  34. /**
  35. * Creates removal details for a set of directives within the same comment.
  36. * @param {Directive[]} directives Unused directives to be removed.
  37. * @param {Token} commentToken The backing Comment token.
  38. * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
  39. */
  40. function createIndividualDirectivesRemoval(directives, commentToken) {
  41. /*
  42. * `commentToken.value` starts right after `//` or `/*`.
  43. * All calculated offsets will be relative to this index.
  44. */
  45. const commentValueStart = commentToken.range[0] + "//".length;
  46. // Find where the list of rules starts. `\S+` matches with the directive name (e.g. `eslint-disable-line`)
  47. const listStartOffset = /^\s*\S+\s+/u.exec(commentToken.value)[0].length;
  48. /*
  49. * Get the list text without any surrounding whitespace. In order to preserve the original
  50. * formatting, we don't want to change that whitespace.
  51. *
  52. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  53. * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  54. */
  55. const listText = commentToken.value
  56. .slice(listStartOffset) // remove directive name and all whitespace before the list
  57. .split(/\s-{2,}\s/u)[0] // remove `-- comment`, if it exists
  58. .trimEnd(); // remove all whitespace after the list
  59. /*
  60. * We can assume that `listText` contains multiple elements.
  61. * Otherwise, this function wouldn't be called - if there is
  62. * only one rule in the list, then the whole comment must be removed.
  63. */
  64. return directives.map(directive => {
  65. const { ruleId } = directive;
  66. const regex = new RegExp(String.raw`(?:^|\s*,\s*)${escapeRegExp(ruleId)}(?:\s*,\s*|$)`, "u");
  67. const match = regex.exec(listText);
  68. const matchedText = match[0];
  69. const matchStartOffset = listStartOffset + match.index;
  70. const matchEndOffset = matchStartOffset + matchedText.length;
  71. const firstIndexOfComma = matchedText.indexOf(",");
  72. const lastIndexOfComma = matchedText.lastIndexOf(",");
  73. let removalStartOffset, removalEndOffset;
  74. if (firstIndexOfComma !== lastIndexOfComma) {
  75. /*
  76. * Since there are two commas, this must one of the elements in the middle of the list.
  77. * Matched range starts where the previous rule name ends, and ends where the next rule name starts.
  78. *
  79. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  80. * ^^^^^^^^^^^^^^
  81. *
  82. * We want to remove only the content between the two commas, and also one of the commas.
  83. *
  84. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  85. * ^^^^^^^^^^^
  86. */
  87. removalStartOffset = matchStartOffset + firstIndexOfComma;
  88. removalEndOffset = matchStartOffset + lastIndexOfComma;
  89. } else {
  90. /*
  91. * This is either the first element or the last element.
  92. *
  93. * If this is the first element, matched range starts where the first rule name starts
  94. * and ends where the second rule name starts. This is exactly the range we want
  95. * to remove so that the second rule name will start where the first one was starting
  96. * and thus preserve the original formatting.
  97. *
  98. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  99. * ^^^^^^^^^^^
  100. *
  101. * Similarly, if this is the last element, we've already matched the range we want to
  102. * remove. The previous rule name will end where the last one was ending, relative
  103. * to the content on the right side.
  104. *
  105. * // eslint-disable-line rule-one , rule-two , rule-three -- comment
  106. * ^^^^^^^^^^^^^
  107. */
  108. removalStartOffset = matchStartOffset;
  109. removalEndOffset = matchEndOffset;
  110. }
  111. return {
  112. description: `'${ruleId}'`,
  113. fix: {
  114. range: [
  115. commentValueStart + removalStartOffset,
  116. commentValueStart + removalEndOffset
  117. ],
  118. text: ""
  119. },
  120. unprocessedDirective: directive.unprocessedDirective
  121. };
  122. });
  123. }
  124. /**
  125. * Creates a description of deleting an entire unused disable comment.
  126. * @param {Directive[]} directives Unused directives to be removed.
  127. * @param {Token} commentToken The backing Comment token.
  128. * @returns {{ description, fix, unprocessedDirective }} Details for later creation of an output Problem.
  129. */
  130. function createCommentRemoval(directives, commentToken) {
  131. const { range } = commentToken;
  132. const ruleIds = directives.filter(directive => directive.ruleId).map(directive => `'${directive.ruleId}'`);
  133. return {
  134. description: ruleIds.length <= 2
  135. ? ruleIds.join(" or ")
  136. : `${ruleIds.slice(0, ruleIds.length - 1).join(", ")}, or ${ruleIds[ruleIds.length - 1]}`,
  137. fix: {
  138. range,
  139. text: " "
  140. },
  141. unprocessedDirective: directives[0].unprocessedDirective
  142. };
  143. }
  144. /**
  145. * Parses details from directives to create output Problems.
  146. * @param {Directive[]} allDirectives Unused directives to be removed.
  147. * @returns {{ description, fix, unprocessedDirective }[]} Details for later creation of output Problems.
  148. */
  149. function processUnusedDisableDirectives(allDirectives) {
  150. const directiveGroups = groupByParentComment(allDirectives);
  151. return directiveGroups.flatMap(
  152. directives => {
  153. const { parentComment } = directives[0].unprocessedDirective;
  154. const remainingRuleIds = new Set(parentComment.ruleIds);
  155. for (const directive of directives) {
  156. remainingRuleIds.delete(directive.ruleId);
  157. }
  158. return remainingRuleIds.size
  159. ? createIndividualDirectivesRemoval(directives, parentComment.commentToken)
  160. : [createCommentRemoval(directives, parentComment.commentToken)];
  161. }
  162. );
  163. }
  164. /**
  165. * This is the same as the exported function, except that it
  166. * doesn't handle disable-line and disable-next-line directives, and it always reports unused
  167. * disable directives.
  168. * @param {Object} options options for applying directives. This is the same as the options
  169. * for the exported function, except that `reportUnusedDisableDirectives` is not supported
  170. * (this function always reports unused disable directives).
  171. * @returns {{problems: Problem[], unusedDisableDirectives: Problem[]}} An object with a list
  172. * of problems (including suppressed ones) and unused eslint-disable directives
  173. */
  174. function applyDirectives(options) {
  175. const problems = [];
  176. const usedDisableDirectives = new Set();
  177. for (const problem of options.problems) {
  178. let disableDirectivesForProblem = [];
  179. let nextDirectiveIndex = 0;
  180. while (
  181. nextDirectiveIndex < options.directives.length &&
  182. compareLocations(options.directives[nextDirectiveIndex], problem) <= 0
  183. ) {
  184. const directive = options.directives[nextDirectiveIndex++];
  185. if (directive.ruleId === null || directive.ruleId === problem.ruleId) {
  186. switch (directive.type) {
  187. case "disable":
  188. disableDirectivesForProblem.push(directive);
  189. break;
  190. case "enable":
  191. disableDirectivesForProblem = [];
  192. break;
  193. // no default
  194. }
  195. }
  196. }
  197. if (disableDirectivesForProblem.length > 0) {
  198. const suppressions = disableDirectivesForProblem.map(directive => ({
  199. kind: "directive",
  200. justification: directive.unprocessedDirective.justification
  201. }));
  202. if (problem.suppressions) {
  203. problem.suppressions = problem.suppressions.concat(suppressions);
  204. } else {
  205. problem.suppressions = suppressions;
  206. usedDisableDirectives.add(disableDirectivesForProblem[disableDirectivesForProblem.length - 1]);
  207. }
  208. }
  209. problems.push(problem);
  210. }
  211. const unusedDisableDirectivesToReport = options.directives
  212. .filter(directive => directive.type === "disable" && !usedDisableDirectives.has(directive));
  213. const processed = processUnusedDisableDirectives(unusedDisableDirectivesToReport);
  214. const unusedDisableDirectives = processed
  215. .map(({ description, fix, unprocessedDirective }) => {
  216. const { parentComment, type, line, column } = unprocessedDirective;
  217. return {
  218. ruleId: null,
  219. message: description
  220. ? `Unused eslint-disable directive (no problems were reported from ${description}).`
  221. : "Unused eslint-disable directive (no problems were reported).",
  222. line: type === "disable-next-line" ? parentComment.commentToken.loc.start.line : line,
  223. column: type === "disable-next-line" ? parentComment.commentToken.loc.start.column + 1 : column,
  224. severity: options.reportUnusedDisableDirectives === "warn" ? 1 : 2,
  225. nodeType: null,
  226. ...options.disableFixes ? {} : { fix }
  227. };
  228. });
  229. return { problems, unusedDisableDirectives };
  230. }
  231. /**
  232. * Given a list of directive comments (i.e. metadata about eslint-disable and eslint-enable comments) and a list
  233. * of reported problems, adds the suppression information to the problems.
  234. * @param {Object} options Information about directives and problems
  235. * @param {{
  236. * type: ("disable"|"enable"|"disable-line"|"disable-next-line"),
  237. * ruleId: (string|null),
  238. * line: number,
  239. * column: number,
  240. * justification: string
  241. * }} options.directives Directive comments found in the file, with one-based columns.
  242. * Two directive comments can only have the same location if they also have the same type (e.g. a single eslint-disable
  243. * comment for two different rules is represented as two directives).
  244. * @param {{ruleId: (string|null), line: number, column: number}[]} options.problems
  245. * A list of problems reported by rules, sorted by increasing location in the file, with one-based columns.
  246. * @param {"off" | "warn" | "error"} options.reportUnusedDisableDirectives If `"warn"` or `"error"`, adds additional problems for unused directives
  247. * @param {boolean} options.disableFixes If true, it doesn't make `fix` properties.
  248. * @returns {{ruleId: (string|null), line: number, column: number, suppressions?: {kind: string, justification: string}}[]}
  249. * An object with a list of reported problems, the suppressed of which contain the suppression information.
  250. */
  251. module.exports = ({ directives, disableFixes, problems, reportUnusedDisableDirectives = "off" }) => {
  252. const blockDirectives = directives
  253. .filter(directive => directive.type === "disable" || directive.type === "enable")
  254. .map(directive => Object.assign({}, directive, { unprocessedDirective: directive }))
  255. .sort(compareLocations);
  256. const lineDirectives = directives.flatMap(directive => {
  257. switch (directive.type) {
  258. case "disable":
  259. case "enable":
  260. return [];
  261. case "disable-line":
  262. return [
  263. { type: "disable", line: directive.line, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
  264. { type: "enable", line: directive.line + 1, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
  265. ];
  266. case "disable-next-line":
  267. return [
  268. { type: "disable", line: directive.line + 1, column: 1, ruleId: directive.ruleId, unprocessedDirective: directive },
  269. { type: "enable", line: directive.line + 2, column: 0, ruleId: directive.ruleId, unprocessedDirective: directive }
  270. ];
  271. default:
  272. throw new TypeError(`Unrecognized directive type '${directive.type}'`);
  273. }
  274. }).sort(compareLocations);
  275. const blockDirectivesResult = applyDirectives({
  276. problems,
  277. directives: blockDirectives,
  278. disableFixes,
  279. reportUnusedDisableDirectives
  280. });
  281. const lineDirectivesResult = applyDirectives({
  282. problems: blockDirectivesResult.problems,
  283. directives: lineDirectives,
  284. disableFixes,
  285. reportUnusedDisableDirectives
  286. });
  287. return reportUnusedDisableDirectives !== "off"
  288. ? lineDirectivesResult.problems
  289. .concat(blockDirectivesResult.unusedDisableDirectives)
  290. .concat(lineDirectivesResult.unusedDisableDirectives)
  291. .sort(compareLocations)
  292. : lineDirectivesResult.problems;
  293. };