项目原始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.
 
 
 
 

373 linhas
12 KiB

  1. /**
  2. * @fileoverview Source code for spaced-comments rule
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. const lodash = require("lodash");
  7. const astUtils = require("../ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Helpers
  10. //------------------------------------------------------------------------------
  11. /**
  12. * Escapes the control characters of a given string.
  13. * @param {string} s - A string to escape.
  14. * @returns {string} An escaped string.
  15. */
  16. function escape(s) {
  17. return `(?:${lodash.escapeRegExp(s)})`;
  18. }
  19. /**
  20. * Escapes the control characters of a given string.
  21. * And adds a repeat flag.
  22. * @param {string} s - A string to escape.
  23. * @returns {string} An escaped string.
  24. */
  25. function escapeAndRepeat(s) {
  26. return `${escape(s)}+`;
  27. }
  28. /**
  29. * Parses `markers` option.
  30. * If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
  31. * @param {string[]} [markers] - A marker list.
  32. * @returns {string[]} A marker list.
  33. */
  34. function parseMarkersOption(markers) {
  35. // `*` is a marker for JSDoc comments.
  36. if (markers.indexOf("*") === -1) {
  37. return markers.concat("*");
  38. }
  39. return markers;
  40. }
  41. /**
  42. * Creates string pattern for exceptions.
  43. * Generated pattern:
  44. *
  45. * 1. A space or an exception pattern sequence.
  46. *
  47. * @param {string[]} exceptions - An exception pattern list.
  48. * @returns {string} A regular expression string for exceptions.
  49. */
  50. function createExceptionsPattern(exceptions) {
  51. let pattern = "";
  52. /*
  53. * A space or an exception pattern sequence.
  54. * [] ==> "\s"
  55. * ["-"] ==> "(?:\s|\-+$)"
  56. * ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
  57. * ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
  58. */
  59. if (exceptions.length === 0) {
  60. // a space.
  61. pattern += "\\s";
  62. } else {
  63. // a space or...
  64. pattern += "(?:\\s|";
  65. if (exceptions.length === 1) {
  66. // a sequence of the exception pattern.
  67. pattern += escapeAndRepeat(exceptions[0]);
  68. } else {
  69. // a sequence of one of the exception patterns.
  70. pattern += "(?:";
  71. pattern += exceptions.map(escapeAndRepeat).join("|");
  72. pattern += ")";
  73. }
  74. pattern += `(?:$|[${Array.from(astUtils.LINEBREAKS).join("")}]))`;
  75. }
  76. return pattern;
  77. }
  78. /**
  79. * Creates RegExp object for `always` mode.
  80. * Generated pattern for beginning of comment:
  81. *
  82. * 1. First, a marker or nothing.
  83. * 2. Next, a space or an exception pattern sequence.
  84. *
  85. * @param {string[]} markers - A marker list.
  86. * @param {string[]} exceptions - An exception pattern list.
  87. * @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
  88. */
  89. function createAlwaysStylePattern(markers, exceptions) {
  90. let pattern = "^";
  91. /*
  92. * A marker or nothing.
  93. * ["*"] ==> "\*?"
  94. * ["*", "!"] ==> "(?:\*|!)?"
  95. * ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
  96. */
  97. if (markers.length === 1) {
  98. // the marker.
  99. pattern += escape(markers[0]);
  100. } else {
  101. // one of markers.
  102. pattern += "(?:";
  103. pattern += markers.map(escape).join("|");
  104. pattern += ")";
  105. }
  106. pattern += "?"; // or nothing.
  107. pattern += createExceptionsPattern(exceptions);
  108. return new RegExp(pattern);
  109. }
  110. /**
  111. * Creates RegExp object for `never` mode.
  112. * Generated pattern for beginning of comment:
  113. *
  114. * 1. First, a marker or nothing (captured).
  115. * 2. Next, a space or a tab.
  116. *
  117. * @param {string[]} markers - A marker list.
  118. * @returns {RegExp} A RegExp object for `never` mode.
  119. */
  120. function createNeverStylePattern(markers) {
  121. const pattern = `^(${markers.map(escape).join("|")})?[ \t]+`;
  122. return new RegExp(pattern);
  123. }
  124. //------------------------------------------------------------------------------
  125. // Rule Definition
  126. //------------------------------------------------------------------------------
  127. module.exports = {
  128. meta: {
  129. docs: {
  130. description: "enforce consistent spacing after the `//` or `/*` in a comment",
  131. category: "Stylistic Issues",
  132. recommended: false,
  133. url: "https://eslint.org/docs/rules/spaced-comment"
  134. },
  135. fixable: "whitespace",
  136. schema: [
  137. {
  138. enum: ["always", "never"]
  139. },
  140. {
  141. type: "object",
  142. properties: {
  143. exceptions: {
  144. type: "array",
  145. items: {
  146. type: "string"
  147. }
  148. },
  149. markers: {
  150. type: "array",
  151. items: {
  152. type: "string"
  153. }
  154. },
  155. line: {
  156. type: "object",
  157. properties: {
  158. exceptions: {
  159. type: "array",
  160. items: {
  161. type: "string"
  162. }
  163. },
  164. markers: {
  165. type: "array",
  166. items: {
  167. type: "string"
  168. }
  169. }
  170. },
  171. additionalProperties: false
  172. },
  173. block: {
  174. type: "object",
  175. properties: {
  176. exceptions: {
  177. type: "array",
  178. items: {
  179. type: "string"
  180. }
  181. },
  182. markers: {
  183. type: "array",
  184. items: {
  185. type: "string"
  186. }
  187. },
  188. balanced: {
  189. type: "boolean"
  190. }
  191. },
  192. additionalProperties: false
  193. }
  194. },
  195. additionalProperties: false
  196. }
  197. ]
  198. },
  199. create(context) {
  200. const sourceCode = context.getSourceCode();
  201. // Unless the first option is never, require a space
  202. const requireSpace = context.options[0] !== "never";
  203. /*
  204. * Parse the second options.
  205. * If markers don't include `"*"`, it's added automatically for JSDoc
  206. * comments.
  207. */
  208. const config = context.options[1] || {};
  209. const balanced = config.block && config.block.balanced;
  210. const styleRules = ["block", "line"].reduce((rule, type) => {
  211. const markers = parseMarkersOption(config[type] && config[type].markers || config.markers || []);
  212. const exceptions = config[type] && config[type].exceptions || config.exceptions || [];
  213. const endNeverPattern = "[ \t]+$";
  214. // Create RegExp object for valid patterns.
  215. rule[type] = {
  216. beginRegex: requireSpace ? createAlwaysStylePattern(markers, exceptions) : createNeverStylePattern(markers),
  217. endRegex: balanced && requireSpace ? new RegExp(`${createExceptionsPattern(exceptions)}$`) : new RegExp(endNeverPattern),
  218. hasExceptions: exceptions.length > 0,
  219. markers: new RegExp(`^(${markers.map(escape).join("|")})`)
  220. };
  221. return rule;
  222. }, {});
  223. /**
  224. * Reports a beginning spacing error with an appropriate message.
  225. * @param {ASTNode} node - A comment node to check.
  226. * @param {string} message - An error message to report.
  227. * @param {Array} match - An array of match results for markers.
  228. * @param {string} refChar - Character used for reference in the error message.
  229. * @returns {void}
  230. */
  231. function reportBegin(node, message, match, refChar) {
  232. const type = node.type.toLowerCase(),
  233. commentIdentifier = type === "block" ? "/*" : "//";
  234. context.report({
  235. node,
  236. fix(fixer) {
  237. const start = node.range[0];
  238. let end = start + 2;
  239. if (requireSpace) {
  240. if (match) {
  241. end += match[0].length;
  242. }
  243. return fixer.insertTextAfterRange([start, end], " ");
  244. }
  245. end += match[0].length;
  246. return fixer.replaceTextRange([start, end], commentIdentifier + (match[1] ? match[1] : ""));
  247. },
  248. message,
  249. data: { refChar }
  250. });
  251. }
  252. /**
  253. * Reports an ending spacing error with an appropriate message.
  254. * @param {ASTNode} node - A comment node to check.
  255. * @param {string} message - An error message to report.
  256. * @param {string} match - An array of the matched whitespace characters.
  257. * @returns {void}
  258. */
  259. function reportEnd(node, message, match) {
  260. context.report({
  261. node,
  262. fix(fixer) {
  263. if (requireSpace) {
  264. return fixer.insertTextAfterRange([node.range[0], node.range[1] - 2], " ");
  265. }
  266. const end = node.range[1] - 2,
  267. start = end - match[0].length;
  268. return fixer.replaceTextRange([start, end], "");
  269. },
  270. message
  271. });
  272. }
  273. /**
  274. * Reports a given comment if it's invalid.
  275. * @param {ASTNode} node - a comment node to check.
  276. * @returns {void}
  277. */
  278. function checkCommentForSpace(node) {
  279. const type = node.type.toLowerCase(),
  280. rule = styleRules[type],
  281. commentIdentifier = type === "block" ? "/*" : "//";
  282. // Ignores empty comments.
  283. if (node.value.length === 0) {
  284. return;
  285. }
  286. const beginMatch = rule.beginRegex.exec(node.value);
  287. const endMatch = rule.endRegex.exec(node.value);
  288. // Checks.
  289. if (requireSpace) {
  290. if (!beginMatch) {
  291. const hasMarker = rule.markers.exec(node.value);
  292. const marker = hasMarker ? commentIdentifier + hasMarker[0] : commentIdentifier;
  293. if (rule.hasExceptions) {
  294. reportBegin(node, "Expected exception block, space or tab after '{{refChar}}' in comment.", hasMarker, marker);
  295. } else {
  296. reportBegin(node, "Expected space or tab after '{{refChar}}' in comment.", hasMarker, marker);
  297. }
  298. }
  299. if (balanced && type === "block" && !endMatch) {
  300. reportEnd(node, "Expected space or tab before '*/' in comment.");
  301. }
  302. } else {
  303. if (beginMatch) {
  304. if (!beginMatch[1]) {
  305. reportBegin(node, "Unexpected space or tab after '{{refChar}}' in comment.", beginMatch, commentIdentifier);
  306. } else {
  307. reportBegin(node, "Unexpected space or tab after marker ({{refChar}}) in comment.", beginMatch, beginMatch[1]);
  308. }
  309. }
  310. if (balanced && type === "block" && endMatch) {
  311. reportEnd(node, "Unexpected space or tab before '*/' in comment.", endMatch);
  312. }
  313. }
  314. }
  315. return {
  316. Program() {
  317. const comments = sourceCode.getAllComments();
  318. comments.filter(token => token.type !== "Shebang").forEach(checkCommentForSpace);
  319. }
  320. };
  321. }
  322. };