max-len.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /**
  2. * @author Yosuke Ota
  3. * @fileoverview Rule to check for max length on a line of Vue file.
  4. */
  5. 'use strict'
  6. const utils = require('../utils')
  7. const OPTIONS_SCHEMA = {
  8. type: 'object',
  9. properties: {
  10. code: {
  11. type: 'integer',
  12. minimum: 0
  13. },
  14. template: {
  15. type: 'integer',
  16. minimum: 0
  17. },
  18. comments: {
  19. type: 'integer',
  20. minimum: 0
  21. },
  22. tabWidth: {
  23. type: 'integer',
  24. minimum: 0
  25. },
  26. ignorePattern: {
  27. type: 'string'
  28. },
  29. ignoreComments: {
  30. type: 'boolean'
  31. },
  32. ignoreTrailingComments: {
  33. type: 'boolean'
  34. },
  35. ignoreUrls: {
  36. type: 'boolean'
  37. },
  38. ignoreStrings: {
  39. type: 'boolean'
  40. },
  41. ignoreTemplateLiterals: {
  42. type: 'boolean'
  43. },
  44. ignoreRegExpLiterals: {
  45. type: 'boolean'
  46. },
  47. ignoreHTMLAttributeValues: {
  48. type: 'boolean'
  49. },
  50. ignoreHTMLTextContents: {
  51. type: 'boolean'
  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. * Computes the length of a line that may contain tabs. The width of each
  67. * tab will be the number of spaces to the next tab stop.
  68. * @param {string} line The line.
  69. * @param {number} tabWidth The width of each tab stop in spaces.
  70. * @returns {number} The computed line length.
  71. * @private
  72. */
  73. function computeLineLength(line, tabWidth) {
  74. let extraCharacterCount = 0
  75. const re = /\t/gu
  76. let ret
  77. while ((ret = re.exec(line))) {
  78. const offset = ret.index
  79. const totalOffset = offset + extraCharacterCount
  80. const previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0
  81. const spaceCount = tabWidth - previousTabStopOffset
  82. extraCharacterCount += spaceCount - 1 // -1 for the replaced tab
  83. }
  84. return [...line].length + extraCharacterCount
  85. }
  86. /**
  87. * Tells if a given comment is trailing: it starts on the current line and
  88. * extends to or past the end of the current line.
  89. * @param {string} line The source line we want to check for a trailing comment on
  90. * @param {number} lineNumber The one-indexed line number for line
  91. * @param {Token | null} comment The comment to inspect
  92. * @returns {comment is Token} If the comment is trailing on the given line
  93. */
  94. function isTrailingComment(line, lineNumber, comment) {
  95. return Boolean(
  96. comment &&
  97. comment.loc.start.line === lineNumber &&
  98. lineNumber <= comment.loc.end.line &&
  99. (comment.loc.end.line > lineNumber ||
  100. comment.loc.end.column === line.length)
  101. )
  102. }
  103. /**
  104. * Tells if a comment encompasses the entire line.
  105. * @param {string} line The source line with a trailing comment
  106. * @param {number} lineNumber The one-indexed line number this is on
  107. * @param {Token | null} comment The comment to remove
  108. * @returns {boolean} If the comment covers the entire line
  109. */
  110. function isFullLineComment(line, lineNumber, comment) {
  111. if (!comment) {
  112. return false
  113. }
  114. const start = comment.loc.start
  115. const end = comment.loc.end
  116. const isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim()
  117. return (
  118. comment &&
  119. (start.line < lineNumber ||
  120. (start.line === lineNumber && isFirstTokenOnLine)) &&
  121. (end.line > lineNumber ||
  122. (end.line === lineNumber && end.column === line.length))
  123. )
  124. }
  125. /**
  126. * Gets the line after the comment and any remaining trailing whitespace is
  127. * stripped.
  128. * @param {string} line The source line with a trailing comment
  129. * @param {Token} comment The comment to remove
  130. * @returns {string} Line without comment and trailing whitepace
  131. */
  132. function stripTrailingComment(line, comment) {
  133. // loc.column is zero-indexed
  134. return line.slice(0, comment.loc.start.column).replace(/\s+$/u, '')
  135. }
  136. /**
  137. * Group AST nodes by line number, both start and end.
  138. *
  139. * @param {Token[]} nodes the AST nodes in question
  140. * @returns { { [key: number]: Token[] } } the grouped nodes
  141. * @private
  142. */
  143. function groupByLineNumber(nodes) {
  144. /** @type { { [key: number]: Token[] } } */
  145. const grouped = {}
  146. for (const node of nodes) {
  147. for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
  148. if (!Array.isArray(grouped[i])) {
  149. grouped[i] = []
  150. }
  151. grouped[i].push(node)
  152. }
  153. }
  154. return grouped
  155. }
  156. module.exports = {
  157. meta: {
  158. type: 'layout',
  159. docs: {
  160. description: 'enforce a maximum line length in `.vue` files',
  161. categories: undefined,
  162. url: 'https://eslint.vuejs.org/rules/max-len.html',
  163. extensionRule: true,
  164. coreRuleUrl: 'https://eslint.org/docs/rules/max-len'
  165. },
  166. schema: [
  167. OPTIONS_OR_INTEGER_SCHEMA,
  168. OPTIONS_OR_INTEGER_SCHEMA,
  169. OPTIONS_SCHEMA
  170. ],
  171. messages: {
  172. max: 'This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.',
  173. maxComment:
  174. 'This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.'
  175. }
  176. },
  177. /**
  178. * @param {RuleContext} context - The rule context.
  179. * @returns {RuleListener} AST event handlers.
  180. */
  181. create(context) {
  182. /*
  183. * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
  184. * - They're matching an entire string that we know is a URI
  185. * - We're matching part of a string where we think there *might* be a URL
  186. * - We're only concerned about URLs, as picking out any URI would cause
  187. * too many false positives
  188. * - We don't care about matching the entire URL, any small segment is fine
  189. */
  190. const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u
  191. const sourceCode = context.getSourceCode()
  192. /** @type {Token[]} */
  193. const tokens = []
  194. /** @type {(HTMLComment | HTMLBogusComment | Comment)[]} */
  195. const comments = []
  196. /** @type {VLiteral[]} */
  197. const htmlAttributeValues = []
  198. // The options object must be the last option specified…
  199. const options = Object.assign(
  200. {},
  201. context.options[context.options.length - 1]
  202. )
  203. // …but max code length…
  204. if (typeof context.options[0] === 'number') {
  205. options.code = context.options[0]
  206. }
  207. // …and tabWidth can be optionally specified directly as integers.
  208. if (typeof context.options[1] === 'number') {
  209. options.tabWidth = context.options[1]
  210. }
  211. /** @type {number} */
  212. const scriptMaxLength = typeof options.code === 'number' ? options.code : 80
  213. /** @type {number} */
  214. const tabWidth = typeof options.tabWidth === 'number' ? options.tabWidth : 2 // default value of `vue/html-indent`
  215. /** @type {number} */
  216. const templateMaxLength =
  217. typeof options.template === 'number' ? options.template : scriptMaxLength
  218. const ignoreComments = !!options.ignoreComments
  219. const ignoreStrings = !!options.ignoreStrings
  220. const ignoreTemplateLiterals = !!options.ignoreTemplateLiterals
  221. const ignoreRegExpLiterals = !!options.ignoreRegExpLiterals
  222. const ignoreTrailingComments =
  223. !!options.ignoreTrailingComments || !!options.ignoreComments
  224. const ignoreUrls = !!options.ignoreUrls
  225. const ignoreHTMLAttributeValues = !!options.ignoreHTMLAttributeValues
  226. const ignoreHTMLTextContents = !!options.ignoreHTMLTextContents
  227. /** @type {number} */
  228. const maxCommentLength = options.comments
  229. /** @type {RegExp} */
  230. let ignorePattern = options.ignorePattern || null
  231. if (ignorePattern) {
  232. ignorePattern = new RegExp(ignorePattern, 'u')
  233. }
  234. /**
  235. * Retrieves an array containing all strings (" or ') in the source code.
  236. *
  237. * @returns {Token[]} An array of string nodes.
  238. */
  239. function getAllStrings() {
  240. return tokens.filter(
  241. (token) =>
  242. token.type === 'String' ||
  243. (token.type === 'JSXText' &&
  244. sourceCode.getNodeByRangeIndex(token.range[0] - 1).type ===
  245. 'JSXAttribute')
  246. )
  247. }
  248. /**
  249. * Retrieves an array containing all template literals in the source code.
  250. *
  251. * @returns {Token[]} An array of template literal nodes.
  252. */
  253. function getAllTemplateLiterals() {
  254. return tokens.filter((token) => token.type === 'Template')
  255. }
  256. /**
  257. * Retrieves an array containing all RegExp literals in the source code.
  258. *
  259. * @returns {Token[]} An array of RegExp literal nodes.
  260. */
  261. function getAllRegExpLiterals() {
  262. return tokens.filter((token) => token.type === 'RegularExpression')
  263. }
  264. /**
  265. * Retrieves an array containing all HTML texts in the source code.
  266. *
  267. * @returns {Token[]} An array of HTML text nodes.
  268. */
  269. function getAllHTMLTextContents() {
  270. return tokens.filter((token) => token.type === 'HTMLText')
  271. }
  272. /**
  273. * Check the program for max length
  274. * @param {Program} node Node to examine
  275. * @returns {void}
  276. * @private
  277. */
  278. function checkProgramForMaxLength(node) {
  279. const programNode = node
  280. const templateBody = node.templateBody
  281. // setup tokens
  282. const scriptTokens = sourceCode.ast.tokens
  283. const scriptComments = sourceCode.getAllComments()
  284. if (context.parserServices.getTemplateBodyTokenStore && templateBody) {
  285. const tokenStore = context.parserServices.getTemplateBodyTokenStore()
  286. const templateTokens = tokenStore.getTokens(templateBody, {
  287. includeComments: true
  288. })
  289. if (templateBody.range[0] < programNode.range[0]) {
  290. tokens.push(...templateTokens, ...scriptTokens)
  291. } else {
  292. tokens.push(...scriptTokens, ...templateTokens)
  293. }
  294. } else {
  295. tokens.push(...scriptTokens)
  296. }
  297. if (ignoreComments || maxCommentLength || ignoreTrailingComments) {
  298. // list of comments to ignore
  299. if (templateBody) {
  300. if (templateBody.range[0] < programNode.range[0]) {
  301. comments.push(...templateBody.comments, ...scriptComments)
  302. } else {
  303. comments.push(...scriptComments, ...templateBody.comments)
  304. }
  305. } else {
  306. comments.push(...scriptComments)
  307. }
  308. }
  309. /** @type {Range | undefined} */
  310. let scriptLinesRange
  311. if (scriptTokens.length > 0) {
  312. scriptLinesRange =
  313. scriptComments.length > 0
  314. ? [
  315. Math.min(
  316. scriptTokens[0].loc.start.line,
  317. scriptComments[0].loc.start.line
  318. ),
  319. Math.max(
  320. scriptTokens[scriptTokens.length - 1].loc.end.line,
  321. scriptComments[scriptComments.length - 1].loc.end.line
  322. )
  323. ]
  324. : [
  325. scriptTokens[0].loc.start.line,
  326. scriptTokens[scriptTokens.length - 1].loc.end.line
  327. ]
  328. } else if (scriptComments.length > 0) {
  329. scriptLinesRange = [
  330. scriptComments[0].loc.start.line,
  331. scriptComments[scriptComments.length - 1].loc.end.line
  332. ]
  333. }
  334. const templateLinesRange = templateBody && [
  335. templateBody.loc.start.line,
  336. templateBody.loc.end.line
  337. ]
  338. // split (honors line-ending)
  339. const lines = sourceCode.lines
  340. const strings = getAllStrings()
  341. const stringsByLine = groupByLineNumber(strings)
  342. const templateLiterals = getAllTemplateLiterals()
  343. const templateLiteralsByLine = groupByLineNumber(templateLiterals)
  344. const regExpLiterals = getAllRegExpLiterals()
  345. const regExpLiteralsByLine = groupByLineNumber(regExpLiterals)
  346. const htmlAttributeValuesByLine = groupByLineNumber(htmlAttributeValues)
  347. const htmlTextContents = getAllHTMLTextContents()
  348. const htmlTextContentsByLine = groupByLineNumber(htmlTextContents)
  349. const commentsByLine = groupByLineNumber(comments)
  350. for (const [i, line] of lines.entries()) {
  351. // i is zero-indexed, line numbers are one-indexed
  352. const lineNumber = i + 1
  353. const inScript =
  354. scriptLinesRange &&
  355. scriptLinesRange[0] <= lineNumber &&
  356. lineNumber <= scriptLinesRange[1]
  357. const inTemplate =
  358. templateLinesRange &&
  359. templateLinesRange[0] <= lineNumber &&
  360. lineNumber <= templateLinesRange[1]
  361. // check if line is inside a script or template.
  362. if (!inScript && !inTemplate) {
  363. // out of range.
  364. continue
  365. }
  366. const maxLength = Math.max(
  367. inScript ? scriptMaxLength : 0,
  368. inTemplate ? templateMaxLength : 0
  369. )
  370. if (
  371. (ignoreStrings && stringsByLine[lineNumber]) ||
  372. (ignoreTemplateLiterals && templateLiteralsByLine[lineNumber]) ||
  373. (ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]) ||
  374. (ignoreHTMLAttributeValues &&
  375. htmlAttributeValuesByLine[lineNumber]) ||
  376. (ignoreHTMLTextContents && htmlTextContentsByLine[lineNumber])
  377. ) {
  378. // ignore this line
  379. continue
  380. }
  381. /*
  382. * if we're checking comment length; we need to know whether this
  383. * line is a comment
  384. */
  385. let lineIsComment = false
  386. let textToMeasure
  387. /*
  388. * comments to check.
  389. */
  390. if (commentsByLine[lineNumber]) {
  391. const commentList = [...commentsByLine[lineNumber]]
  392. let comment = commentList.pop() || null
  393. if (isFullLineComment(line, lineNumber, comment)) {
  394. lineIsComment = true
  395. textToMeasure = line
  396. } else if (
  397. ignoreTrailingComments &&
  398. isTrailingComment(line, lineNumber, comment)
  399. ) {
  400. textToMeasure = stripTrailingComment(line, comment)
  401. // ignore multiple trailing comments in the same line
  402. comment = commentList.pop() || null
  403. while (isTrailingComment(textToMeasure, lineNumber, comment)) {
  404. textToMeasure = stripTrailingComment(textToMeasure, comment)
  405. }
  406. } else {
  407. textToMeasure = line
  408. }
  409. } else {
  410. textToMeasure = line
  411. }
  412. if (
  413. (ignorePattern && ignorePattern.test(textToMeasure)) ||
  414. (ignoreUrls && URL_REGEXP.test(textToMeasure))
  415. ) {
  416. // ignore this line
  417. continue
  418. }
  419. const lineLength = computeLineLength(textToMeasure, tabWidth)
  420. const commentLengthApplies = lineIsComment && maxCommentLength
  421. if (lineIsComment && ignoreComments) {
  422. continue
  423. }
  424. if (commentLengthApplies) {
  425. if (lineLength > maxCommentLength) {
  426. context.report({
  427. node,
  428. loc: { line: lineNumber, column: 0 },
  429. messageId: 'maxComment',
  430. data: {
  431. lineLength,
  432. maxCommentLength
  433. }
  434. })
  435. }
  436. } else if (lineLength > maxLength) {
  437. context.report({
  438. node,
  439. loc: { line: lineNumber, column: 0 },
  440. messageId: 'max',
  441. data: {
  442. lineLength,
  443. maxLength
  444. }
  445. })
  446. }
  447. }
  448. }
  449. return utils.compositingVisitors(
  450. utils.defineTemplateBodyVisitor(context, {
  451. /** @param {VLiteral} node */
  452. 'VAttribute[directive=false] > VLiteral'(node) {
  453. htmlAttributeValues.push(node)
  454. }
  455. }),
  456. {
  457. 'Program:exit'(node) {
  458. checkProgramForMaxLength(node)
  459. }
  460. }
  461. )
  462. }
  463. }