assignDisabledRanges.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. 'use strict';
  2. const isStandardSyntaxComment = require('./utils/isStandardSyntaxComment');
  3. const {
  4. DISABLE_COMMAND,
  5. DISABLE_LINE_COMMAND,
  6. DISABLE_NEXT_LINE_COMMAND,
  7. ENABLE_COMMAND,
  8. extractConfigurationComment,
  9. getConfigurationComment,
  10. isConfigurationComment,
  11. } = require('./utils/configurationComment');
  12. const { assert, assertNumber, assertString } = require('./utils/validateTypes');
  13. const ALL_RULES = 'all';
  14. /** @typedef {import('postcss').Comment} PostcssComment */
  15. /** @typedef {import('postcss').Root} PostcssRoot */
  16. /** @typedef {import('postcss').Document} PostcssDocument */
  17. /** @typedef {import('stylelint').PostcssResult} PostcssResult */
  18. /** @typedef {import('stylelint').DisabledRangeObject} DisabledRangeObject */
  19. /** @typedef {import('stylelint').DisabledRange} DisabledRange */
  20. /**
  21. * @param {PostcssComment} comment
  22. * @param {number} start
  23. * @param {boolean} strictStart
  24. * @param {string|undefined} description
  25. * @param {number} [end]
  26. * @param {boolean} [strictEnd]
  27. * @returns {DisabledRange}
  28. */
  29. function createDisableRange(comment, start, strictStart, description, end, strictEnd) {
  30. return {
  31. comment,
  32. start,
  33. end: end || undefined,
  34. strictStart,
  35. strictEnd: typeof strictEnd === 'boolean' ? strictEnd : undefined,
  36. description,
  37. };
  38. }
  39. /**
  40. * Run it like a PostCSS plugin
  41. * @param {PostcssRoot | PostcssDocument} root
  42. * @param {PostcssResult} result
  43. * @returns {PostcssResult}
  44. */
  45. module.exports = function assignDisabledRanges(root, result) {
  46. result.stylelint = result.stylelint || {
  47. disabledRanges: {},
  48. ruleSeverities: {},
  49. customMessages: {},
  50. ruleMetadata: {},
  51. };
  52. /**
  53. * Most of the functions below work via side effects mutating this object
  54. * @type {DisabledRangeObject & { all: DisabledRange[] }}
  55. */
  56. const disabledRanges = {
  57. [ALL_RULES]: [],
  58. };
  59. result.stylelint.disabledRanges = disabledRanges;
  60. // Work around postcss/postcss-scss#109 by merging adjacent `//` comments
  61. // into a single node before passing to `checkComment`.
  62. /** @type {PostcssComment?} */
  63. let inlineEnd;
  64. const configurationComment = result.stylelint.config?.configurationComment;
  65. root.walkComments((comment) => {
  66. if (inlineEnd) {
  67. // Ignore comments already processed by grouping with a previous one.
  68. if (inlineEnd === comment) inlineEnd = null;
  69. return;
  70. }
  71. const nextComment = comment.next();
  72. // If any of these conditions are not met, do not merge comments.
  73. if (
  74. !(
  75. !isStandardSyntaxComment(comment) &&
  76. isConfigurationComment(comment, configurationComment) &&
  77. nextComment &&
  78. nextComment.type === 'comment' &&
  79. (comment.text.includes('--') || nextComment.text.startsWith('--'))
  80. )
  81. ) {
  82. checkComment(comment);
  83. return;
  84. }
  85. let lastLine = (comment.source && comment.source.end && comment.source.end.line) || 0;
  86. const fullComment = comment.clone();
  87. let current = nextComment;
  88. while (
  89. !isStandardSyntaxComment(current) &&
  90. !isConfigurationComment(current, configurationComment)
  91. ) {
  92. const currentLine = (current.source && current.source.end && current.source.end.line) || 0;
  93. if (lastLine + 1 !== currentLine) break;
  94. fullComment.text += `\n${current.text}`;
  95. if (fullComment.source && current.source) {
  96. fullComment.source.end = current.source.end;
  97. }
  98. inlineEnd = current;
  99. const next = current.next();
  100. if (!next || next.type !== 'comment') break;
  101. current = next;
  102. lastLine = currentLine;
  103. }
  104. checkComment(fullComment);
  105. });
  106. return result;
  107. /**
  108. * @param {PostcssComment} comment
  109. */
  110. function processDisableLineCommand(comment) {
  111. if (comment.source && comment.source.start) {
  112. const line = comment.source.start.line;
  113. const description = getDescription(comment.text);
  114. for (const ruleName of getCommandRules(DISABLE_LINE_COMMAND, comment.text)) {
  115. disableLine(comment, line, ruleName, description);
  116. }
  117. }
  118. }
  119. /**
  120. * @param {PostcssComment} comment
  121. */
  122. function processDisableNextLineCommand(comment) {
  123. if (comment.source && comment.source.end) {
  124. const line = comment.source.end.line;
  125. const description = getDescription(comment.text);
  126. for (const ruleName of getCommandRules(DISABLE_NEXT_LINE_COMMAND, comment.text)) {
  127. disableLine(comment, line + 1, ruleName, description);
  128. }
  129. }
  130. }
  131. /**
  132. * @param {PostcssComment} comment
  133. * @param {number} line
  134. * @param {string} ruleName
  135. * @param {string|undefined} description
  136. */
  137. function disableLine(comment, line, ruleName, description) {
  138. if (ruleIsDisabled(ALL_RULES)) {
  139. throw comment.error('All rules have already been disabled', {
  140. plugin: 'stylelint',
  141. });
  142. }
  143. if (ruleName === ALL_RULES) {
  144. for (const disabledRuleName of Object.keys(disabledRanges)) {
  145. if (ruleIsDisabled(disabledRuleName)) continue;
  146. const strict = disabledRuleName === ALL_RULES;
  147. startDisabledRange(comment, line, disabledRuleName, strict, description);
  148. endDisabledRange(line, disabledRuleName, strict);
  149. }
  150. } else {
  151. if (ruleIsDisabled(ruleName)) {
  152. throw comment.error(`"${ruleName}" has already been disabled`, {
  153. plugin: 'stylelint',
  154. });
  155. }
  156. startDisabledRange(comment, line, ruleName, true, description);
  157. endDisabledRange(line, ruleName, true);
  158. }
  159. }
  160. /**
  161. * @param {PostcssComment} comment
  162. */
  163. function processDisableCommand(comment) {
  164. const description = getDescription(comment.text);
  165. for (const ruleToDisable of getCommandRules(DISABLE_COMMAND, comment.text)) {
  166. const isAllRules = ruleToDisable === ALL_RULES;
  167. if (ruleIsDisabled(ruleToDisable)) {
  168. throw comment.error(
  169. isAllRules
  170. ? 'All rules have already been disabled'
  171. : `"${ruleToDisable}" has already been disabled`,
  172. {
  173. plugin: 'stylelint',
  174. },
  175. );
  176. }
  177. if (comment.source && comment.source.start) {
  178. const line = comment.source.start.line;
  179. if (isAllRules) {
  180. for (const ruleName of Object.keys(disabledRanges)) {
  181. startDisabledRange(comment, line, ruleName, ruleName === ALL_RULES, description);
  182. }
  183. } else {
  184. startDisabledRange(comment, line, ruleToDisable, true, description);
  185. }
  186. }
  187. }
  188. }
  189. /**
  190. * @param {PostcssComment} comment
  191. */
  192. function processEnableCommand(comment) {
  193. for (const ruleToEnable of getCommandRules(ENABLE_COMMAND, comment.text)) {
  194. // need fallback if endLine will be undefined
  195. const endLine = comment.source && comment.source.end && comment.source.end.line;
  196. assertNumber(endLine);
  197. if (ruleToEnable === ALL_RULES) {
  198. if (
  199. Object.values(disabledRanges).every((ranges) => {
  200. if (ranges.length === 0) return true;
  201. const lastRange = ranges[ranges.length - 1];
  202. return lastRange && typeof lastRange.end === 'number';
  203. })
  204. ) {
  205. throw comment.error('No rules have been disabled', {
  206. plugin: 'stylelint',
  207. });
  208. }
  209. for (const [ruleName, ranges] of Object.entries(disabledRanges)) {
  210. const lastRange = ranges[ranges.length - 1];
  211. if (!lastRange || !lastRange.end) {
  212. endDisabledRange(endLine, ruleName, ruleName === ALL_RULES);
  213. }
  214. }
  215. continue;
  216. }
  217. if (ruleIsDisabled(ALL_RULES) && disabledRanges[ruleToEnable] === undefined) {
  218. // Get a starting point from the where all rules were disabled
  219. disabledRanges[ruleToEnable] = disabledRanges[ALL_RULES].map(
  220. ({ start, end, description }) =>
  221. createDisableRange(comment, start, false, description, end, false),
  222. );
  223. endDisabledRange(endLine, ruleToEnable, true);
  224. continue;
  225. }
  226. if (ruleIsDisabled(ruleToEnable)) {
  227. endDisabledRange(endLine, ruleToEnable, true);
  228. continue;
  229. }
  230. throw comment.error(`"${ruleToEnable}" has not been disabled`, {
  231. plugin: 'stylelint',
  232. });
  233. }
  234. }
  235. /**
  236. * @param {PostcssComment} comment
  237. */
  238. function checkComment(comment) {
  239. // Ignore comments that are not relevant commands
  240. if (!isConfigurationComment(comment, configurationComment)) {
  241. return;
  242. }
  243. switch (extractConfigurationComment(comment, configurationComment)) {
  244. case DISABLE_LINE_COMMAND:
  245. processDisableLineCommand(comment);
  246. break;
  247. case DISABLE_NEXT_LINE_COMMAND:
  248. processDisableNextLineCommand(comment);
  249. break;
  250. case DISABLE_COMMAND:
  251. processDisableCommand(comment);
  252. break;
  253. case ENABLE_COMMAND:
  254. processEnableCommand(comment);
  255. break;
  256. }
  257. }
  258. /**
  259. * @param {string} command
  260. * @param {string} fullText
  261. * @returns {string[]}
  262. */
  263. function getCommandRules(command, fullText) {
  264. // Allow for description (f.e. /* stylelint-disable a, b -- Description */).
  265. const fullCommand = getConfigurationComment(command, configurationComment);
  266. const splitted = fullText.slice(fullCommand.length).split(/\s-{2,}\s/u)[0];
  267. assertString(splitted);
  268. const rules = splitted
  269. .trim()
  270. .split(',')
  271. .filter(Boolean)
  272. .map((r) => r.trim());
  273. if (rules.length === 0) {
  274. return [ALL_RULES];
  275. }
  276. return rules;
  277. }
  278. /**
  279. * @param {string} fullText
  280. * @returns {string|undefined}
  281. */
  282. function getDescription(fullText) {
  283. const descriptionStart = fullText.indexOf('--');
  284. if (descriptionStart === -1) return;
  285. return fullText.slice(descriptionStart + 2).trim();
  286. }
  287. /**
  288. * @param {PostcssComment} comment
  289. * @param {number} line
  290. * @param {string} ruleName
  291. * @param {boolean} strict
  292. * @param {string|undefined} description
  293. */
  294. function startDisabledRange(comment, line, ruleName, strict, description) {
  295. const rangeObj = createDisableRange(comment, line, strict, description);
  296. ensureRuleRanges(ruleName);
  297. const range = disabledRanges[ruleName];
  298. assert(range);
  299. range.push(rangeObj);
  300. }
  301. /**
  302. * @param {number} line
  303. * @param {string} ruleName
  304. * @param {boolean} strict
  305. */
  306. function endDisabledRange(line, ruleName, strict) {
  307. const ranges = disabledRanges[ruleName];
  308. const lastRangeForRule = ranges ? ranges[ranges.length - 1] : null;
  309. if (!lastRangeForRule) {
  310. return;
  311. }
  312. // Add an `end` prop to the last range of that rule
  313. lastRangeForRule.end = line;
  314. lastRangeForRule.strictEnd = strict;
  315. }
  316. /**
  317. * @param {string} ruleName
  318. */
  319. function ensureRuleRanges(ruleName) {
  320. if (!disabledRanges[ruleName]) {
  321. disabledRanges[ruleName] = disabledRanges[ALL_RULES].map(
  322. ({ comment, start, end, description }) =>
  323. createDisableRange(comment, start, false, description, end, false),
  324. );
  325. }
  326. }
  327. /**
  328. * @param {string} ruleName
  329. * @returns {boolean}
  330. */
  331. function ruleIsDisabled(ruleName) {
  332. const ranges = disabledRanges[ruleName];
  333. if (!ranges) return false;
  334. const lastRange = ranges[ranges.length - 1];
  335. if (!lastRange) return false;
  336. if (!lastRange.end) return true;
  337. return false;
  338. }
  339. };