suppressionsService.cjs 8.8 KB

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