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.

quotes.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * @fileoverview A rule to choose between single and double quote marks
  3. * @author Matt DuVall <http://www.mattduvall.com/>, Brandon Payton
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Constants
  12. //------------------------------------------------------------------------------
  13. const QUOTE_SETTINGS = {
  14. double: {
  15. quote: "\"",
  16. alternateQuote: "'",
  17. description: "doublequote"
  18. },
  19. single: {
  20. quote: "'",
  21. alternateQuote: "\"",
  22. description: "singlequote"
  23. },
  24. backtick: {
  25. quote: "`",
  26. alternateQuote: "\"",
  27. description: "backtick"
  28. }
  29. };
  30. // An unescaped newline is a newline preceded by an even number of backslashes.
  31. const UNESCAPED_LINEBREAK_PATTERN = new RegExp(String.raw`(^|[^\\])(\\\\)*[${Array.from(astUtils.LINEBREAKS).join("")}]`);
  32. /**
  33. * Switches quoting of javascript string between ' " and `
  34. * escaping and unescaping as necessary.
  35. * Only escaping of the minimal set of characters is changed.
  36. * Note: escaping of newlines when switching from backtick to other quotes is not handled.
  37. * @param {string} str - A string to convert.
  38. * @returns {string} The string with changed quotes.
  39. * @private
  40. */
  41. QUOTE_SETTINGS.double.convert =
  42. QUOTE_SETTINGS.single.convert =
  43. QUOTE_SETTINGS.backtick.convert = function(str) {
  44. const newQuote = this.quote;
  45. const oldQuote = str[0];
  46. if (newQuote === oldQuote) {
  47. return str;
  48. }
  49. return newQuote + str.slice(1, -1).replace(/\\(\${|\r\n?|\n|.)|["'`]|\${|(\r\n?|\n)/g, (match, escaped, newline) => {
  50. if (escaped === oldQuote || oldQuote === "`" && escaped === "${") {
  51. return escaped; // unescape
  52. }
  53. if (match === newQuote || newQuote === "`" && match === "${") {
  54. return `\\${match}`; // escape
  55. }
  56. if (newline && oldQuote === "`") {
  57. return "\\n"; // escape newlines
  58. }
  59. return match;
  60. }) + newQuote;
  61. };
  62. const AVOID_ESCAPE = "avoid-escape";
  63. //------------------------------------------------------------------------------
  64. // Rule Definition
  65. //------------------------------------------------------------------------------
  66. module.exports = {
  67. meta: {
  68. type: "layout",
  69. docs: {
  70. description: "enforce the consistent use of either backticks, double, or single quotes",
  71. category: "Stylistic Issues",
  72. recommended: false,
  73. url: "https://eslint.org/docs/rules/quotes"
  74. },
  75. fixable: "code",
  76. schema: [
  77. {
  78. enum: ["single", "double", "backtick"]
  79. },
  80. {
  81. anyOf: [
  82. {
  83. enum: ["avoid-escape"]
  84. },
  85. {
  86. type: "object",
  87. properties: {
  88. avoidEscape: {
  89. type: "boolean"
  90. },
  91. allowTemplateLiterals: {
  92. type: "boolean"
  93. }
  94. },
  95. additionalProperties: false
  96. }
  97. ]
  98. }
  99. ]
  100. },
  101. create(context) {
  102. const quoteOption = context.options[0],
  103. settings = QUOTE_SETTINGS[quoteOption || "double"],
  104. options = context.options[1],
  105. allowTemplateLiterals = options && options.allowTemplateLiterals === true,
  106. sourceCode = context.getSourceCode();
  107. let avoidEscape = options && options.avoidEscape === true;
  108. // deprecated
  109. if (options === AVOID_ESCAPE) {
  110. avoidEscape = true;
  111. }
  112. /**
  113. * Determines if a given node is part of JSX syntax.
  114. *
  115. * This function returns `true` in the following cases:
  116. *
  117. * - `<div className="foo"></div>` ... If the literal is an attribute value, the parent of the literal is `JSXAttribute`.
  118. * - `<div>foo</div>` ... If the literal is a text content, the parent of the literal is `JSXElement`.
  119. * - `<>foo</>` ... If the literal is a text content, the parent of the literal is `JSXFragment`.
  120. *
  121. * In particular, this function returns `false` in the following cases:
  122. *
  123. * - `<div className={"foo"}></div>`
  124. * - `<div>{"foo"}</div>`
  125. *
  126. * In both cases, inside of the braces is handled as normal JavaScript.
  127. * The braces are `JSXExpressionContainer` nodes.
  128. *
  129. * @param {ASTNode} node The Literal node to check.
  130. * @returns {boolean} True if the node is a part of JSX, false if not.
  131. * @private
  132. */
  133. function isJSXLiteral(node) {
  134. return node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment";
  135. }
  136. /**
  137. * Checks whether or not a given node is a directive.
  138. * The directive is a `ExpressionStatement` which has only a string literal.
  139. * @param {ASTNode} node - A node to check.
  140. * @returns {boolean} Whether or not the node is a directive.
  141. * @private
  142. */
  143. function isDirective(node) {
  144. return (
  145. node.type === "ExpressionStatement" &&
  146. node.expression.type === "Literal" &&
  147. typeof node.expression.value === "string"
  148. );
  149. }
  150. /**
  151. * Checks whether or not a given node is a part of directive prologues.
  152. * See also: http://www.ecma-international.org/ecma-262/6.0/#sec-directive-prologues-and-the-use-strict-directive
  153. * @param {ASTNode} node - A node to check.
  154. * @returns {boolean} Whether or not the node is a part of directive prologues.
  155. * @private
  156. */
  157. function isPartOfDirectivePrologue(node) {
  158. const block = node.parent.parent;
  159. if (block.type !== "Program" && (block.type !== "BlockStatement" || !astUtils.isFunction(block.parent))) {
  160. return false;
  161. }
  162. // Check the node is at a prologue.
  163. for (let i = 0; i < block.body.length; ++i) {
  164. const statement = block.body[i];
  165. if (statement === node.parent) {
  166. return true;
  167. }
  168. if (!isDirective(statement)) {
  169. break;
  170. }
  171. }
  172. return false;
  173. }
  174. /**
  175. * Checks whether or not a given node is allowed as non backtick.
  176. * @param {ASTNode} node - A node to check.
  177. * @returns {boolean} Whether or not the node is allowed as non backtick.
  178. * @private
  179. */
  180. function isAllowedAsNonBacktick(node) {
  181. const parent = node.parent;
  182. switch (parent.type) {
  183. // Directive Prologues.
  184. case "ExpressionStatement":
  185. return isPartOfDirectivePrologue(node);
  186. // LiteralPropertyName.
  187. case "Property":
  188. case "MethodDefinition":
  189. return parent.key === node && !parent.computed;
  190. // ModuleSpecifier.
  191. case "ImportDeclaration":
  192. case "ExportNamedDeclaration":
  193. case "ExportAllDeclaration":
  194. return parent.source === node;
  195. // Others don't allow.
  196. default:
  197. return false;
  198. }
  199. }
  200. return {
  201. Literal(node) {
  202. const val = node.value,
  203. rawVal = node.raw;
  204. if (settings && typeof val === "string") {
  205. let isValid = (quoteOption === "backtick" && isAllowedAsNonBacktick(node)) ||
  206. isJSXLiteral(node) ||
  207. astUtils.isSurroundedBy(rawVal, settings.quote);
  208. if (!isValid && avoidEscape) {
  209. isValid = astUtils.isSurroundedBy(rawVal, settings.alternateQuote) && rawVal.indexOf(settings.quote) >= 0;
  210. }
  211. if (!isValid) {
  212. context.report({
  213. node,
  214. message: "Strings must use {{description}}.",
  215. data: {
  216. description: settings.description
  217. },
  218. fix(fixer) {
  219. return fixer.replaceText(node, settings.convert(node.raw));
  220. }
  221. });
  222. }
  223. }
  224. },
  225. TemplateLiteral(node) {
  226. // If backticks are expected or it's a tagged template, then this shouldn't throw an errors
  227. if (
  228. allowTemplateLiterals ||
  229. quoteOption === "backtick" ||
  230. node.parent.type === "TaggedTemplateExpression" && node === node.parent.quasi
  231. ) {
  232. return;
  233. }
  234. // A warning should be produced if the template literal only has one TemplateElement, and has no unescaped newlines.
  235. const shouldWarn = node.quasis.length === 1 && !UNESCAPED_LINEBREAK_PATTERN.test(node.quasis[0].value.raw);
  236. if (shouldWarn) {
  237. context.report({
  238. node,
  239. message: "Strings must use {{description}}.",
  240. data: {
  241. description: settings.description
  242. },
  243. fix(fixer) {
  244. if (isPartOfDirectivePrologue(node)) {
  245. /*
  246. * TemplateLiterals in a directive prologue aren't actually directives, but if they're
  247. * in the directive prologue, then fixing them might turn them into directives and change
  248. * the behavior of the code.
  249. */
  250. return null;
  251. }
  252. return fixer.replaceText(node, settings.convert(sourceCode.getText(node)));
  253. }
  254. });
  255. }
  256. }
  257. };
  258. }
  259. };