2 * @fileoverview Rule to check for max length on a line.
3 * @author Matt DuVall <http://www.mattduvall.com>
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const OPTIONS_SCHEMA = {
39 ignoreTemplateLiterals: {
42 ignoreRegExpLiterals: {
45 ignoreTrailingComments: {
49 additionalProperties: false
52 const OPTIONS_OR_INTEGER_SCHEMA = {
62 //------------------------------------------------------------------------------
64 //------------------------------------------------------------------------------
71 description: "enforce a maximum line length",
72 category: "Stylistic Issues",
74 url: "https://eslint.org/docs/rules/max-len"
78 OPTIONS_OR_INTEGER_SCHEMA,
79 OPTIONS_OR_INTEGER_SCHEMA,
83 max: "This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.",
84 maxComment: "This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}."
91 * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
92 * - They're matching an entire string that we know is a URI
93 * - We're matching part of a string where we think there *might* be a URL
94 * - We're only concerned about URLs, as picking out any URI would cause
95 * too many false positives
96 * - We don't care about matching the entire URL, any small segment is fine
98 const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u;
100 const sourceCode = context.getSourceCode();
103 * Computes the length of a line that may contain tabs. The width of each
104 * tab will be the number of spaces to the next tab stop.
105 * @param {string} line The line.
106 * @param {int} tabWidth The width of each tab stop in spaces.
107 * @returns {int} The computed line length.
110 function computeLineLength(line, tabWidth) {
111 let extraCharacterCount = 0;
113 line.replace(/\t/gu, (match, offset) => {
114 const totalOffset = offset + extraCharacterCount,
115 previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
116 spaceCount = tabWidth - previousTabStopOffset;
118 extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
120 return Array.from(line).length + extraCharacterCount;
123 // The options object must be the last option specified…
124 const options = Object.assign({}, context.options[context.options.length - 1]);
126 // …but max code length…
127 if (typeof context.options[0] === "number") {
128 options.code = context.options[0];
131 // …and tabWidth can be optionally specified directly as integers.
132 if (typeof context.options[1] === "number") {
133 options.tabWidth = context.options[1];
136 const maxLength = typeof options.code === "number" ? options.code : 80,
137 tabWidth = typeof options.tabWidth === "number" ? options.tabWidth : 4,
138 ignoreComments = !!options.ignoreComments,
139 ignoreStrings = !!options.ignoreStrings,
140 ignoreTemplateLiterals = !!options.ignoreTemplateLiterals,
141 ignoreRegExpLiterals = !!options.ignoreRegExpLiterals,
142 ignoreTrailingComments = !!options.ignoreTrailingComments || !!options.ignoreComments,
143 ignoreUrls = !!options.ignoreUrls,
144 maxCommentLength = options.comments;
145 let ignorePattern = options.ignorePattern || null;
148 ignorePattern = new RegExp(ignorePattern, "u");
151 //--------------------------------------------------------------------------
153 //--------------------------------------------------------------------------
156 * Tells if a given comment is trailing: it starts on the current line and
157 * extends to or past the end of the current line.
158 * @param {string} line The source line we want to check for a trailing comment on
159 * @param {number} lineNumber The one-indexed line number for line
160 * @param {ASTNode} comment The comment to inspect
161 * @returns {boolean} If the comment is trailing on the given line
163 function isTrailingComment(line, lineNumber, comment) {
165 (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) &&
166 (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length);
170 * Tells if a comment encompasses the entire line.
171 * @param {string} line The source line with a trailing comment
172 * @param {number} lineNumber The one-indexed line number this is on
173 * @param {ASTNode} comment The comment to remove
174 * @returns {boolean} If the comment covers the entire line
176 function isFullLineComment(line, lineNumber, comment) {
177 const start = comment.loc.start,
178 end = comment.loc.end,
179 isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim();
182 (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) &&
183 (end.line > lineNumber || (end.line === lineNumber && end.column === line.length));
187 * Gets the line after the comment and any remaining trailing whitespace is
189 * @param {string} line The source line with a trailing comment
190 * @param {ASTNode} comment The comment to remove
191 * @returns {string} Line without comment and trailing whitepace
193 function stripTrailingComment(line, comment) {
195 // loc.column is zero-indexed
196 return line.slice(0, comment.loc.start.column).replace(/\s+$/u, "");
200 * Ensure that an array exists at [key] on `object`, and add `value` to it.
201 * @param {Object} object the object to mutate
202 * @param {string} key the object's key
203 * @param {*} value the value to add
207 function ensureArrayAndPush(object, key, value) {
208 if (!Array.isArray(object[key])) {
211 object[key].push(value);
215 * Retrieves an array containing all strings (" or ') in the source code.
216 * @returns {ASTNode[]} An array of string nodes.
218 function getAllStrings() {
219 return sourceCode.ast.tokens.filter(token => (token.type === "String" ||
220 (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute")));
224 * Retrieves an array containing all template literals in the source code.
225 * @returns {ASTNode[]} An array of template literal nodes.
227 function getAllTemplateLiterals() {
228 return sourceCode.ast.tokens.filter(token => token.type === "Template");
233 * Retrieves an array containing all RegExp literals in the source code.
234 * @returns {ASTNode[]} An array of RegExp literal nodes.
236 function getAllRegExpLiterals() {
237 return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression");
242 * A reducer to group an AST node by line number, both start and end.
243 * @param {Object} acc the accumulator
244 * @param {ASTNode} node the AST node in question
245 * @returns {Object} the modified accumulator
248 function groupByLineNumber(acc, node) {
249 for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
250 ensureArrayAndPush(acc, i, node);
256 * Check the program for max length
257 * @param {ASTNode} node Node to examine
261 function checkProgramForMaxLength(node) {
263 // split (honors line-ending)
264 const lines = sourceCode.lines,
266 // list of comments to ignore
267 comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];
269 // we iterate over comments in parallel with the lines
270 let commentsIndex = 0;
272 const strings = getAllStrings();
273 const stringsByLine = strings.reduce(groupByLineNumber, {});
275 const templateLiterals = getAllTemplateLiterals();
276 const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
278 const regExpLiterals = getAllRegExpLiterals();
279 const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
281 lines.forEach((line, i) => {
283 // i is zero-indexed, line numbers are one-indexed
284 const lineNumber = i + 1;
287 * if we're checking comment length; we need to know whether this
290 let lineIsComment = false;
294 * We can short-circuit the comment checks if we're already out of
297 if (commentsIndex < comments.length) {
300 // iterate over comments until we find one past the current line
302 comment = comments[++commentsIndex];
303 } while (comment && comment.loc.start.line <= lineNumber);
305 // and step back by one
306 comment = comments[--commentsIndex];
308 if (isFullLineComment(line, lineNumber, comment)) {
309 lineIsComment = true;
310 textToMeasure = line;
311 } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
312 textToMeasure = stripTrailingComment(line, comment);
314 // ignore multiple trailing comments in the same line
315 let lastIndex = commentsIndex;
317 while (isTrailingComment(textToMeasure, lineNumber, comments[--lastIndex])) {
318 textToMeasure = stripTrailingComment(textToMeasure, comments[lastIndex]);
321 textToMeasure = line;
324 textToMeasure = line;
326 if (ignorePattern && ignorePattern.test(textToMeasure) ||
327 ignoreUrls && URL_REGEXP.test(textToMeasure) ||
328 ignoreStrings && stringsByLine[lineNumber] ||
329 ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
330 ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
337 const lineLength = computeLineLength(textToMeasure, tabWidth);
338 const commentLengthApplies = lineIsComment && maxCommentLength;
340 if (lineIsComment && ignoreComments) {
344 if (commentLengthApplies) {
345 if (lineLength > maxCommentLength) {
348 loc: { line: lineNumber, column: 0 },
349 messageId: "maxComment",
356 } else if (lineLength > maxLength) {
359 loc: { line: lineNumber, column: 0 },
371 //--------------------------------------------------------------------------
373 //--------------------------------------------------------------------------
376 Program: checkProgramForMaxLength