assignDisabledRanges.js 10 KB

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