index.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. 'use strict';
  2. const styleSearch = require('style-search');
  3. const isOnlyWhitespace = require('../../utils/isOnlyWhitespace');
  4. const isStandardSyntaxComment = require('../../utils/isStandardSyntaxComment');
  5. const optionsMatches = require('../../utils/optionsMatches');
  6. const report = require('../../utils/report');
  7. const ruleMessages = require('../../utils/ruleMessages');
  8. const { isAtRule, isComment, isDeclaration, isRule } = require('../../utils/typeGuards');
  9. const validateOptions = require('../../utils/validateOptions');
  10. const ruleName = 'no-eol-whitespace';
  11. const messages = ruleMessages(ruleName, {
  12. rejected: 'Unexpected whitespace at end of line',
  13. });
  14. const meta = {
  15. url: 'https://stylelint.io/user-guide/rules/no-eol-whitespace',
  16. fixable: true,
  17. };
  18. const whitespacesToReject = new Set([' ', '\t']);
  19. /**
  20. * @param {string} str
  21. * @returns {string}
  22. */
  23. function fixString(str) {
  24. return str.replace(/[ \t]+$/, '');
  25. }
  26. /**
  27. * @param {number} lastEOLIndex
  28. * @param {string} string
  29. * @param {{ ignoreEmptyLines: boolean, isRootFirst: boolean }} options
  30. * @returns {number}
  31. */
  32. function findErrorStartIndex(lastEOLIndex, string, { ignoreEmptyLines, isRootFirst }) {
  33. const eolWhitespaceIndex = lastEOLIndex - 1;
  34. // If the character before newline is not whitespace, ignore
  35. if (!whitespacesToReject.has(string.charAt(eolWhitespaceIndex))) {
  36. return -1;
  37. }
  38. if (ignoreEmptyLines) {
  39. // If there is only whitespace between the previous newline and
  40. // this newline, ignore
  41. const beforeNewlineIndex = string.lastIndexOf('\n', eolWhitespaceIndex);
  42. if (beforeNewlineIndex >= 0 || isRootFirst) {
  43. const line = string.substring(beforeNewlineIndex, eolWhitespaceIndex);
  44. if (isOnlyWhitespace(line)) {
  45. return -1;
  46. }
  47. }
  48. }
  49. return eolWhitespaceIndex;
  50. }
  51. /** @type {import('stylelint').Rule} */
  52. const rule = (primary, secondaryOptions, context) => {
  53. return (root, result) => {
  54. const validOptions = validateOptions(
  55. result,
  56. ruleName,
  57. {
  58. actual: primary,
  59. },
  60. {
  61. optional: true,
  62. actual: secondaryOptions,
  63. possible: {
  64. ignore: ['empty-lines'],
  65. },
  66. },
  67. );
  68. if (!validOptions) {
  69. return;
  70. }
  71. const ignoreEmptyLines = optionsMatches(secondaryOptions, 'ignore', 'empty-lines');
  72. if (context.fix) {
  73. fix(root);
  74. }
  75. const rootString = context.fix ? root.toString() : (root.source && root.source.input.css) || '';
  76. /**
  77. * @param {number} index
  78. */
  79. const reportFromIndex = (index) => {
  80. report({
  81. message: messages.rejected,
  82. node: root,
  83. index,
  84. result,
  85. ruleName,
  86. });
  87. };
  88. eachEolWhitespace(rootString, reportFromIndex, true);
  89. const errorIndex = findErrorStartIndex(rootString.length, rootString, {
  90. ignoreEmptyLines,
  91. isRootFirst: true,
  92. });
  93. if (errorIndex > -1) {
  94. reportFromIndex(errorIndex);
  95. }
  96. /**
  97. * Iterate each whitespace at the end of each line of the given string.
  98. * @param {string} string - the source code string
  99. * @param {(index: number) => void} callback - callback the whitespace index at the end of each line.
  100. * @param {boolean} isRootFirst - set `true` if the given string is the first token of the root.
  101. * @returns {void}
  102. */
  103. function eachEolWhitespace(string, callback, isRootFirst) {
  104. styleSearch(
  105. {
  106. source: string,
  107. target: ['\n', '\r'],
  108. comments: 'check',
  109. },
  110. (match) => {
  111. const index = findErrorStartIndex(match.startIndex, string, {
  112. ignoreEmptyLines,
  113. isRootFirst,
  114. });
  115. if (index > -1) {
  116. callback(index);
  117. }
  118. },
  119. );
  120. }
  121. /**
  122. * @param {import('postcss').Root} rootNode
  123. */
  124. function fix(rootNode) {
  125. let isRootFirst = true;
  126. rootNode.walk((node) => {
  127. fixText(
  128. node.raws.before,
  129. (fixed) => {
  130. node.raws.before = fixed;
  131. },
  132. isRootFirst,
  133. );
  134. isRootFirst = false;
  135. if (isAtRule(node)) {
  136. fixText(node.raws.afterName, (fixed) => {
  137. node.raws.afterName = fixed;
  138. });
  139. const rawsParams = node.raws.params;
  140. if (rawsParams) {
  141. fixText(rawsParams.raw, (fixed) => {
  142. rawsParams.raw = fixed;
  143. });
  144. } else {
  145. fixText(node.params, (fixed) => {
  146. node.params = fixed;
  147. });
  148. }
  149. }
  150. if (isRule(node)) {
  151. const rawsSelector = node.raws.selector;
  152. if (rawsSelector) {
  153. fixText(rawsSelector.raw, (fixed) => {
  154. rawsSelector.raw = fixed;
  155. });
  156. } else {
  157. fixText(node.selector, (fixed) => {
  158. node.selector = fixed;
  159. });
  160. }
  161. }
  162. if (isAtRule(node) || isRule(node) || isDeclaration(node)) {
  163. fixText(node.raws.between, (fixed) => {
  164. node.raws.between = fixed;
  165. });
  166. }
  167. if (isDeclaration(node)) {
  168. const rawsValue = node.raws.value;
  169. if (rawsValue) {
  170. fixText(rawsValue.raw, (fixed) => {
  171. rawsValue.raw = fixed;
  172. });
  173. } else {
  174. fixText(node.value, (fixed) => {
  175. node.value = fixed;
  176. });
  177. }
  178. }
  179. if (isComment(node)) {
  180. fixText(node.raws.left, (fixed) => {
  181. node.raws.left = fixed;
  182. });
  183. if (!isStandardSyntaxComment(node)) {
  184. node.raws.right = node.raws.right && fixString(node.raws.right);
  185. } else {
  186. fixText(node.raws.right, (fixed) => {
  187. node.raws.right = fixed;
  188. });
  189. }
  190. fixText(node.text, (fixed) => {
  191. node.text = fixed;
  192. });
  193. }
  194. if (isAtRule(node) || isRule(node)) {
  195. fixText(node.raws.after, (fixed) => {
  196. node.raws.after = fixed;
  197. });
  198. }
  199. });
  200. fixText(
  201. rootNode.raws.after,
  202. (fixed) => {
  203. rootNode.raws.after = fixed;
  204. },
  205. isRootFirst,
  206. );
  207. if (typeof rootNode.raws.after === 'string') {
  208. const lastEOL = Math.max(
  209. rootNode.raws.after.lastIndexOf('\n'),
  210. rootNode.raws.after.lastIndexOf('\r'),
  211. );
  212. if (lastEOL !== rootNode.raws.after.length - 1) {
  213. rootNode.raws.after =
  214. rootNode.raws.after.slice(0, lastEOL + 1) +
  215. fixString(rootNode.raws.after.slice(lastEOL + 1));
  216. }
  217. }
  218. }
  219. /**
  220. * @param {string | undefined} value
  221. * @param {(text: string) => void} fixFn
  222. * @param {boolean} isRootFirst
  223. */
  224. function fixText(value, fixFn, isRootFirst = false) {
  225. if (!value) {
  226. return;
  227. }
  228. let fixed = '';
  229. let lastIndex = 0;
  230. eachEolWhitespace(
  231. value,
  232. (index) => {
  233. const newlineIndex = index + 1;
  234. fixed += fixString(value.slice(lastIndex, newlineIndex));
  235. lastIndex = newlineIndex;
  236. },
  237. isRootFirst,
  238. );
  239. if (lastIndex) {
  240. fixed += value.slice(lastIndex);
  241. fixFn(fixed);
  242. }
  243. }
  244. };
  245. };
  246. rule.ruleName = ruleName;
  247. rule.messages = messages;
  248. rule.meta = meta;
  249. module.exports = rule;