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