max-len.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. /** @type {import('../shared/types').Rule} */
  61. module.exports = {
  62. meta: {
  63. type: "layout",
  64. docs: {
  65. description: "Enforce a maximum line length",
  66. recommended: false,
  67. url: "https://eslint.org/docs/latest/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.sourceCode;
  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 {any} 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. *
  223. * reduce an array of AST nodes by line number, both start and end.
  224. * @param {ASTNode[]} arr array of AST nodes
  225. * @returns {Object} accululated AST nodes
  226. */
  227. function groupArrayByLineNumber(arr) {
  228. const obj = {};
  229. for (let i = 0; i < arr.length; i++) {
  230. const node = arr[i];
  231. for (let j = node.loc.start.line; j <= node.loc.end.line; ++j) {
  232. ensureArrayAndPush(obj, j, node);
  233. }
  234. }
  235. return obj;
  236. }
  237. /**
  238. * Returns an array of all comments in the source code.
  239. * If the element in the array is a JSXEmptyExpression contained with a single line JSXExpressionContainer,
  240. * the element is changed with JSXExpressionContainer node.
  241. * @returns {ASTNode[]} An array of comment nodes
  242. */
  243. function getAllComments() {
  244. const comments = [];
  245. sourceCode.getAllComments()
  246. .forEach(commentNode => {
  247. const containingNode = sourceCode.getNodeByRangeIndex(commentNode.range[0]);
  248. if (isJSXEmptyExpressionInSingleLineContainer(containingNode)) {
  249. // push a unique node only
  250. if (comments[comments.length - 1] !== containingNode.parent) {
  251. comments.push(containingNode.parent);
  252. }
  253. } else {
  254. comments.push(commentNode);
  255. }
  256. });
  257. return comments;
  258. }
  259. /**
  260. * Check the program for max length
  261. * @param {ASTNode} node Node to examine
  262. * @returns {void}
  263. * @private
  264. */
  265. function checkProgramForMaxLength(node) {
  266. // split (honors line-ending)
  267. const lines = sourceCode.lines,
  268. // list of comments to ignore
  269. comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? getAllComments() : [];
  270. // we iterate over comments in parallel with the lines
  271. let commentsIndex = 0;
  272. const strings = getAllStrings();
  273. const stringsByLine = groupArrayByLineNumber(strings);
  274. const templateLiterals = getAllTemplateLiterals();
  275. const templateLiteralsByLine = groupArrayByLineNumber(templateLiterals);
  276. const regExpLiterals = getAllRegExpLiterals();
  277. const regExpLiteralsByLine = groupArrayByLineNumber(regExpLiterals);
  278. lines.forEach((line, i) => {
  279. // i is zero-indexed, line numbers are one-indexed
  280. const lineNumber = i + 1;
  281. /*
  282. * if we're checking comment length; we need to know whether this
  283. * line is a comment
  284. */
  285. let lineIsComment = false;
  286. let textToMeasure;
  287. /*
  288. * We can short-circuit the comment checks if we're already out of
  289. * comments to check.
  290. */
  291. if (commentsIndex < comments.length) {
  292. let comment = null;
  293. // iterate over comments until we find one past the current line
  294. do {
  295. comment = comments[++commentsIndex];
  296. } while (comment && comment.loc.start.line <= lineNumber);
  297. // and step back by one
  298. comment = comments[--commentsIndex];
  299. if (isFullLineComment(line, lineNumber, comment)) {
  300. lineIsComment = true;
  301. textToMeasure = line;
  302. } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
  303. textToMeasure = stripTrailingComment(line, comment);
  304. // ignore multiple trailing comments in the same line
  305. let lastIndex = commentsIndex;
  306. while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) {
  307. textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]);
  308. }
  309. } else {
  310. textToMeasure = line;
  311. }
  312. } else {
  313. textToMeasure = line;
  314. }
  315. if (ignorePattern && ignorePattern.test(textToMeasure) ||
  316. ignoreUrls && URL_REGEXP.test(textToMeasure) ||
  317. ignoreStrings && stringsByLine[lineNumber] ||
  318. ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
  319. ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
  320. ) {
  321. // ignore this line
  322. return;
  323. }
  324. const lineLength = computeLineLength(textToMeasure, tabWidth);
  325. const commentLengthApplies = lineIsComment && maxCommentLength;
  326. if (lineIsComment && ignoreComments) {
  327. return;
  328. }
  329. const loc = {
  330. start: {
  331. line: lineNumber,
  332. column: 0
  333. },
  334. end: {
  335. line: lineNumber,
  336. column: textToMeasure.length
  337. }
  338. };
  339. if (commentLengthApplies) {
  340. if (lineLength > maxCommentLength) {
  341. context.report({
  342. node,
  343. loc,
  344. messageId: "maxComment",
  345. data: {
  346. lineLength,
  347. maxCommentLength
  348. }
  349. });
  350. }
  351. } else if (lineLength > maxLength) {
  352. context.report({
  353. node,
  354. loc,
  355. messageId: "max",
  356. data: {
  357. lineLength,
  358. maxLength
  359. }
  360. });
  361. }
  362. });
  363. }
  364. //--------------------------------------------------------------------------
  365. // Public API
  366. //--------------------------------------------------------------------------
  367. return {
  368. Program: checkProgramForMaxLength
  369. };
  370. }
  371. };