source: imaps-frontend/node_modules/eslint/lib/linter/config-comment-parser.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 6.1 KB
Line 
1/**
2 * @fileoverview Config Comment Parser
3 * @author Nicholas C. Zakas
4 */
5
6/* eslint class-methods-use-this: off -- Methods desired on instance */
7"use strict";
8
9//------------------------------------------------------------------------------
10// Requirements
11//------------------------------------------------------------------------------
12
13const levn = require("levn"),
14 {
15 Legacy: {
16 ConfigOps
17 }
18 } = require("@eslint/eslintrc/universal"),
19 {
20 directivesPattern
21 } = require("../shared/directives");
22
23const debug = require("debug")("eslint:config-comment-parser");
24
25//------------------------------------------------------------------------------
26// Typedefs
27//------------------------------------------------------------------------------
28
29/** @typedef {import("../shared/types").LintMessage} LintMessage */
30
31//------------------------------------------------------------------------------
32// Public Interface
33//------------------------------------------------------------------------------
34
35/**
36 * Object to parse ESLint configuration comments inside JavaScript files.
37 * @name ConfigCommentParser
38 */
39module.exports = class ConfigCommentParser {
40
41 /**
42 * Parses a list of "name:string_value" or/and "name" options divided by comma or
43 * whitespace. Used for "global" and "exported" comments.
44 * @param {string} string The string to parse.
45 * @param {Comment} comment The comment node which has the string.
46 * @returns {Object} Result map object of names and string values, or null values if no value was provided
47 */
48 parseStringConfig(string, comment) {
49 debug("Parsing String config");
50
51 const items = {};
52
53 // Collapse whitespace around `:` and `,` to make parsing easier
54 const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1");
55
56 trimmedString.split(/\s|,+/u).forEach(name => {
57 if (!name) {
58 return;
59 }
60
61 // value defaults to null (if not provided), e.g: "foo" => ["foo", null]
62 const [key, value = null] = name.split(":");
63
64 items[key] = { value, comment };
65 });
66 return items;
67 }
68
69 /**
70 * Parses a JSON-like config.
71 * @param {string} string The string to parse.
72 * @param {Object} location Start line and column of comments for potential error message.
73 * @returns {({success: true, config: Object}|{success: false, error: LintMessage})} Result map object
74 */
75 parseJsonConfig(string, location) {
76 debug("Parsing JSON config");
77
78 let items = {};
79
80 // Parses a JSON-like comment by the same way as parsing CLI option.
81 try {
82 items = levn.parse("Object", string) || {};
83
84 // Some tests say that it should ignore invalid comments such as `/*eslint no-alert:abc*/`.
85 // Also, commaless notations have invalid severity:
86 // "no-alert: 2 no-console: 2" --> {"no-alert": "2 no-console: 2"}
87 // Should ignore that case as well.
88 if (ConfigOps.isEverySeverityValid(items)) {
89 return {
90 success: true,
91 config: items
92 };
93 }
94 } catch {
95
96 debug("Levn parsing failed; falling back to manual parsing.");
97
98 // ignore to parse the string by a fallback.
99 }
100
101 /*
102 * Optionator cannot parse commaless notations.
103 * But we are supporting that. So this is a fallback for that.
104 */
105 items = {};
106 const normalizedString = string.replace(/([-a-zA-Z0-9/]+):/gu, "\"$1\":").replace(/(\]|[0-9])\s+(?=")/u, "$1,");
107
108 try {
109 items = JSON.parse(`{${normalizedString}}`);
110 } catch (ex) {
111 debug("Manual parsing failed.");
112
113 return {
114 success: false,
115 error: {
116 ruleId: null,
117 fatal: true,
118 severity: 2,
119 message: `Failed to parse JSON from '${normalizedString}': ${ex.message}`,
120 line: location.start.line,
121 column: location.start.column + 1,
122 nodeType: null
123 }
124 };
125
126 }
127
128 return {
129 success: true,
130 config: items
131 };
132 }
133
134 /**
135 * Parses a config of values separated by comma.
136 * @param {string} string The string to parse.
137 * @returns {Object} Result map of values and true values
138 */
139 parseListConfig(string) {
140 debug("Parsing list config");
141
142 const items = {};
143
144 string.split(",").forEach(name => {
145 const trimmedName = name.trim().replace(/^(?<quote>['"]?)(?<ruleId>.*)\k<quote>$/us, "$<ruleId>");
146
147 if (trimmedName) {
148 items[trimmedName] = true;
149 }
150 });
151 return items;
152 }
153
154 /**
155 * Extract the directive and the justification from a given directive comment and trim them.
156 * @param {string} value The comment text to extract.
157 * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification.
158 */
159 extractDirectiveComment(value) {
160 const match = /\s-{2,}\s/u.exec(value);
161
162 if (!match) {
163 return { directivePart: value.trim(), justificationPart: "" };
164 }
165
166 const directive = value.slice(0, match.index).trim();
167 const justification = value.slice(match.index + match[0].length).trim();
168
169 return { directivePart: directive, justificationPart: justification };
170 }
171
172 /**
173 * Parses a directive comment into directive text and value.
174 * @param {Comment} comment The comment node with the directive to be parsed.
175 * @returns {{directiveText: string, directiveValue: string}} The directive text and value.
176 */
177 parseDirective(comment) {
178 const { directivePart } = this.extractDirectiveComment(comment.value);
179 const match = directivesPattern.exec(directivePart);
180 const directiveText = match[1];
181 const directiveValue = directivePart.slice(match.index + directiveText.length);
182
183 return { directiveText, directiveValue };
184 }
185};
Note: See TracBrowser for help on using the repository browser.