suppressionsService.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * This file is based on ESLint's suppressions-service.js
  3. * https://github.com/eslint/eslint/blob/v9.26.0/lib/services/suppressions-service.js
  4. *
  5. * Copyright OpenJS Foundation and other contributors, https://openjsf.org/
  6. * Released under the MIT License:
  7. * https://github.com/eslint/eslint/blob/main/LICENSE
  8. */
  9. import fs from 'node:fs';
  10. import path from 'node:path';
  11. import getRelativePath from './getRelativePath.mjs';
  12. import isPathNotFoundError from './isPathNotFoundError.mjs';
  13. /** @import {LintResult, Warning, SuppressedProblems} from 'stylelint' */
  14. /**
  15. * Manages the suppressed problems.
  16. */
  17. export class SuppressionsService {
  18. filePath = '';
  19. cwd = '';
  20. /**
  21. * Creates a new instance of SuppressionsService.
  22. * @param {Object} options The options.
  23. * @param {string} options.filePath The path to the suppressions file.
  24. * @param {string} options.cwd The current working directory.
  25. */
  26. constructor({ filePath, cwd }) {
  27. this.filePath = filePath;
  28. this.cwd = cwd;
  29. }
  30. /**
  31. * Updates the suppressions file based on the current problems and the provided rules.
  32. * If no rules are provided, all problems are suppressed.
  33. * This method now automatically prunes suppressions that no longer exist.
  34. * @param {LintResult[] | undefined} results The lint results.
  35. * @param {string[] | undefined} rules The rules to suppress.
  36. * @returns {Promise<void>}
  37. */
  38. async suppress(results, rules) {
  39. if (results === undefined) return;
  40. const suppressions = await this.load();
  41. for (const result of results) {
  42. const source = result.source;
  43. if (!source) continue;
  44. const relativePath = path.isAbsolute(source) ? getRelativePath(this.cwd, source) : source;
  45. const problemsByRule = SuppressionsService.countProblemsByRule(result.warnings);
  46. for (const [rule, ruleData] of problemsByRule) {
  47. if (rules && !rules.includes(rule)) continue;
  48. if (!suppressions.has(relativePath)) {
  49. suppressions.set(relativePath, new Map());
  50. }
  51. const fileRules = suppressions.get(relativePath);
  52. if (!fileRules) continue;
  53. fileRules.set(rule, ruleData);
  54. }
  55. }
  56. const { unused } = this.applySuppressions(results, suppressions);
  57. const prunedSuppressions = this.#prune(unused, suppressions);
  58. return this.#save(prunedSuppressions);
  59. }
  60. /**
  61. * Removes old, unused suppressions for problems that do not occur anymore.
  62. * @param {SuppressedProblems} unused The unused suppressions.
  63. * @param {SuppressedProblems} suppressions The suppressions.
  64. * @returns {SuppressedProblems} The pruned suppressions.
  65. */
  66. #prune(unused, suppressions) {
  67. for (const [file, rules] of unused) {
  68. if (!suppressions.has(file)) continue;
  69. for (const [rule, ruleData] of rules) {
  70. const fileRules = suppressions.get(file);
  71. if (!fileRules) continue;
  72. const suppressionData = fileRules.get(rule);
  73. if (!suppressionData) continue;
  74. const suppressionsCount = suppressionData.count;
  75. const problemsCount = ruleData.count;
  76. if (suppressionsCount === problemsCount) {
  77. // Remove unused rules
  78. fileRules.delete(rule);
  79. } else {
  80. // Update the count to match the new number of problems
  81. const ruleDataForUpdate = fileRules.get(rule);
  82. if (ruleDataForUpdate) {
  83. ruleDataForUpdate.count -= problemsCount;
  84. }
  85. }
  86. }
  87. // Cleanup files with no rules
  88. const fileRulesForCleanup = suppressions.get(file);
  89. if (fileRulesForCleanup && fileRulesForCleanup.size === 0) {
  90. suppressions.delete(file);
  91. }
  92. }
  93. return suppressions;
  94. }
  95. /**
  96. * Checks the provided suppressions against the lint results.
  97. *
  98. * For each file, counts the number of problems per rule.
  99. * For each rule in each file, compares the number of problems against the counter from the suppressions file.
  100. * If the number of problems is less or equal to the counter, warnings are ignored.
  101. * Otherwise, all problems are reported as usual.
  102. * @param {LintResult[]} results The lint results.
  103. * @param {SuppressedProblems} suppressions The suppressions.
  104. * @returns {{
  105. * results: LintResult[],
  106. * unused: SuppressedProblems
  107. * }} The updated results and the unused suppressions.
  108. */
  109. applySuppressions(results, suppressions) {
  110. /**
  111. * We copy the results to avoid modifying the original objects
  112. * We remove only result warnings that are matched and hence suppressed
  113. * We leave the rest untouched to minimize the risk of losing parts of the original data
  114. */
  115. const clonedResults = results.map((r) => {
  116. return {
  117. ...r,
  118. warnings: structuredClone(r.warnings),
  119. };
  120. });
  121. /** @type {SuppressedProblems} */
  122. const unused = new Map();
  123. for (const result of clonedResults) {
  124. const source = result.source;
  125. if (!source) continue;
  126. const relativePath = path.isAbsolute(source) ? getRelativePath(this.cwd, source) : source;
  127. if (!suppressions.has(relativePath)) continue;
  128. const problemsByRule = SuppressionsService.countProblemsByRule(result.warnings);
  129. for (const [rule, ruleStats] of problemsByRule) {
  130. const fileRules = suppressions.get(relativePath);
  131. if (!fileRules) continue;
  132. const ruleData = fileRules.get(rule);
  133. if (!ruleData) continue;
  134. const suppressionsCount = ruleData.count;
  135. if (!ruleStats) continue;
  136. const problemsCount = ruleStats.count;
  137. // Suppress warnings if the number of problems is less or equal to the suppressions count
  138. if (problemsCount <= suppressionsCount) {
  139. result.warnings = result.warnings.filter((warning) => warning.rule !== rule);
  140. }
  141. // Update the count to match the new number of problems, otherwise remove the rule entirely
  142. if (problemsCount < suppressionsCount) {
  143. if (!unused.has(relativePath)) {
  144. unused.set(relativePath, new Map());
  145. }
  146. const unusedFileRules = unused.get(relativePath);
  147. if (unusedFileRules && !unusedFileRules.has(rule)) {
  148. unusedFileRules.set(rule, { count: 0 });
  149. }
  150. if (unusedFileRules) {
  151. const unusedRuleData = unusedFileRules.get(rule);
  152. if (unusedRuleData) {
  153. unusedRuleData.count = suppressionsCount - problemsCount;
  154. }
  155. }
  156. }
  157. }
  158. // Mark as unused all the suppressions that were not matched against a rule
  159. const fileRulesForUnused = suppressions.get(relativePath);
  160. if (fileRulesForUnused) {
  161. for (const [rule, savedEntry] of fileRulesForUnused) {
  162. if (problemsByRule.has(rule)) continue;
  163. if (!savedEntry) continue;
  164. if (!unused.has(relativePath)) {
  165. unused.set(relativePath, new Map());
  166. }
  167. const unusedFileRulesForSet = unused.get(relativePath);
  168. if (!unusedFileRulesForSet) continue;
  169. unusedFileRulesForSet.set(rule, savedEntry);
  170. }
  171. }
  172. }
  173. return {
  174. results: clonedResults,
  175. unused,
  176. };
  177. }
  178. /**
  179. * Loads the suppressions file.
  180. * @throws {Error} If the suppressions file cannot be parsed.
  181. * @returns {Promise<SuppressedProblems>} The suppressions.
  182. */
  183. async load() {
  184. try {
  185. const data = await fs.promises.readFile(this.filePath, 'utf8');
  186. const parsed = JSON.parse(data);
  187. // Convert Object to Map
  188. const suppressions = new Map();
  189. for (const [filePath, rules] of Object.entries(parsed)) {
  190. const rulesMap = new Map();
  191. for (const [ruleName, ruleData] of Object.entries(rules)) {
  192. rulesMap.set(ruleName, ruleData);
  193. }
  194. suppressions.set(filePath, rulesMap);
  195. }
  196. return suppressions;
  197. } catch (err) {
  198. if (isPathNotFoundError(err)) {
  199. return new Map();
  200. }
  201. throw new Error(`Failed to parse suppressions file at ${this.filePath}`);
  202. }
  203. }
  204. /**
  205. * Updates the suppressions file.
  206. * @param {SuppressedProblems} suppressions The suppressions to save.
  207. * @returns {Promise<void>}
  208. */
  209. #save(suppressions) {
  210. // Convert Map to Object for JSON serialization
  211. /** @type {Record<string, Record<string, {count: number}>>} */
  212. const obj = {};
  213. for (const [filePath, rulesMap] of suppressions) {
  214. obj[filePath] = {};
  215. for (const [ruleName, ruleData] of rulesMap) {
  216. obj[filePath][ruleName] = ruleData;
  217. }
  218. }
  219. return fs.promises.writeFile(this.filePath, `${JSON.stringify(obj, null, 2)}\n`);
  220. }
  221. /**
  222. * Counts the problems by rule, ignoring warnings.
  223. * @param {Warning[]} warnings The warnings to count.
  224. * @returns {Map<string, {count: number}>} The number of problems by rule.
  225. */
  226. static countProblemsByRule(warnings) {
  227. /** @type {Map<string, {count: number}>} */
  228. const totals = new Map();
  229. for (const warning of warnings) {
  230. const rule = warning.rule;
  231. if (warning.severity !== 'error' || !rule) continue;
  232. if (!totals.has(rule)) {
  233. totals.set(rule, { count: 0 });
  234. }
  235. const ruleData = totals.get(rule);
  236. if (ruleData) {
  237. ruleData.count += 1;
  238. }
  239. }
  240. return totals;
  241. }
  242. }