max-len.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. extensionSource: {
  164. url: 'https://eslint.org/docs/rules/max-len',
  165. name: 'ESLint core'
  166. }
  167. },
  168. schema: [
  169. OPTIONS_OR_INTEGER_SCHEMA,
  170. OPTIONS_OR_INTEGER_SCHEMA,
  171. OPTIONS_SCHEMA
  172. ],
  173. messages: {
  174. max: 'This line has a length of {{lineLength}}. Maximum allowed is {{maxLength}}.',
  175. maxComment:
  176. 'This line has a comment length of {{lineLength}}. Maximum allowed is {{maxCommentLength}}.'
  177. }
  178. },
  179. /**
  180. * @param {RuleContext} context - The rule context.
  181. * @returns {RuleListener} AST event handlers.
  182. */
  183. create(context) {
  184. /*
  185. * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
  186. * - They're matching an entire string that we know is a URI
  187. * - We're matching part of a string where we think there *might* be a URL
  188. * - We're only concerned about URLs, as picking out any URI would cause
  189. * too many false positives
  190. * - We don't care about matching the entire URL, any small segment is fine
  191. */
  192. const URL_REGEXP = /[^:/?#]:\/\/[^?#]/u
  193. const sourceCode = context.getSourceCode()
  194. /** @type {Token[]} */
  195. const tokens = []
  196. /** @type {(HTMLComment | HTMLBogusComment | Comment)[]} */
  197. const comments = []
  198. /** @type {VLiteral[]} */
  199. const htmlAttributeValues = []
  200. // The options object must be the last option specified…
  201. const options = Object.assign(
  202. {},
  203. context.options[context.options.length - 1]
  204. )
  205. // …but max code length…
  206. if (typeof context.options[0] === 'number') {
  207. options.code = context.options[0]
  208. }
  209. // …and tabWidth can be optionally specified directly as integers.
  210. if (typeof context.options[1] === 'number') {
  211. options.tabWidth = context.options[1]
  212. }
  213. /** @type {number} */
  214. const scriptMaxLength = typeof options.code === 'number' ? options.code : 80
  215. /** @type {number} */
  216. const tabWidth = typeof options.tabWidth === 'number' ? options.tabWidth : 2 // default value of `vue/html-indent`
  217. /** @type {number} */
  218. const templateMaxLength =
  219. typeof options.template === 'number' ? options.template : scriptMaxLength
  220. const ignoreComments = !!options.ignoreComments
  221. const ignoreStrings = !!options.ignoreStrings
  222. const ignoreTemplateLiterals = !!options.ignoreTemplateLiterals
  223. const ignoreRegExpLiterals = !!options.ignoreRegExpLiterals
  224. const ignoreTrailingComments =
  225. !!options.ignoreTrailingComments || !!options.ignoreComments
  226. const ignoreUrls = !!options.ignoreUrls
  227. const ignoreHTMLAttributeValues = !!options.ignoreHTMLAttributeValues
  228. const ignoreHTMLTextContents = !!options.ignoreHTMLTextContents
  229. /** @type {number} */
  230. const maxCommentLength = options.comments
  231. /** @type {RegExp} */
  232. let ignorePattern = options.ignorePattern || null
  233. if (ignorePattern) {
  234. ignorePattern = new RegExp(ignorePattern, 'u')
  235. }
  236. /**
  237. * Retrieves an array containing all strings (" or ') in the source code.
  238. *
  239. * @returns {Token[]} An array of string nodes.
  240. */
  241. function getAllStrings() {
  242. return tokens.filter(
  243. (token) =>
  244. token.type === 'String' ||
  245. (token.type === 'JSXText' &&
  246. sourceCode.getNodeByRangeIndex(token.range[0] - 1).type ===
  247. 'JSXAttribute')
  248. )
  249. }
  250. /**
  251. * Retrieves an array containing all template literals in the source code.
  252. *
  253. * @returns {Token[]} An array of template literal nodes.
  254. */
  255. function getAllTemplateLiterals() {
  256. return tokens.filter((token) => token.type === 'Template')
  257. }
  258. /**
  259. * Retrieves an array containing all RegExp literals in the source code.
  260. *
  261. * @returns {Token[]} An array of RegExp literal nodes.
  262. */
  263. function getAllRegExpLiterals() {
  264. return tokens.filter((token) => token.type === 'RegularExpression')
  265. }
  266. /**
  267. * Retrieves an array containing all HTML texts in the source code.
  268. *
  269. * @returns {Token[]} An array of HTML text nodes.
  270. */
  271. function getAllHTMLTextContents() {
  272. return tokens.filter((token) => token.type === 'HTMLText')
  273. }
  274. /**
  275. * Check the program for max length
  276. * @param {Program} node Node to examine
  277. * @returns {void}
  278. * @private
  279. */
  280. function checkProgramForMaxLength(node) {
  281. const programNode = node
  282. const templateBody = node.templateBody
  283. // setup tokens
  284. const scriptTokens = sourceCode.ast.tokens
  285. const scriptComments = sourceCode.getAllComments()
  286. if (sourceCode.parserServices.getTemplateBodyTokenStore && templateBody) {
  287. const tokenStore = sourceCode.parserServices.getTemplateBodyTokenStore()
  288. const templateTokens = tokenStore.getTokens(templateBody, {
  289. includeComments: true
  290. })
  291. if (templateBody.range[0] < programNode.range[0]) {
  292. tokens.push(...templateTokens, ...scriptTokens)
  293. } else {
  294. tokens.push(...scriptTokens, ...templateTokens)
  295. }
  296. } else {
  297. tokens.push(...scriptTokens)
  298. }
  299. if (ignoreComments || maxCommentLength || ignoreTrailingComments) {
  300. // list of comments to ignore
  301. if (templateBody) {
  302. if (templateBody.range[0] < programNode.range[0]) {
  303. comments.push(...templateBody.comments, ...scriptComments)
  304. } else {
  305. comments.push(...scriptComments, ...templateBody.comments)
  306. }
  307. } else {
  308. comments.push(...scriptComments)
  309. }
  310. }
  311. /** @type {Range | undefined} */
  312. let scriptLinesRange
  313. if (scriptTokens.length > 0) {
  314. scriptLinesRange =
  315. scriptComments.length > 0
  316. ? [
  317. Math.min(
  318. scriptTokens[0].loc.start.line,
  319. scriptComments[0].loc.start.line
  320. ),
  321. Math.max(
  322. scriptTokens[scriptTokens.length - 1].loc.end.line,
  323. scriptComments[scriptComments.length - 1].loc.end.line
  324. )
  325. ]
  326. : [
  327. scriptTokens[0].loc.start.line,
  328. scriptTokens[scriptTokens.length - 1].loc.end.line
  329. ]
  330. } else if (scriptComments.length > 0) {
  331. scriptLinesRange = [
  332. scriptComments[0].loc.start.line,
  333. scriptComments[scriptComments.length - 1].loc.end.line
  334. ]
  335. }
  336. const templateLinesRange = templateBody && [
  337. templateBody.loc.start.line,
  338. templateBody.loc.end.line
  339. ]
  340. // split (honors line-ending)
  341. const lines = sourceCode.lines
  342. const strings = getAllStrings()
  343. const stringsByLine = groupByLineNumber(strings)
  344. const templateLiterals = getAllTemplateLiterals()
  345. const templateLiteralsByLine = groupByLineNumber(templateLiterals)
  346. const regExpLiterals = getAllRegExpLiterals()
  347. const regExpLiteralsByLine = groupByLineNumber(regExpLiterals)
  348. const htmlAttributeValuesByLine = groupByLineNumber(htmlAttributeValues)
  349. const htmlTextContents = getAllHTMLTextContents()
  350. const htmlTextContentsByLine = groupByLineNumber(htmlTextContents)
  351. const commentsByLine = groupByLineNumber(comments)
  352. for (const [i, line] of lines.entries()) {
  353. // i is zero-indexed, line numbers are one-indexed
  354. const lineNumber = i + 1
  355. const inScript =
  356. scriptLinesRange &&
  357. scriptLinesRange[0] <= lineNumber &&
  358. lineNumber <= scriptLinesRange[1]
  359. const inTemplate =
  360. templateLinesRange &&
  361. templateLinesRange[0] <= lineNumber &&
  362. lineNumber <= templateLinesRange[1]
  363. // check if line is inside a script or template.
  364. if (!inScript && !inTemplate) {
  365. // out of range.
  366. continue
  367. }
  368. const maxLength = Math.max(
  369. inScript ? scriptMaxLength : 0,
  370. inTemplate ? templateMaxLength : 0
  371. )
  372. if (
  373. (ignoreStrings && stringsByLine[lineNumber]) ||
  374. (ignoreTemplateLiterals && templateLiteralsByLine[lineNumber]) ||
  375. (ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]) ||
  376. (ignoreHTMLAttributeValues &&
  377. htmlAttributeValuesByLine[lineNumber]) ||
  378. (ignoreHTMLTextContents && htmlTextContentsByLine[lineNumber])
  379. ) {
  380. // ignore this line
  381. continue
  382. }
  383. /*
  384. * if we're checking comment length; we need to know whether this
  385. * line is a comment
  386. */
  387. let lineIsComment = false
  388. let textToMeasure
  389. /*
  390. * comments to check.
  391. */
  392. if (commentsByLine[lineNumber]) {
  393. const commentList = [...commentsByLine[lineNumber]]
  394. let comment = commentList.pop() || null
  395. if (isFullLineComment(line, lineNumber, comment)) {
  396. lineIsComment = true
  397. textToMeasure = line
  398. } else if (
  399. ignoreTrailingComments &&
  400. isTrailingComment(line, lineNumber, comment)
  401. ) {
  402. textToMeasure = stripTrailingComment(line, comment)
  403. // ignore multiple trailing comments in the same line
  404. comment = commentList.pop() || null
  405. while (isTrailingComment(textToMeasure, lineNumber, comment)) {
  406. textToMeasure = stripTrailingComment(textToMeasure, comment)
  407. }
  408. } else {
  409. textToMeasure = line
  410. }
  411. } else {
  412. textToMeasure = line
  413. }
  414. if (
  415. (ignorePattern && ignorePattern.test(textToMeasure)) ||
  416. (ignoreUrls && URL_REGEXP.test(textToMeasure))
  417. ) {
  418. // ignore this line
  419. continue
  420. }
  421. const lineLength = computeLineLength(textToMeasure, tabWidth)
  422. const commentLengthApplies = lineIsComment && maxCommentLength
  423. if (lineIsComment && ignoreComments) {
  424. continue
  425. }
  426. if (commentLengthApplies) {
  427. if (lineLength > maxCommentLength) {
  428. context.report({
  429. node,
  430. loc: { line: lineNumber, column: 0 },
  431. messageId: 'maxComment',
  432. data: {
  433. lineLength,
  434. maxCommentLength
  435. }
  436. })
  437. }
  438. } else if (lineLength > maxLength) {
  439. context.report({
  440. node,
  441. loc: { line: lineNumber, column: 0 },
  442. messageId: 'max',
  443. data: {
  444. lineLength,
  445. maxLength
  446. }
  447. })
  448. }
  449. }
  450. }
  451. return utils.compositingVisitors(
  452. utils.defineTemplateBodyVisitor(context, {
  453. /** @param {VLiteral} node */
  454. 'VAttribute[directive=false] > VLiteral'(node) {
  455. htmlAttributeValues.push(node)
  456. }
  457. }),
  458. {
  459. 'Program:exit'(node) {
  460. checkProgramForMaxLength(node)
  461. }
  462. }
  463. )
  464. }
  465. }