index.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. 'use strict';
  2. const atRuleParamIndex = require('../../utils/atRuleParamIndex');
  3. const declarationValueIndex = require('../../utils/declarationValueIndex');
  4. const isStandardSyntaxRule = require('../../utils/isStandardSyntaxRule');
  5. const parseSelector = require('../../utils/parseSelector');
  6. const report = require('../../utils/report');
  7. const ruleMessages = require('../../utils/ruleMessages');
  8. const validateOptions = require('../../utils/validateOptions');
  9. const valueParser = require('postcss-value-parser');
  10. const { isBoolean, assertString } = require('../../utils/validateTypes');
  11. const { isAtRule } = require('../../utils/typeGuards');
  12. const ruleName = 'string-quotes';
  13. const messages = ruleMessages(ruleName, {
  14. expected: (q) => `Expected ${q} quotes`,
  15. });
  16. const meta = {
  17. url: 'https://stylelint.io/user-guide/rules/string-quotes',
  18. fixable: true,
  19. };
  20. const singleQuote = `'`;
  21. const doubleQuote = `"`;
  22. /** @type {import('stylelint').Rule} */
  23. const rule = (primary, secondaryOptions, context) => {
  24. const correctQuote = primary === 'single' ? singleQuote : doubleQuote;
  25. const erroneousQuote = primary === 'single' ? doubleQuote : singleQuote;
  26. return (root, result) => {
  27. const validOptions = validateOptions(
  28. result,
  29. ruleName,
  30. {
  31. actual: primary,
  32. possible: ['single', 'double'],
  33. },
  34. {
  35. actual: secondaryOptions,
  36. possible: {
  37. avoidEscape: [isBoolean],
  38. },
  39. optional: true,
  40. },
  41. );
  42. if (!validOptions) {
  43. return;
  44. }
  45. const avoidEscape =
  46. secondaryOptions && secondaryOptions.avoidEscape !== undefined
  47. ? secondaryOptions.avoidEscape
  48. : true;
  49. root.walk((node) => {
  50. switch (node.type) {
  51. case 'atrule':
  52. checkDeclOrAtRule(node, node.params, atRuleParamIndex);
  53. break;
  54. case 'decl':
  55. checkDeclOrAtRule(node, node.value, declarationValueIndex);
  56. break;
  57. case 'rule':
  58. checkRule(node);
  59. break;
  60. }
  61. });
  62. /**
  63. * @param {import('postcss').Rule} ruleNode
  64. * @returns {void}
  65. */
  66. function checkRule(ruleNode) {
  67. if (!isStandardSyntaxRule(ruleNode)) {
  68. return;
  69. }
  70. if (!ruleNode.selector.includes('[') || !ruleNode.selector.includes('=')) {
  71. return;
  72. }
  73. /** @type {number[]} */
  74. const fixPositions = [];
  75. parseSelector(ruleNode.selector, result, ruleNode, (selectorTree) => {
  76. let selectorFixed = false;
  77. selectorTree.walkAttributes((attributeNode) => {
  78. if (!attributeNode.quoted) {
  79. return;
  80. }
  81. if (attributeNode.quoteMark === correctQuote && avoidEscape) {
  82. assertString(attributeNode.value);
  83. const needsCorrectEscape = attributeNode.value.includes(correctQuote);
  84. const needsOtherEscape = attributeNode.value.includes(erroneousQuote);
  85. if (needsOtherEscape) {
  86. return;
  87. }
  88. if (needsCorrectEscape) {
  89. if (context.fix) {
  90. selectorFixed = true;
  91. attributeNode.quoteMark = erroneousQuote;
  92. } else {
  93. report({
  94. message: messages.expected(primary === 'single' ? 'double' : primary),
  95. node: ruleNode,
  96. index: attributeNode.sourceIndex + attributeNode.offsetOf('value'),
  97. result,
  98. ruleName,
  99. });
  100. }
  101. }
  102. }
  103. if (attributeNode.quoteMark === erroneousQuote) {
  104. if (avoidEscape) {
  105. assertString(attributeNode.value);
  106. const needsCorrectEscape = attributeNode.value.includes(correctQuote);
  107. const needsOtherEscape = attributeNode.value.includes(erroneousQuote);
  108. if (needsOtherEscape) {
  109. if (context.fix) {
  110. selectorFixed = true;
  111. attributeNode.quoteMark = correctQuote;
  112. } else {
  113. report({
  114. message: messages.expected(primary),
  115. node: ruleNode,
  116. index: attributeNode.sourceIndex + attributeNode.offsetOf('value'),
  117. result,
  118. ruleName,
  119. });
  120. }
  121. return;
  122. }
  123. if (needsCorrectEscape) {
  124. return;
  125. }
  126. }
  127. if (context.fix) {
  128. selectorFixed = true;
  129. attributeNode.quoteMark = correctQuote;
  130. } else {
  131. report({
  132. message: messages.expected(primary),
  133. node: ruleNode,
  134. index: attributeNode.sourceIndex + attributeNode.offsetOf('value'),
  135. result,
  136. ruleName,
  137. });
  138. }
  139. }
  140. });
  141. if (selectorFixed) {
  142. ruleNode.selector = selectorTree.toString();
  143. }
  144. });
  145. for (const fixIndex of fixPositions) {
  146. ruleNode.selector = replaceQuote(ruleNode.selector, fixIndex, correctQuote);
  147. }
  148. }
  149. /**
  150. * @template {import('postcss').AtRule | import('postcss').Declaration} T
  151. * @param {T} node
  152. * @param {string} value
  153. * @param {(node: T) => number} getIndex
  154. * @returns {void}
  155. */
  156. function checkDeclOrAtRule(node, value, getIndex) {
  157. /** @type {number[]} */
  158. const fixPositions = [];
  159. // Get out quickly if there are no erroneous quotes
  160. if (!value.includes(erroneousQuote)) {
  161. return;
  162. }
  163. if (isAtRule(node) && node.name === 'charset') {
  164. // allow @charset rules to have double quotes, in spite of the configuration
  165. // TODO: @charset should always use double-quotes, see https://github.com/stylelint/stylelint/issues/2788
  166. return;
  167. }
  168. valueParser(value).walk((valueNode) => {
  169. if (valueNode.type === 'string' && valueNode.quote === erroneousQuote) {
  170. const needsEscape = valueNode.value.includes(correctQuote);
  171. if (avoidEscape && needsEscape) {
  172. // don't consider this an error
  173. return;
  174. }
  175. const openIndex = valueNode.sourceIndex;
  176. // we currently don't fix escapes
  177. if (context.fix && !needsEscape) {
  178. const closeIndex = openIndex + valueNode.value.length + erroneousQuote.length;
  179. fixPositions.push(openIndex, closeIndex);
  180. } else {
  181. report({
  182. message: messages.expected(primary),
  183. node,
  184. index: getIndex(node) + openIndex,
  185. result,
  186. ruleName,
  187. });
  188. }
  189. }
  190. });
  191. for (const fixIndex of fixPositions) {
  192. if (isAtRule(node)) {
  193. node.params = replaceQuote(node.params, fixIndex, correctQuote);
  194. } else {
  195. node.value = replaceQuote(node.value, fixIndex, correctQuote);
  196. }
  197. }
  198. }
  199. };
  200. };
  201. /**
  202. * @param {string} string
  203. * @param {number} index
  204. * @param {string} replace
  205. * @returns {string}
  206. */
  207. function replaceQuote(string, index, replace) {
  208. return string.substring(0, index) + replace + string.substring(index + replace.length);
  209. }
  210. rule.ruleName = ruleName;
  211. rule.messages = messages;
  212. rule.meta = meta;
  213. module.exports = rule;