config-comment-parser.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /**
  2. * @fileoverview Config Comment Parser
  3. * @author Nicholas C. Zakas
  4. */
  5. /* eslint class-methods-use-this: off -- Methods desired on instance */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const levn = require("levn"),
  11. {
  12. Legacy: {
  13. ConfigOps
  14. }
  15. } = require("@eslint/eslintrc/universal");
  16. const debug = require("debug")("eslint:config-comment-parser");
  17. //------------------------------------------------------------------------------
  18. // Public Interface
  19. //------------------------------------------------------------------------------
  20. /**
  21. * Object to parse ESLint configuration comments inside JavaScript files.
  22. * @name ConfigCommentParser
  23. */
  24. module.exports = class ConfigCommentParser {
  25. /**
  26. * Parses a list of "name:string_value" or/and "name" options divided by comma or
  27. * whitespace. Used for "global" and "exported" comments.
  28. * @param {string} string The string to parse.
  29. * @param {Comment} comment The comment node which has the string.
  30. * @returns {Object} Result map object of names and string values, or null values if no value was provided
  31. */
  32. parseStringConfig(string, comment) {
  33. debug("Parsing String config");
  34. const items = {};
  35. // Collapse whitespace around `:` and `,` to make parsing easier
  36. const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1");
  37. trimmedString.split(/\s|,+/u).forEach(name => {
  38. if (!name) {
  39. return;
  40. }
  41. // value defaults to null (if not provided), e.g: "foo" => ["foo", null]
  42. const [key, value = null] = name.split(":");
  43. items[key] = { value, comment };
  44. });
  45. return items;
  46. }
  47. /**
  48. * Parses a JSON-like config.
  49. * @param {string} string The string to parse.
  50. * @param {Object} location Start line and column of comments for potential error message.
  51. * @returns {({success: true, config: Object}|{success: false, error: Problem})} Result map object
  52. */
  53. parseJsonConfig(string, location) {
  54. debug("Parsing JSON config");
  55. let items = {};
  56. // Parses a JSON-like comment by the same way as parsing CLI option.
  57. try {
  58. items = levn.parse("Object", string) || {};
  59. // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
  60. // Also, commaless notations have invalid severity:
  61. // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
  62. // Should ignore that case as well.
  63. if (ConfigOps.isEverySeverityValid(items)) {
  64. return {
  65. success: true,
  66. config: items
  67. };
  68. }
  69. } catch {
  70. debug("Levn parsing failed; falling back to manual parsing.");
  71. // ignore to parse the string by a fallback.
  72. }
  73. /*
  74. * Optionator cannot parse commaless notations.
  75. * But we are supporting that. So this is a fallback for that.
  76. */
  77. items = {};
  78. const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,");
  79. try {
  80. items = JSON.parse(`{${normalizedString}}`);
  81. } catch (ex) {
  82. debug("Manual parsing failed.");
  83. return {
  84. success: false,
  85. error: {
  86. ruleId: null,
  87. fatal: true,
  88. severity: 2,
  89. message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`,
  90. line: location.start.line,
  91. column: location.start.column + 1
  92. }
  93. };
  94. }
  95. return {
  96. success: true,
  97. config: items
  98. };
  99. }
  100. /**
  101. * Parses a config of values separated by comma.
  102. * @param {string} string The string to parse.
  103. * @returns {Object} Result map of values and true values
  104. */
  105. parseListConfig(string) {
  106. debug("Parsing list config");
  107. const items = {};
  108. string.split(",").forEach(name => {
  109. const trimmedName = name.trim();
  110. if (trimmedName) {
  111. items[trimmedName] = true;
  112. }
  113. });
  114. return items;
  115. }
  116. };