no-trailing-spaces.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /**
  2. * @fileoverview Disallow trailing spaces at the end of lines.
  3. * @author Nodeca Team <https://github.com/nodeca>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. module.exports = {
  14. meta: {
  15. type: "layout",
  16. docs: {
  17. description: "disallow trailing whitespace at the end of lines",
  18. category: "Stylistic Issues",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-trailing-spaces"
  21. },
  22. fixable: "whitespace",
  23. schema: [
  24. {
  25. type: "object",
  26. properties: {
  27. skipBlankLines: {
  28. type: "boolean",
  29. default: false
  30. },
  31. ignoreComments: {
  32. type: "boolean",
  33. default: false
  34. }
  35. },
  36. additionalProperties: false
  37. }
  38. ]
  39. },
  40. create(context) {
  41. const sourceCode = context.getSourceCode();
  42. const BLANK_CLASS = "[ \t\u00a0\u2000-\u200b\u3000]",
  43. SKIP_BLANK = `^${BLANK_CLASS}*$`,
  44. NONBLANK = `${BLANK_CLASS}+$`;
  45. const options = context.options[0] || {},
  46. skipBlankLines = options.skipBlankLines || false,
  47. ignoreComments = options.ignoreComments || false;
  48. /**
  49. * Report the error message
  50. * @param {ASTNode} node node to report
  51. * @param {int[]} location range information
  52. * @param {int[]} fixRange Range based on the whole program
  53. * @returns {void}
  54. */
  55. function report(node, location, fixRange) {
  56. /*
  57. * Passing node is a bit dirty, because message data will contain big
  58. * text in `source`. But... who cares :) ?
  59. * One more kludge will not make worse the bloody wizardry of this
  60. * plugin.
  61. */
  62. context.report({
  63. node,
  64. loc: location,
  65. message: "Trailing spaces not allowed.",
  66. fix(fixer) {
  67. return fixer.removeRange(fixRange);
  68. }
  69. });
  70. }
  71. /**
  72. * Given a list of comment nodes, return the line numbers for those comments.
  73. * @param {Array} comments An array of comment nodes.
  74. * @returns {number[]} An array of line numbers containing comments.
  75. */
  76. function getCommentLineNumbers(comments) {
  77. const lines = new Set();
  78. comments.forEach(comment => {
  79. const endLine = comment.type === "Block"
  80. ? comment.loc.end.line - 1
  81. : comment.loc.end.line;
  82. for (let i = comment.loc.start.line; i <= endLine; i++) {
  83. lines.add(i);
  84. }
  85. });
  86. return lines;
  87. }
  88. //--------------------------------------------------------------------------
  89. // Public
  90. //--------------------------------------------------------------------------
  91. return {
  92. Program: function checkTrailingSpaces(node) {
  93. /*
  94. * Let's hack. Since Espree does not return whitespace nodes,
  95. * fetch the source code and do matching via regexps.
  96. */
  97. const re = new RegExp(NONBLANK, "u"),
  98. skipMatch = new RegExp(SKIP_BLANK, "u"),
  99. lines = sourceCode.lines,
  100. linebreaks = sourceCode.getText().match(astUtils.createGlobalLinebreakMatcher()),
  101. comments = sourceCode.getAllComments(),
  102. commentLineNumbers = getCommentLineNumbers(comments);
  103. let totalLength = 0,
  104. fixRange = [];
  105. for (let i = 0, ii = lines.length; i < ii; i++) {
  106. const lineNumber = i + 1;
  107. /*
  108. * Always add linebreak length to line length to accommodate for line break (\n or \r\n)
  109. * Because during the fix time they also reserve one spot in the array.
  110. * Usually linebreak length is 2 for \r\n (CRLF) and 1 for \n (LF)
  111. */
  112. const linebreakLength = linebreaks && linebreaks[i] ? linebreaks[i].length : 1;
  113. const lineLength = lines[i].length + linebreakLength;
  114. const matches = re.exec(lines[i]);
  115. if (matches) {
  116. const location = {
  117. start: {
  118. line: lineNumber,
  119. column: matches.index
  120. },
  121. end: {
  122. line: lineNumber,
  123. column: lineLength - linebreakLength
  124. }
  125. };
  126. const rangeStart = totalLength + location.start.column;
  127. const rangeEnd = totalLength + location.end.column;
  128. const containingNode = sourceCode.getNodeByRangeIndex(rangeStart);
  129. if (containingNode && containingNode.type === "TemplateElement" &&
  130. rangeStart > containingNode.parent.range[0] &&
  131. rangeEnd < containingNode.parent.range[1]) {
  132. totalLength += lineLength;
  133. continue;
  134. }
  135. /*
  136. * If the line has only whitespace, and skipBlankLines
  137. * is true, don't report it
  138. */
  139. if (skipBlankLines && skipMatch.test(lines[i])) {
  140. totalLength += lineLength;
  141. continue;
  142. }
  143. fixRange = [rangeStart, rangeEnd];
  144. if (!ignoreComments || !commentLineNumbers.has(lineNumber)) {
  145. report(node, location, fixRange);
  146. }
  147. }
  148. totalLength += lineLength;
  149. }
  150. }
  151. };
  152. }
  153. };