项目原始demo,不改动
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
Este repositório está arquivado. Pode ver ficheiros e cloná-lo, mas não pode fazer envios ou lançar questões ou pedidos de integração.
 
 
 
 

296 linhas
14 KiB

  1. /**
  2. * @fileoverview enforce a particular style for multiline comments
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. const astUtils = require("../ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. docs: {
  13. description: "enforce a particular style for multiline comments",
  14. category: "Stylistic Issues",
  15. recommended: false,
  16. url: "https://eslint.org/docs/rules/multiline-comment-style"
  17. },
  18. fixable: "whitespace",
  19. schema: [{ enum: ["starred-block", "separate-lines", "bare-block"] }]
  20. },
  21. create(context) {
  22. const sourceCode = context.getSourceCode();
  23. const option = context.options[0] || "starred-block";
  24. const EXPECTED_BLOCK_ERROR = "Expected a block comment instead of consecutive line comments.";
  25. const START_NEWLINE_ERROR = "Expected a linebreak after '/*'.";
  26. const END_NEWLINE_ERROR = "Expected a linebreak before '*/'.";
  27. const MISSING_STAR_ERROR = "Expected a '*' at the start of this line.";
  28. const ALIGNMENT_ERROR = "Expected this line to be aligned with the start of the comment.";
  29. const EXPECTED_LINES_ERROR = "Expected multiple line comments instead of a block comment.";
  30. //----------------------------------------------------------------------
  31. // Helpers
  32. //----------------------------------------------------------------------
  33. /**
  34. * Gets a list of comment lines in a group
  35. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  36. * @returns {string[]} A list of comment lines
  37. */
  38. function getCommentLines(commentGroup) {
  39. if (commentGroup[0].type === "Line") {
  40. return commentGroup.map(comment => comment.value);
  41. }
  42. return commentGroup[0].value
  43. .split(astUtils.LINEBREAK_MATCHER)
  44. .map(line => line.replace(/^\s*\*?/, ""));
  45. }
  46. /**
  47. * Converts a comment into starred-block form
  48. * @param {Token} firstComment The first comment of the group being converted
  49. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  50. * @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
  51. */
  52. function convertToStarredBlock(firstComment, commentLinesList) {
  53. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  54. const starredLines = commentLinesList.map(line => `${initialOffset} *${line}`);
  55. return `\n${starredLines.join("\n")}\n${initialOffset} `;
  56. }
  57. /**
  58. * Converts a comment into separate-line form
  59. * @param {Token} firstComment The first comment of the group being converted
  60. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  61. * @returns {string} A representation of the comment value in separate-line form
  62. */
  63. function convertToSeparateLines(firstComment, commentLinesList) {
  64. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  65. const separateLines = commentLinesList.map(line => `// ${line.trim()}`);
  66. return separateLines.join(`\n${initialOffset}`);
  67. }
  68. /**
  69. * Converts a comment into bare-block form
  70. * @param {Token} firstComment The first comment of the group being converted
  71. * @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
  72. * @returns {string} A representation of the comment value in bare-block form
  73. */
  74. function convertToBlock(firstComment, commentLinesList) {
  75. const initialOffset = sourceCode.text.slice(firstComment.range[0] - firstComment.loc.start.column, firstComment.range[0]);
  76. const blockLines = commentLinesList.map(line => line.trim());
  77. return `/* ${blockLines.join(`\n${initialOffset} `)} */`;
  78. }
  79. /**
  80. * Check a comment is JSDoc form
  81. * @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
  82. * @returns {boolean} if commentGroup is JSDoc form, return true
  83. */
  84. function isJSDoc(commentGroup) {
  85. const lines = commentGroup[0].value.split(astUtils.LINEBREAK_MATCHER);
  86. return commentGroup[0].type === "Block" &&
  87. /^\*\s*$/.test(lines[0]) &&
  88. lines.slice(1, -1).every(line => /^\s* /.test(line)) &&
  89. /^\s*$/.test(lines[lines.length - 1]);
  90. }
  91. /**
  92. * Each method checks a group of comments to see if it's valid according to the given option.
  93. * @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
  94. * block comment or multiple line comments.
  95. * @returns {void}
  96. */
  97. const commentGroupCheckers = {
  98. "starred-block"(commentGroup) {
  99. const commentLines = getCommentLines(commentGroup);
  100. if (commentLines.some(value => value.includes("*/"))) {
  101. return;
  102. }
  103. if (commentGroup.length > 1) {
  104. context.report({
  105. loc: {
  106. start: commentGroup[0].loc.start,
  107. end: commentGroup[commentGroup.length - 1].loc.end
  108. },
  109. message: EXPECTED_BLOCK_ERROR,
  110. fix(fixer) {
  111. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  112. const starredBlock = `/*${convertToStarredBlock(commentGroup[0], commentLines)}*/`;
  113. return commentLines.some(value => value.startsWith("/"))
  114. ? null
  115. : fixer.replaceTextRange(range, starredBlock);
  116. }
  117. });
  118. } else {
  119. const block = commentGroup[0];
  120. const lines = block.value.split(astUtils.LINEBREAK_MATCHER);
  121. const expectedLinePrefix = `${sourceCode.text.slice(block.range[0] - block.loc.start.column, block.range[0])} *`;
  122. if (!/^\*?\s*$/.test(lines[0])) {
  123. const start = block.value.startsWith("*") ? block.range[0] + 1 : block.range[0];
  124. context.report({
  125. loc: {
  126. start: block.loc.start,
  127. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  128. },
  129. message: START_NEWLINE_ERROR,
  130. fix: fixer => fixer.insertTextAfterRange([start, start + 2], `\n${expectedLinePrefix}`)
  131. });
  132. }
  133. if (!/^\s*$/.test(lines[lines.length - 1])) {
  134. context.report({
  135. loc: {
  136. start: { line: block.loc.end.line, column: block.loc.end.column - 2 },
  137. end: block.loc.end
  138. },
  139. message: END_NEWLINE_ERROR,
  140. fix: fixer => fixer.replaceTextRange([block.range[1] - 2, block.range[1]], `\n${expectedLinePrefix}/`)
  141. });
  142. }
  143. for (let lineNumber = block.loc.start.line + 1; lineNumber <= block.loc.end.line; lineNumber++) {
  144. const lineText = sourceCode.lines[lineNumber - 1];
  145. if (!lineText.startsWith(expectedLinePrefix)) {
  146. context.report({
  147. loc: {
  148. start: { line: lineNumber, column: 0 },
  149. end: { line: lineNumber, column: sourceCode.lines[lineNumber - 1].length }
  150. },
  151. message: /^\s*\*/.test(lineText)
  152. ? ALIGNMENT_ERROR
  153. : MISSING_STAR_ERROR,
  154. fix(fixer) {
  155. const lineStartIndex = sourceCode.getIndexFromLoc({ line: lineNumber, column: 0 });
  156. const linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length;
  157. const commentStartIndex = lineStartIndex + linePrefixLength;
  158. const replacementText = lineNumber === block.loc.end.line || lineText.length === linePrefixLength
  159. ? expectedLinePrefix
  160. : `${expectedLinePrefix} `;
  161. return fixer.replaceTextRange([lineStartIndex, commentStartIndex], replacementText);
  162. }
  163. });
  164. }
  165. }
  166. }
  167. },
  168. "separate-lines"(commentGroup) {
  169. if (!isJSDoc(commentGroup) && commentGroup[0].type === "Block") {
  170. const commentLines = getCommentLines(commentGroup);
  171. const block = commentGroup[0];
  172. const tokenAfter = sourceCode.getTokenAfter(block, { includeComments: true });
  173. if (tokenAfter && block.loc.end.line === tokenAfter.loc.start.line) {
  174. return;
  175. }
  176. context.report({
  177. loc: {
  178. start: block.loc.start,
  179. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  180. },
  181. message: EXPECTED_LINES_ERROR,
  182. fix(fixer) {
  183. return fixer.replaceText(block, convertToSeparateLines(block, commentLines.filter(line => line)));
  184. }
  185. });
  186. }
  187. },
  188. "bare-block"(commentGroup) {
  189. if (!isJSDoc(commentGroup)) {
  190. const commentLines = getCommentLines(commentGroup);
  191. // disallows consecutive line comments in favor of using a block comment.
  192. if (commentGroup[0].type === "Line" && commentLines.length > 1 &&
  193. !commentLines.some(value => value.includes("*/"))) {
  194. context.report({
  195. loc: {
  196. start: commentGroup[0].loc.start,
  197. end: commentGroup[commentGroup.length - 1].loc.end
  198. },
  199. message: EXPECTED_BLOCK_ERROR,
  200. fix(fixer) {
  201. const range = [commentGroup[0].range[0], commentGroup[commentGroup.length - 1].range[1]];
  202. const block = convertToBlock(commentGroup[0], commentLines.filter(line => line));
  203. return fixer.replaceTextRange(range, block);
  204. }
  205. });
  206. }
  207. // prohibits block comments from having a * at the beginning of each line.
  208. if (commentGroup[0].type === "Block") {
  209. const block = commentGroup[0];
  210. const lines = block.value.split(astUtils.LINEBREAK_MATCHER).filter(line => line.trim());
  211. if (lines.length > 0 && lines.every(line => /^\s*\*/.test(line))) {
  212. context.report({
  213. loc: {
  214. start: block.loc.start,
  215. end: { line: block.loc.start.line, column: block.loc.start.column + 2 }
  216. },
  217. message: EXPECTED_BLOCK_ERROR,
  218. fix(fixer) {
  219. return fixer.replaceText(block, convertToBlock(block, commentLines.filter(line => line)));
  220. }
  221. });
  222. }
  223. }
  224. }
  225. }
  226. };
  227. //----------------------------------------------------------------------
  228. // Public
  229. //----------------------------------------------------------------------
  230. return {
  231. Program() {
  232. return sourceCode.getAllComments()
  233. .filter(comment => comment.type !== "Shebang")
  234. .filter(comment => !astUtils.COMMENTS_IGNORE_PATTERN.test(comment.value))
  235. .filter(comment => {
  236. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  237. return !tokenBefore || tokenBefore.loc.end.line < comment.loc.start.line;
  238. })
  239. .reduce((commentGroups, comment, index, commentList) => {
  240. const tokenBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
  241. if (
  242. comment.type === "Line" &&
  243. index && commentList[index - 1].type === "Line" &&
  244. tokenBefore && tokenBefore.loc.end.line === comment.loc.start.line - 1 &&
  245. tokenBefore === commentList[index - 1]
  246. ) {
  247. commentGroups[commentGroups.length - 1].push(comment);
  248. } else {
  249. commentGroups.push([comment]);
  250. }
  251. return commentGroups;
  252. }, [])
  253. .filter(commentGroup => !(commentGroup.length === 1 && commentGroup[0].loc.start.line === commentGroup[0].loc.end.line))
  254. .forEach(commentGroupCheckers[option]);
  255. }
  256. };
  257. }
  258. };