assignDisabledRanges.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. 'use strict';
  2. const isStandardSyntaxComment = require('./utils/isStandardSyntaxComment');
  3. const { assert, assertNumber, assertString } = 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 & { all: DisabledRange[] }}
  51. */
  52. const disabledRanges = {
  53. [ALL_RULES]: [],
  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((ranges) => {
  198. if (ranges.length === 0) return true;
  199. const lastRange = ranges[ranges.length - 1];
  200. return lastRange && typeof lastRange.end === 'number';
  201. })
  202. ) {
  203. throw comment.error('No rules have been disabled', {
  204. plugin: 'stylelint',
  205. });
  206. }
  207. for (const [ruleName, ranges] of Object.entries(disabledRanges)) {
  208. const lastRange = ranges[ranges.length - 1];
  209. if (!lastRange || !lastRange.end) {
  210. endDisabledRange(endLine, ruleName, ruleName === ALL_RULES);
  211. }
  212. }
  213. continue;
  214. }
  215. if (ruleIsDisabled(ALL_RULES) && disabledRanges[ruleToEnable] === undefined) {
  216. // Get a starting point from the where all rules were disabled
  217. disabledRanges[ruleToEnable] = disabledRanges[ALL_RULES].map(
  218. ({ start, end, description }) =>
  219. createDisableRange(comment, start, false, description, end, false),
  220. );
  221. endDisabledRange(endLine, ruleToEnable, true);
  222. continue;
  223. }
  224. if (ruleIsDisabled(ruleToEnable)) {
  225. endDisabledRange(endLine, ruleToEnable, true);
  226. continue;
  227. }
  228. throw comment.error(`"${ruleToEnable}" has not been disabled`, {
  229. plugin: 'stylelint',
  230. });
  231. }
  232. }
  233. /**
  234. * @param {PostcssComment} comment
  235. */
  236. function checkComment(comment) {
  237. const text = comment.text;
  238. // Ignore comments that are not relevant commands
  239. if (text.indexOf(COMMAND_PREFIX) !== 0) {
  240. return;
  241. }
  242. if (text.startsWith(disableLineCommand)) {
  243. processDisableLineCommand(comment);
  244. } else if (text.startsWith(disableNextLineCommand)) {
  245. processDisableNextLineCommand(comment);
  246. } else if (text.startsWith(disableCommand)) {
  247. processDisableCommand(comment);
  248. } else if (text.startsWith(enableCommand)) {
  249. processEnableCommand(comment);
  250. }
  251. }
  252. /**
  253. * @param {string} command
  254. * @param {string} fullText
  255. * @returns {string[]}
  256. */
  257. function getCommandRules(command, fullText) {
  258. // Allow for description (f.e. /* stylelint-disable a, b -- Description */).
  259. const splitted = fullText.slice(command.length).split(/\s-{2,}\s/u)[0];
  260. assertString(splitted);
  261. const rules = splitted
  262. .trim()
  263. .split(',')
  264. .filter(Boolean)
  265. .map((r) => r.trim());
  266. if (rules.length === 0) {
  267. return [ALL_RULES];
  268. }
  269. return rules;
  270. }
  271. /**
  272. * @param {string} fullText
  273. * @returns {string|undefined}
  274. */
  275. function getDescription(fullText) {
  276. const descriptionStart = fullText.indexOf('--');
  277. if (descriptionStart === -1) return;
  278. return fullText.slice(descriptionStart + 2).trim();
  279. }
  280. /**
  281. * @param {PostcssComment} comment
  282. * @param {number} line
  283. * @param {string} ruleName
  284. * @param {boolean} strict
  285. * @param {string|undefined} description
  286. */
  287. function startDisabledRange(comment, line, ruleName, strict, description) {
  288. const rangeObj = createDisableRange(comment, line, strict, description);
  289. ensureRuleRanges(ruleName);
  290. const range = disabledRanges[ruleName];
  291. assert(range);
  292. range.push(rangeObj);
  293. }
  294. /**
  295. * @param {number} line
  296. * @param {string} ruleName
  297. * @param {boolean} strict
  298. */
  299. function endDisabledRange(line, ruleName, strict) {
  300. const ranges = disabledRanges[ruleName];
  301. const lastRangeForRule = ranges ? ranges[ranges.length - 1] : null;
  302. if (!lastRangeForRule) {
  303. return;
  304. }
  305. // Add an `end` prop to the last range of that rule
  306. lastRangeForRule.end = line;
  307. lastRangeForRule.strictEnd = strict;
  308. }
  309. /**
  310. * @param {string} ruleName
  311. */
  312. function ensureRuleRanges(ruleName) {
  313. if (!disabledRanges[ruleName]) {
  314. disabledRanges[ruleName] = disabledRanges[ALL_RULES].map(
  315. ({ comment, start, end, description }) =>
  316. createDisableRange(comment, start, false, description, end, false),
  317. );
  318. }
  319. }
  320. /**
  321. * @param {string} ruleName
  322. * @returns {boolean}
  323. */
  324. function ruleIsDisabled(ruleName) {
  325. const ranges = disabledRanges[ruleName];
  326. if (!ranges) return false;
  327. const lastRange = ranges[ranges.length - 1];
  328. if (!lastRange) return false;
  329. if (!lastRange.end) return true;
  330. return false;
  331. }
  332. };