Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

max-len.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. module.exports = {
  61. meta: {
  62. type: "layout",
  63. docs: {
  64. description: "enforce a maximum line length",
  65. category: "Stylistic Issues",
  66. recommended: false,
  67. url: "https://eslint.org/docs/rules/max-len"
  68. },
  69. schema: [
  70. OPTIONS_OR_INTEGER_SCHEMA,
  71. OPTIONS_OR_INTEGER_SCHEMA,
  72. OPTIONS_SCHEMA
  73. ]
  74. },
  75. create(context) {
  76. /*
  77. * Inspired by http://tools.ietf.org/html/rfc3986#appendix-B, however:
  78. * - They're matching an entire string that we know is a URI
  79. * - We're matching part of a string where we think there *might* be a URL
  80. * - We're only concerned about URLs, as picking out any URI would cause
  81. * too many false positives
  82. * - We don't care about matching the entire URL, any small segment is fine
  83. */
  84. const URL_REGEXP = /[^:/?#]:\/\/[^?#]/;
  85. const sourceCode = context.getSourceCode();
  86. /**
  87. * Computes the length of a line that may contain tabs. The width of each
  88. * tab will be the number of spaces to the next tab stop.
  89. * @param {string} line The line.
  90. * @param {int} tabWidth The width of each tab stop in spaces.
  91. * @returns {int} The computed line length.
  92. * @private
  93. */
  94. function computeLineLength(line, tabWidth) {
  95. let extraCharacterCount = 0;
  96. line.replace(/\t/g, (match, offset) => {
  97. const totalOffset = offset + extraCharacterCount,
  98. previousTabStopOffset = tabWidth ? totalOffset % tabWidth : 0,
  99. spaceCount = tabWidth - previousTabStopOffset;
  100. extraCharacterCount += spaceCount - 1; // -1 for the replaced tab
  101. });
  102. return Array.from(line).length + extraCharacterCount;
  103. }
  104. // The options object must be the last option specified…
  105. const lastOption = context.options[context.options.length - 1];
  106. const options = typeof lastOption === "object" ? Object.create(lastOption) : {};
  107. // …but max code length…
  108. if (typeof context.options[0] === "number") {
  109. options.code = context.options[0];
  110. }
  111. // …and tabWidth can be optionally specified directly as integers.
  112. if (typeof context.options[1] === "number") {
  113. options.tabWidth = context.options[1];
  114. }
  115. const maxLength = options.code || 80,
  116. tabWidth = options.tabWidth || 4,
  117. ignoreComments = options.ignoreComments || false,
  118. ignoreStrings = options.ignoreStrings || false,
  119. ignoreTemplateLiterals = options.ignoreTemplateLiterals || false,
  120. ignoreRegExpLiterals = options.ignoreRegExpLiterals || false,
  121. ignoreTrailingComments = options.ignoreTrailingComments || options.ignoreComments || false,
  122. ignoreUrls = options.ignoreUrls || false,
  123. maxCommentLength = options.comments;
  124. let ignorePattern = options.ignorePattern || null;
  125. if (ignorePattern) {
  126. ignorePattern = new RegExp(ignorePattern);
  127. }
  128. //--------------------------------------------------------------------------
  129. // Helpers
  130. //--------------------------------------------------------------------------
  131. /**
  132. * Tells if a given comment is trailing: it starts on the current line and
  133. * extends to or past the end of the current line.
  134. * @param {string} line The source line we want to check for a trailing comment on
  135. * @param {number} lineNumber The one-indexed line number for line
  136. * @param {ASTNode} comment The comment to inspect
  137. * @returns {boolean} If the comment is trailing on the given line
  138. */
  139. function isTrailingComment(line, lineNumber, comment) {
  140. return comment &&
  141. (comment.loc.start.line === lineNumber && lineNumber <= comment.loc.end.line) &&
  142. (comment.loc.end.line > lineNumber || comment.loc.end.column === line.length);
  143. }
  144. /**
  145. * Tells if a comment encompasses the entire line.
  146. * @param {string} line The source line with a trailing comment
  147. * @param {number} lineNumber The one-indexed line number this is on
  148. * @param {ASTNode} comment The comment to remove
  149. * @returns {boolean} If the comment covers the entire line
  150. */
  151. function isFullLineComment(line, lineNumber, comment) {
  152. const start = comment.loc.start,
  153. end = comment.loc.end,
  154. isFirstTokenOnLine = !line.slice(0, comment.loc.start.column).trim();
  155. return comment &&
  156. (start.line < lineNumber || (start.line === lineNumber && isFirstTokenOnLine)) &&
  157. (end.line > lineNumber || (end.line === lineNumber && end.column === line.length));
  158. }
  159. /**
  160. * Gets the line after the comment and any remaining trailing whitespace is
  161. * stripped.
  162. * @param {string} line The source line with a trailing comment
  163. * @param {ASTNode} comment The comment to remove
  164. * @returns {string} Line without comment and trailing whitepace
  165. */
  166. function stripTrailingComment(line, comment) {
  167. // loc.column is zero-indexed
  168. return line.slice(0, comment.loc.start.column).replace(/\s+$/, "");
  169. }
  170. /**
  171. * Ensure that an array exists at [key] on `object`, and add `value` to it.
  172. *
  173. * @param {Object} object the object to mutate
  174. * @param {string} key the object's key
  175. * @param {*} value the value to add
  176. * @returns {void}
  177. * @private
  178. */
  179. function ensureArrayAndPush(object, key, value) {
  180. if (!Array.isArray(object[key])) {
  181. object[key] = [];
  182. }
  183. object[key].push(value);
  184. }
  185. /**
  186. * Retrieves an array containing all strings (" or ') in the source code.
  187. *
  188. * @returns {ASTNode[]} An array of string nodes.
  189. */
  190. function getAllStrings() {
  191. return sourceCode.ast.tokens.filter(token => (token.type === "String" ||
  192. (token.type === "JSXText" && sourceCode.getNodeByRangeIndex(token.range[0] - 1).type === "JSXAttribute")));
  193. }
  194. /**
  195. * Retrieves an array containing all template literals in the source code.
  196. *
  197. * @returns {ASTNode[]} An array of template literal nodes.
  198. */
  199. function getAllTemplateLiterals() {
  200. return sourceCode.ast.tokens.filter(token => token.type === "Template");
  201. }
  202. /**
  203. * Retrieves an array containing all RegExp literals in the source code.
  204. *
  205. * @returns {ASTNode[]} An array of RegExp literal nodes.
  206. */
  207. function getAllRegExpLiterals() {
  208. return sourceCode.ast.tokens.filter(token => token.type === "RegularExpression");
  209. }
  210. /**
  211. * A reducer to group an AST node by line number, both start and end.
  212. *
  213. * @param {Object} acc the accumulator
  214. * @param {ASTNode} node the AST node in question
  215. * @returns {Object} the modified accumulator
  216. * @private
  217. */
  218. function groupByLineNumber(acc, node) {
  219. for (let i = node.loc.start.line; i <= node.loc.end.line; ++i) {
  220. ensureArrayAndPush(acc, i, node);
  221. }
  222. return acc;
  223. }
  224. /**
  225. * Check the program for max length
  226. * @param {ASTNode} node Node to examine
  227. * @returns {void}
  228. * @private
  229. */
  230. function checkProgramForMaxLength(node) {
  231. // split (honors line-ending)
  232. const lines = sourceCode.lines,
  233. // list of comments to ignore
  234. comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];
  235. // we iterate over comments in parallel with the lines
  236. let commentsIndex = 0;
  237. const strings = getAllStrings();
  238. const stringsByLine = strings.reduce(groupByLineNumber, {});
  239. const templateLiterals = getAllTemplateLiterals();
  240. const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});
  241. const regExpLiterals = getAllRegExpLiterals();
  242. const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});
  243. lines.forEach((line, i) => {
  244. // i is zero-indexed, line numbers are one-indexed
  245. const lineNumber = i + 1;
  246. /*
  247. * if we're checking comment length; we need to know whether this
  248. * line is a comment
  249. */
  250. let lineIsComment = false;
  251. let textToMeasure;
  252. /*
  253. * We can short-circuit the comment checks if we're already out of
  254. * comments to check.
  255. */
  256. if (commentsIndex < comments.length) {
  257. let comment = null;
  258. // iterate over comments until we find one past the current line
  259. do {
  260. comment = comments[++commentsIndex];
  261. } while (comment && comment.loc.start.line <= lineNumber);
  262. // and step back by one
  263. comment = comments[--commentsIndex];
  264. if (isFullLineComment(line, lineNumber, comment)) {
  265. lineIsComment = true;
  266. textToMeasure = line;
  267. } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
  268. textToMeasure = stripTrailingComment(line, comment);
  269. } else {
  270. textToMeasure = line;
  271. }
  272. } else {
  273. textToMeasure = line;
  274. }
  275. if (ignorePattern && ignorePattern.test(textToMeasure) ||
  276. ignoreUrls && URL_REGEXP.test(textToMeasure) ||
  277. ignoreStrings && stringsByLine[lineNumber] ||
  278. ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
  279. ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
  280. ) {
  281. // ignore this line
  282. return;
  283. }
  284. const lineLength = computeLineLength(textToMeasure, tabWidth);
  285. const commentLengthApplies = lineIsComment && maxCommentLength;
  286. if (lineIsComment && ignoreComments) {
  287. return;
  288. }
  289. if (commentLengthApplies) {
  290. if (lineLength > maxCommentLength) {
  291. context.report({
  292. node,
  293. loc: { line: lineNumber, column: 0 },
  294. message: "Line {{lineNumber}} exceeds the maximum comment line length of {{maxCommentLength}}.",
  295. data: {
  296. lineNumber: i + 1,
  297. maxCommentLength
  298. }
  299. });
  300. }
  301. } else if (lineLength > maxLength) {
  302. context.report({
  303. node,
  304. loc: { line: lineNumber, column: 0 },
  305. message: "Line {{lineNumber}} exceeds the maximum line length of {{maxLength}}.",
  306. data: {
  307. lineNumber: i + 1,
  308. maxLength
  309. }
  310. });
  311. }
  312. });
  313. }
  314. //--------------------------------------------------------------------------
  315. // Public API
  316. //--------------------------------------------------------------------------
  317. return {
  318. Program: checkProgramForMaxLength
  319. };
  320. }
  321. };