max-len.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. * Check if a node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
  164. * @param {ASTNode} node A node to check.
  165. * @returns {boolean} True if the node is a JSXEmptyExpression contained in a single line JSXExpressionContainer.
  166. */
  167. function isJSXEmptyExpressionInSingleLineContainer(node) {
  168. if (!node || !node.parent || node.type !== "JSXEmptyExpression" || node.parent.type !== "JSXExpressionContainer") {
  169. return false;
  170. }
  171. const parent = node.parent;
  172. return parent.loc.start.line === parent.loc.end.line;
  173. }
  174. /**
  175. * Gets the line after the comment and any remaining trailing whitespace is
  176. * stripped.
  177. * @param {string} line The source line with a trailing comment
  178. * @param {ASTNode} comment The comment to remove
  179. * @returns {string} Line without comment and trailing whitespace
  180. */
  181. function stripTrailingComment(line, comment) {
  182. // loc.column is zero-indexed
  183. return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
  184. }
  185. /**
  186. * Ensure that an array exists at [key] on `object`, and add `value` to it.
  187. * @param {Object} object the object to mutate
  188. * @param {string} key the object's key
  189. * @param {*} value the value to add
  190. * @returns {void}
  191. * @private
  192. */
  193. function ensureArrayAndPush(object, key, value) {
  194. if (!Array.isArray(object[key])) {
  195. object[key] = [];
  196. }
  197. object[key].push(value);
  198. }
  199. /**
  200. * Retrieves an array containing all strings (" or ') in the source code.
  201. * @returns {ASTNode[]} An array of string nodes.
  202. */
  203. function getAllStrings() {
  204. return sourceCode.ast.tokens.filter(token => (token.type === "String" ||
  205. (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute")));
  206. }
  207. /**
  208. * Retrieves an array containing all template literals in the source code.
  209. * @returns {ASTNode[]} An array of template literal nodes.
  210. */
  211. function getAllTemplateLiterals() {
  212. return sourceCode.ast.tokens.filter(token => token.type === "Template");
  213. }
  214. /**
  215. * Retrieves an array containing all RegExp literals in the source code.
  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. * @param {Object} acc the accumulator
  224. * @param {ASTNode} node the AST node in question
  225. * @returns {Object} the modified accumulator
  226. * @private
  227. */
  228. function groupByLineNumber(acc, node) {
  229. for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
  230. ensureArrayAndPush(acc, i, node);
  231. }
  232. return acc;
  233. }
  234. /**
  235. * Returns an array of all comments in the source code.
  236. * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
  237. * the element is changed with JSXExpressionContainer node.
  238. * @returns {ASTNode[]} An array of comment nodes
  239. */
  240. function getAllComments() {
  241. const comments = [];
  242. sourceCode.getAllComments()
  243. .forEach(commentNode => {
  244. const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]);
  245. if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
  246. // push a unique node only
  247. if (comments[comments.length - 1] !== containingNode.parent) {
  248. comments.push(containingNode.parent);
  249. }
  250. } else {
  251. comments.push(commentNode);
  252. }
  253. });
  254. return comments;
  255. }
  256. /**
  257. * Check the program for max length
  258. * @param {ASTNode} node Node to examine
  259. * @returns {void}
  260. * @private
  261. */
  262. function checkProgramForMaxLength(node) {
  263. // split (honors line-ending)
  264. const lines = sourceCode.lines,
  265. // list of comments to ignore
  266. comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : [];
  267. // we iterate over comments in parallel with the lines
  268. let commentsIndex = 0;
  269. const strings = getAllStrings();
  270. const stringsByLine = strings.reduce(groupByLineNumber, {});
  271. const templateLiterals = getAllTemplateLiterals();
  272. const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
  273. const regExpLiterals = getAllRegExpLiterals();
  274. const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
  275. lines.forEach((line, i) => {
  276. // i is zero-indexed, line numbers are one-indexed
  277. const lineNumber = i + 1;
  278. /*
  279. * if we're checking comment length; we need to know whether this
  280. * line is a comment
  281. */
  282. let lineIsComment = false;
  283. let textToMeasure;
  284. /*
  285. * We can short-circuit the comment checks if we're already out of
  286. * comments to check.
  287. */
  288. if (commentsIndex < comments.length) {
  289. let comment = null;
  290. // iterate over comments until we find one past the current line
  291. do {
  292. comment = comments[++commentsIndex];
  293. } while (comment && comment.loc.start.line <= lineNumber);
  294. // and step back by one
  295. comment = comments[--commentsIndex];
  296. if (isFullLineComment(line, lineNumber, comment)) {
  297. lineIsComment = true;
  298. textToMeasure = line;
  299. } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
  300. textToMeasure = stripTrailingComment(line, comment);
  301. // ignore multiple trailing comments in the same line
  302. let lastIndex = commentsIndex;
  303. while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) {
  304. textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]);
  305. }
  306. } else {
  307. textToMeasure = line;
  308. }
  309. } else {
  310. textToMeasure = line;
  311. }
  312. if (ignorePattern && ignorePattern.test(textToMeasure) ||
  313. ignoreUrls && URL_REGEXP.test(textToMeasure) ||
  314. ignoreStrings && stringsByLine[lineNumber] ||
  315. ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
  316. ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
  317. ) {
  318. // ignore this line
  319. return;
  320. }
  321. const lineLength = computeLineLength(textToMeasure, tabWidth);
  322. const commentLengthApplies = lineIsComment && maxCommentLength;
  323. if (lineIsComment && ignoreComments) {
  324. return;
  325. }
  326. const loc = {
  327. start: {
  328. line: lineNumber,
  329. column: 0
  330. },
  331. end: {
  332. line: lineNumber,
  333. column: textToMeasure.length
  334. }
  335. };
  336. if (commentLengthApplies) {
  337. if (lineLength > maxCommentLength) {
  338. context.report({
  339. node,
  340. loc,
  341. messageId: "maxComment",
  342. data: {
  343. lineLength,
  344. maxCommentLength
  345. }
  346. });
  347. }
  348. } else if (lineLength > maxLength) {
  349. context.report({
  350. node,
  351. loc,
  352. messageId: "max",
  353. data: {
  354. lineLength,
  355. maxLength
  356. }
  357. });
  358. }
  359. });
  360. }
  361. //--------------------------------------------------------------------------
  362. // Public API
  363. //--------------------------------------------------------------------------
  364. return {
  365. Program: checkProgramForMaxLength
  366. };
  367. }
  368. };