assignDisabledRanges.js 10 KB

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