max-len.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /**
  2. * @fileoverview Rule to check for max length on a line.
  3. * @author Matt DuVall <http://www.mattduvall.com>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Constants
  8. //------------------------------------------------------------------------------
  9. const OPTIONS_SCHEMA = {
  10. type: "object",
  11. properties: {
  12. code: {
  13. type: "integer",
  14. minimum: 0
  15. },
  16. comments: {
  17. type: "integer",
  18. minimum: 0
  19. },
  20. tabWidth: {
  21. type: "integer",
  22. minimum: 0
  23. },
  24. ignorePattern: {
  25. type: "string"
  26. },
  27. ignoreComments: {
  28. type: "boolean"
  29. },
  30. ignoreStrings: {
  31. type: "boolean"
  32. },
  33. ignoreUrls: {
  34. type: "boolean"
  35. },
  36. ignoreTemplateLiterals: {
  37. type: "boolean"
  38. },
  39. ignoreRegExpLiterals: {
  40. type: "boolean"
  41. },
  42. ignoreTrailingComments: {
  43. type: "boolean"
  44. }
  45. },
  46. additionalProperties: false
  47. };
  48. const OPTIONS_OR_INTEGER_SCHEMA = {
  49. anyOf: [
  50. OPTIONS_SCHEMA,
  51. {
  52. type: "integer",
  53. minimum: 0
  54. }
  55. ]
  56. };
  57. //------------------------------------------------------------------------------
  58. // Rule Definition
  59. //------------------------------------------------------------------------------
  60. module.exports = {
  61. meta: {
  62. type: "layout",
  63. docs: {
  64. description: "enforce a maximum line length",
  65. category: "Stylistic Issues",
  66. recommended: false,
  67. url: "https://eslint.org/docs/rules/max-len"
  68. },
  69. schema: [
  70. OPTIONS_OR_INTEGER_SCHEMA,
  71. OPTIONS_OR_INTEGER_SCHEMA,
  72. OPTIONS_SCHEMA
  73. ],
  74. messages: {
  75. max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.",
  76. maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}."
  77. }
  78. },
  79. create(context) {
  80. /*
  81. * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
  82. * - They're matching an entire string that we know is a URI
  83. * - We're matching part of a string where we think there *might* be a URL
  84. * - We're only concerned about URLs, as picking out any URI would cause
  85. * too many false positives
  86. * - We don't care about matching the entire URL, any small segment is fine
  87. */
  88. const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
  89. const sourceCode = context.getSourceCode();
  90. /**
  91. * Computes the length of a line that may contain tabs. The width of each
  92. * tab will be the number of spaces to the next tab stop.
  93. * @param {string} line The line.
  94. * @param {int} tabWidth The width of each tab stop in spaces.
  95. * @returns {int} The computed line length.
  96. * @private
  97. */
  98. function computeLineLength(line, tabWidth) {
  99. let extraCharacterCount = 0;
  100. line.replace(/\t/gu, (match, offset) => {
  101. const totalOffset = offset + extraCharacterCount,
  102. previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
  103. spaceCount = tabWidth - previousTabStopOffset;
  104. extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
  105. });
  106. return Array.from(line).length + extraCharacterCount;
  107. }
  108. // The options object must be the last option specified…
  109. const options = Object.assign({}, context.options[context.options.length - 1]);
  110. // …but max code length…
  111. if (typeof context.options[0] === "number") {
  112. options.code = context.options[0];
  113. }
  114. // …and tabWidth can be optionally specified directly as integers.
  115. if (typeof context.options[1] === "number") {
  116. options.tabWidth = context.options[1];
  117. }
  118. const maxLength = typeof options.code === "number" ? options.code : 80,
  119. tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4,
  120. ignoreComments = !!options.ignoreComments,
  121. ignoreStrings = !!options.ignoreStrings,
  122. ignoreTemplateLiterals = !!options.ignoreTemplateLiterals,
  123. ignoreRegExpLiterals = !!options.ignoreRegExpLiterals,
  124. ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments,
  125. ignoreUrls = !!options.ignoreUrls,
  126. maxCommentLength = options.comments;
  127. let ignorePattern = options.ignorePattern || null;
  128. if (ignorePattern) {
  129. ignorePattern = new RegExp(ignorePattern, "u");
  130. }
  131. //--------------------------------------------------------------------------
  132. // Helpers
  133. //--------------------------------------------------------------------------
  134. /**
  135. * Tells if a given comment is trailing: it starts on the current line and
  136. * extends to or past the end of the current line.
  137. * @param {string} line The source line we want to check for a trailing comment on
  138. * @param {number} lineNumber The one-indexed line number for line
  139. * @param {ASTNode} comment The comment to inspect
  140. * @returns {boolean} If the comment is trailing on the given line
  141. */
  142. function isTrailingComment(line, lineNumber, comment) {
  143. return comment &&
  144. (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) &&
  145. (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length);
  146. }
  147. /**
  148. * Tells if a comment encompasses the entire line.
  149. * @param {string} line The source line with a trailing comment
  150. * @param {number} lineNumber The one-indexed line number this is on
  151. * @param {ASTNode} comment The comment to remove
  152. * @returns {boolean} If the comment covers the entire line
  153. */
  154. function isFullLineComment(line, lineNumber, comment) {
  155. const start = comment.loc.start,
  156. end = comment.loc.end,
  157. isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim();
  158. return comment &&
  159. (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) &&
  160. (end.line > lineNumber || (end.line === lineNumber && end.column === line.length));
  161. }
  162. /**
  163. * Gets the line after the comment and any remaining trailing whitespace is
  164. * stripped.
  165. * @param {string} line The source line with a trailing comment
  166. * @param {ASTNode} comment The comment to remove
  167. * @returns {string} Line without comment and trailing whitepace
  168. */
  169. function stripTrailingComment(line, comment) {
  170. // loc.column is zero-indexed
  171. return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
  172. }
  173. /**
  174. * Ensure that an array exists at [key] on `object`, and add `value` to it.
  175. * @param {Object} object the object to mutate
  176. * @param {string} key the object's key
  177. * @param {*} value the value to add
  178. * @returns {void}
  179. * @private
  180. */
  181. function ensureArrayAndPush(object, key, value) {
  182. if (!Array.isArray(object[key])) {
  183. object[key] = [];
  184. }
  185. object[key].push(value);
  186. }
  187. /**
  188. * Retrieves an array containing all strings (" or ') in the source code.
  189. * @returns {ASTNode[]} An array of string nodes.
  190. */
  191. function getAllStrings() {
  192. return sourceCode.ast.tokens.filter(token => (token.type === "String" ||
  193. (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute")));
  194. }
  195. /**
  196. * Retrieves an array containing all template literals in the source code.
  197. * @returns {ASTNode[]} An array of template literal nodes.
  198. */
  199. function getAllTemplateLiterals() {
  200. return sourceCode.ast.tokens.filter(token => token.type === "Template");
  201. }
  202. /**
  203. * Retrieves an array containing all RegExp literals in the source code.
  204. * @returns {ASTNode[]} An array of RegExp literal nodes.
  205. */
  206. function getAllRegExpLiterals() {
  207. return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression");
  208. }
  209. /**
  210. * A reducer to group an AST node by line number, both start and end.
  211. * @param {Object} acc the accumulator
  212. * @param {ASTNode} node the AST node in question
  213. * @returns {Object} the modified accumulator
  214. * @private
  215. */
  216. function groupByLineNumber(acc, node) {
  217. for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
  218. ensureArrayAndPush(acc, i, node);
  219. }
  220. return acc;
  221. }
  222. /**
  223. * Check the program for max length
  224. * @param {ASTNode} node Node to examine
  225. * @returns {void}
  226. * @private
  227. */
  228. function checkProgramForMaxLength(node) {
  229. // split (honors line-ending)
  230. const lines = sourceCode.lines,
  231. // list of comments to ignore
  232. comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];
  233. // we iterate over comments in parallel with the lines
  234. let commentsIndex = 0;
  235. const strings = getAllStrings();
  236. const stringsByLine = strings.reduce(groupByLineNumber, {});
  237. const templateLiterals = getAllTemplateLiterals();
  238. const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
  239. const regExpLiterals = getAllRegExpLiterals();
  240. const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
  241. lines.forEach((line, i) => {
  242. // i is zero-indexed, line numbers are one-indexed
  243. const lineNumber = i + 1;
  244. /*
  245. * if we're checking comment length; we need to know whether this
  246. * line is a comment
  247. */
  248. let lineIsComment = false;
  249. let textToMeasure;
  250. /*
  251. * We can short-circuit the comment checks if we're already out of
  252. * comments to check.
  253. */
  254. if (commentsIndex < comments.length) {
  255. let comment = null;
  256. // iterate over comments until we find one past the current line
  257. do {
  258. comment = comments[++commentsIndex];
  259. } while (comment && comment.loc.start.line <= lineNumber);
  260. // and step back by one
  261. comment = comments[--commentsIndex];
  262. if (isFullLineComment(line, lineNumber, comment)) {
  263. lineIsComment = true;
  264. textToMeasure = line;
  265. } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
  266. textToMeasure = stripTrailingComment(line, comment);
  267. // ignore multiple trailing comments in the same line
  268. let lastIndex = commentsIndex;
  269. while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) {
  270. textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]);
  271. }
  272. } else {
  273. textToMeasure = line;
  274. }
  275. } else {
  276. textToMeasure = line;
  277. }
  278. if (ignorePattern && ignorePattern.test(textToMeasure) ||
  279. ignoreUrls && URL_REGEXP.test(textToMeasure) ||
  280. ignoreStrings && stringsByLine[lineNumber] ||
  281. ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
  282. ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
  283. ) {
  284. // ignore this line
  285. return;
  286. }
  287. const lineLength = computeLineLength(textToMeasure, tabWidth);
  288. const commentLengthApplies = lineIsComment && maxCommentLength;
  289. if (lineIsComment && ignoreComments) {
  290. return;
  291. }
  292. if (commentLengthApplies) {
  293. if (lineLength > maxCommentLength) {
  294. context.report({
  295. node,
  296. loc: { line: lineNumber, column: 0 },
  297. messageId: "maxComment",
  298. data: {
  299. lineLength,
  300. maxCommentLength
  301. }
  302. });
  303. }
  304. } else if (lineLength > maxLength) {
  305. context.report({
  306. node,
  307. loc: { line: lineNumber, column: 0 },
  308. messageId: "max",
  309. data: {
  310. lineLength,
  311. maxLength
  312. }
  313. });
  314. }
  315. });
  316. }
  317. //--------------------------------------------------------------------------
  318. // Public API
  319. //--------------------------------------------------------------------------
  320. return {
  321. Program: checkProgramForMaxLength
  322. };
  323. }
  324. };