max-len.js 14 KB

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