@sap/eslint-plugin-cds 2.4.1 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -2
- package/lib/api/index.js +9 -8
- package/lib/conf/all.js +21 -0
- package/lib/conf/index.js +22 -0
- package/lib/conf/recommended.js +18 -0
- package/lib/constants.js +10 -8
- package/lib/index.js +11 -32
- package/lib/parser.js +158 -7
- package/lib/rules/assoc2many-ambiguous-key.js +21 -38
- package/lib/rules/auth-no-empty-restrictions.js +13 -21
- package/lib/rules/auth-use-requires.js +15 -15
- package/lib/rules/auth-valid-restrict-grant.js +71 -34
- package/lib/rules/auth-valid-restrict-keys.js +22 -16
- package/lib/rules/auth-valid-restrict-to.js +71 -27
- package/lib/rules/auth-valid-restrict-where.js +24 -15
- package/lib/rules/index.js +26 -0
- package/lib/rules/latest-cds-version.js +8 -7
- package/lib/rules/min-node-version.js +10 -9
- package/lib/rules/no-db-keywords.js +16 -15
- package/lib/rules/no-dollar-prefixed-names.js +9 -7
- package/lib/rules/no-join-on-draft-enabled-entities.js +9 -24
- package/lib/rules/require-2many-oncond.js +9 -14
- package/lib/rules/sql-cast-suggestion.js +6 -20
- package/lib/rules/start-elements-lowercase.js +5 -8
- package/lib/rules/start-entities-uppercase.js +8 -11
- package/lib/rules/valid-csv-header.js +66 -66
- package/lib/{api/lint.d.ts → types.d.ts} +4 -7
- package/lib/utils/Cache.js +33 -0
- package/lib/utils/Colors.js +9 -0
- package/lib/utils/createRule.js +304 -0
- package/lib/utils/createRuleDocs.js +361 -0
- package/lib/utils/{fuzzySearch.js → findFuzzy.js} +0 -2
- package/lib/utils/genDocs.js +363 -0
- package/lib/utils/getConfigPath.js +33 -0
- package/lib/utils/getConfiguredFileTypes.js +10 -0
- package/lib/utils/getFileExtensions.js +8 -0
- package/lib/utils/isConfiguredFileType.js +20 -0
- package/lib/utils/jsonc.js +1 -1
- package/lib/utils/jsoncParser.js +1 -0
- package/lib/utils/rules.js +112 -1041
- package/lib/utils/runRuleTester.js +111 -0
- package/package.json +4 -4
- package/lib/processor.js +0 -50
- package/lib/utils/helpers.js +0 -94
- package/lib/utils/model.js +0 -393
- package/lib/utils/ruleHelpers.js +0 -199
- package/lib/utils/ruleTester.js +0 -78
- package/lib/utils/validate.js +0 -36
package/lib/utils/rules.js
CHANGED
|
@@ -1,1042 +1,113 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*/
|
|
1
|
+
const SEP = "[,;\t]";
|
|
2
|
+
const EOL = "\\r?\\n";
|
|
4
3
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
function
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const configPath = !Cache.has("test") ? loadConfigPath(filePath) : path.dirname(filePath);
|
|
116
|
-
let sourcecode = context.getSourceCode();
|
|
117
|
-
const code = sourcecode.getText(node) || Cache.get(`file:${filePath}`);
|
|
118
|
-
if (code) {
|
|
119
|
-
sourcecode = new SourceCode(code, getAST(code));
|
|
120
|
-
}
|
|
121
|
-
const options = context.options;
|
|
122
|
-
const id = context.id;
|
|
123
|
-
return {
|
|
124
|
-
_context: context,
|
|
125
|
-
report: module.exports.reportProxy(context.report),
|
|
126
|
-
cds: module.exports.cdsProxy(cds, { code, filePath, configPath, id, options }),
|
|
127
|
-
id,
|
|
128
|
-
code,
|
|
129
|
-
sourcecode,
|
|
130
|
-
options,
|
|
131
|
-
filePath,
|
|
132
|
-
configPath,
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Wrapper for ESLint's Rule creator:
|
|
138
|
-
* https://eslint.org/docs/developer-guide/working-with-rules
|
|
139
|
-
* - Must follow the ESLint prescribed convention for all rule exports
|
|
140
|
-
* - ESLint uses 'create' function to traverse its AST nodes
|
|
141
|
-
* - Since we do not work with an AST for cds models, a dummy 'Programm'
|
|
142
|
-
* node is used as an entry point
|
|
143
|
-
* - For all ESLint rules, we have two entry points for additional checks:
|
|
144
|
-
* 1. Before ESLint's report via context.report()
|
|
145
|
-
* (see getProxyReport())
|
|
146
|
-
* - More eslint-like API
|
|
147
|
-
* - More convenience re error reports
|
|
148
|
-
* @param {CDSRuleSpec} spec
|
|
149
|
-
* @returns {RuleModule}
|
|
150
|
-
*/
|
|
151
|
-
function createRule(spec) {
|
|
152
|
-
const { meta, create } = spec;
|
|
153
|
-
|
|
154
|
-
if (!meta.type) meta.type = DEFAULT_RULE_TYPE;
|
|
155
|
-
if (!meta.severity) meta.severity = DEFAULT_RULE_SEVERITY;
|
|
156
|
-
if (meta.docs && !meta.docs.category) meta.docs.category = DEFAULT_RULE_CATEGORY;
|
|
157
|
-
|
|
158
|
-
return {
|
|
159
|
-
meta,
|
|
160
|
-
create: (context) => ({
|
|
161
|
-
Program: function (node) {
|
|
162
|
-
const cdscontext = addCDSContext(context, node, meta);
|
|
163
|
-
const lintWithCDSLinter = isValidFile(cdscontext.filePath, 'FILES');
|
|
164
|
-
|
|
165
|
-
if (Cache.has("test") ||
|
|
166
|
-
(!Cache.has(`errRootModel`) && (lintWithCDSLinter && createRuleReports(cdscontext)))
|
|
167
|
-
) {
|
|
168
|
-
try {
|
|
169
|
-
const { report, ...ruleDescriptors } = cdscontext;
|
|
170
|
-
const handlers = create({ ...ruleDescriptors, report: (r) => report(r) });
|
|
171
|
-
|
|
172
|
-
// Report descriptors with fake visitor 'all'
|
|
173
|
-
// Used for environment rules and rules which require another compiled model
|
|
174
|
-
// (i.e. sql or odata)
|
|
175
|
-
if (handlers.all) {
|
|
176
|
-
let reportDescriptor = handlers.all();
|
|
177
|
-
doReport(cdscontext, reportDescriptor);
|
|
178
|
-
} else {
|
|
179
|
-
// TODO: Use external address
|
|
180
|
-
// Report descriptors with visitors using using `any.is()`
|
|
181
|
-
// https://pages.github.tools.sap/cap/docs/node.js/cds-reflect
|
|
182
|
-
if (cdscontext.cds.model) {
|
|
183
|
-
cdscontext.cds.model.forall((d) =>
|
|
184
|
-
Object.entries(handlers)
|
|
185
|
-
.filter(([type, lazy]) => d.is(type))
|
|
186
|
-
.forEach(([lazy, handler]) => doReport(cdscontext, handler(d), d))
|
|
187
|
-
);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
if (Cache.has(`errRootModel`)) {
|
|
191
|
-
reportCompilationErr(meta, node, cdscontext, Cache.get('errRootModel'));
|
|
192
|
-
}
|
|
193
|
-
} catch (err) {
|
|
194
|
-
// Report errors in ESLint style
|
|
195
|
-
if (err.messages) {
|
|
196
|
-
// Always show model compile errors
|
|
197
|
-
reportCompilationErr(meta, node, cdscontext, err);
|
|
198
|
-
} else {
|
|
199
|
-
// Thrown errors are only shown on console with --debug
|
|
200
|
-
reportErr(meta, node, cdscontext, err);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
} else {
|
|
204
|
-
recycleRuleReports(cdscontext);
|
|
205
|
-
}
|
|
206
|
-
},
|
|
207
|
-
}),
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
function createRuleReports(cdscontext) {
|
|
212
|
-
const { filePath, configPath, code } = cdscontext;
|
|
213
|
-
if (isNewConfigPath(configPath)) {
|
|
214
|
-
module.exports.Cache.set("configpath", configPath);
|
|
215
|
-
module.exports.Cache.remove("envReports");
|
|
216
|
-
}
|
|
217
|
-
const isInModel = isFileInModel(filePath, configPath);
|
|
218
|
-
const hasModel = Cache.has(`model:${configPath}`);
|
|
219
|
-
const isFileChanged = isInModel && hasFileChanged(code, filePath, configPath);
|
|
220
|
-
const isModelRefFile = filePath === Cache.get(`initModel:${configPath}`);
|
|
221
|
-
return (!isInModel ||
|
|
222
|
-
(isInModel && hasModel && isModelRefFile) ||
|
|
223
|
-
(isInModel && hasModel && !isModelRefFile && isFileChanged)
|
|
224
|
-
)
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function recycleRuleReports(cdscontext) {
|
|
228
|
-
const { filePath, id, sourcecode } = cdscontext;
|
|
229
|
-
if (Cache.has(`reportsRootModel:${filePath}:${id}`)) {
|
|
230
|
-
const lintReports = Cache.get(`reportsRootModel:${filePath}:${id}`);
|
|
231
|
-
Array.from(lintReports).forEach(report => {
|
|
232
|
-
let suggestions = [];
|
|
233
|
-
if (report.suggest) {
|
|
234
|
-
const { fix, ...rest } = report.suggest;
|
|
235
|
-
suggestions = report.suggest.forEach(s => (s.fix) ? { fix: (fixer) => s.fix(fixer, sourcecode), ...rest} : report.suggest);
|
|
236
|
-
}
|
|
237
|
-
report.suggest = suggestions;
|
|
238
|
-
})
|
|
239
|
-
if (lintReports) doReport(cdscontext, Array.from(lintReports));
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Checks whether a lint rule has been disabled by eslint-disable
|
|
245
|
-
* comments at a given location
|
|
246
|
-
* @param entry lint report
|
|
247
|
-
* @param cdscontext cds context object
|
|
248
|
-
* @param rules all availabe rules
|
|
249
|
-
* @returns boolean
|
|
250
|
-
*/
|
|
251
|
-
|
|
252
|
-
function isRuleDisabled(entry, cdscontext) {
|
|
253
|
-
let isDisabled = false;
|
|
254
|
-
if (entry.loc && entry.loc.start) {
|
|
255
|
-
const line = entry.loc.start.line;
|
|
256
|
-
if (cdscontext) {
|
|
257
|
-
const rulesDisabled = _getDisabled(cdscontext.code, cdscontext.sourcecode, line);
|
|
258
|
-
const id = cdscontext.id;
|
|
259
|
-
isDisabled = line && id in rulesDisabled && rulesDisabled[id] === "off";
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
return isDisabled;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Turns rules "on" or "off" for given line according to eslint-disable
|
|
267
|
-
* comments:
|
|
268
|
-
* 1. Reads code string and extracts a list of comments (in order)
|
|
269
|
-
* 2. Initiates rulesDisabled array with all rules "on" by default
|
|
270
|
-
* 3. Switches rules "off" (or "on" again) based on disable comment
|
|
271
|
-
* @param code current code
|
|
272
|
-
* @param sourcecode source code object to get index from
|
|
273
|
-
* @param line current code line to analyze
|
|
274
|
-
* @returns rules dictionary with rules being either 'on' and 'off'
|
|
275
|
-
*/
|
|
276
|
-
function _getDisabled(code, sourcecode, line) {
|
|
277
|
-
const listDisabled = [];
|
|
278
|
-
let { listEnvRules, listModelRules, listRules } = Cache.get("rulesInfo");
|
|
279
|
-
const rulesDisabled = listRules.reduce((o, key) => ({ ...o, [key]: "on" }), {});
|
|
280
|
-
let matches = [];
|
|
281
|
-
if (code) {
|
|
282
|
-
matches = [...code.matchAll(REGEX_COMMENTS)];
|
|
283
|
-
if (matches.length > 0) {
|
|
284
|
-
matches.forEach((match) => {
|
|
285
|
-
if (match) {
|
|
286
|
-
const index = match.index;
|
|
287
|
-
match = match[0];
|
|
288
|
-
if (match.includes("*/")) {
|
|
289
|
-
match = match.split("*/")[0].replace("/*", "");
|
|
290
|
-
} else if (match.includes("//")) {
|
|
291
|
-
match = match.split("//")[1];
|
|
292
|
-
}
|
|
293
|
-
if (match) {
|
|
294
|
-
match = match.trim();
|
|
295
|
-
}
|
|
296
|
-
["disable", "enable"].forEach((keyword) => {
|
|
297
|
-
const loc = sourcecode.getLocFromIndex(index);
|
|
298
|
-
const disableType = match.split(" ")[0];
|
|
299
|
-
let disableRules = match.split(`${disableType} `)[1];
|
|
300
|
-
disableRules = disableRules
|
|
301
|
-
? disableRules.split(",").map((rule) => rule.trim())
|
|
302
|
-
: listEnvRules.concat(listModelRules).map((rule) => `@sap/cds/${rule}`);
|
|
303
|
-
let comment = {};
|
|
304
|
-
if ([`eslint-${keyword}`, `eslint-${keyword}-line`, `eslint-${keyword}-next-line`].includes(disableType)) {
|
|
305
|
-
comment = disableType.includes("-next-line")
|
|
306
|
-
? {
|
|
307
|
-
lineComment: loc.line,
|
|
308
|
-
lineDisabled: loc.line + 1,
|
|
309
|
-
rules: disableRules,
|
|
310
|
-
type: keyword,
|
|
311
|
-
}
|
|
312
|
-
: {
|
|
313
|
-
lineComment: loc.line,
|
|
314
|
-
lineDisabled: loc.line,
|
|
315
|
-
rules: disableRules,
|
|
316
|
-
type: keyword,
|
|
317
|
-
};
|
|
318
|
-
if (!disableType.includes("-line")) {
|
|
319
|
-
comment.lineDisabled = "EOF";
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
listDisabled.push(comment);
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
});
|
|
326
|
-
for (const el of listDisabled.filter(
|
|
327
|
-
(d) => d.lineComment > line && (d.lineDisabled === "EOF" || d.lineDisabled === line)
|
|
328
|
-
)) {
|
|
329
|
-
if (el.lineDisabled === "EOF") {
|
|
330
|
-
el.lineDisabled = getLastLine(code);
|
|
331
|
-
}
|
|
332
|
-
if (el.rules) {
|
|
333
|
-
el.rules.forEach((rule) => {
|
|
334
|
-
if (el.type === "disable") {
|
|
335
|
-
rulesDisabled[rule] = "off";
|
|
336
|
-
} else if (el.type === "enable") {
|
|
337
|
-
rulesDisabled[rule] = "on";
|
|
338
|
-
}
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
return rulesDisabled;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
module.exports = {
|
|
348
|
-
/**
|
|
349
|
-
* Gets value for a given key in allowed keys of ESLint's meta data
|
|
350
|
-
* @param {string} text meta object from rule
|
|
351
|
-
* @param {string} key key to get value for
|
|
352
|
-
* @returns Value for given key
|
|
353
|
-
*/
|
|
354
|
-
getKeyFromMeta: function (text, key) {
|
|
355
|
-
const regexQuote = new RegExp(`${key}:[\\s]+[\\', \\\`, \\"]`, "gm");
|
|
356
|
-
const matchQuote = regexQuote.exec(text);
|
|
357
|
-
if (matchQuote) {
|
|
358
|
-
const quote = matchQuote[0].slice(-1);
|
|
359
|
-
const exprStart = `${key}:[\\s]+\\${quote}`;
|
|
360
|
-
const exprEnd = `(\\${quote},,?)`;
|
|
361
|
-
const regexKey = new RegExp(`${exprStart}[\\s\\S]*?${exprEnd}`, "gm");
|
|
362
|
-
const matchKey = regexKey.exec(text);
|
|
363
|
-
if (matchKey) {
|
|
364
|
-
const regexStart = new RegExp(`${exprStart}`, "gm");
|
|
365
|
-
const regexEnd = new RegExp(`${exprEnd}`, "gm");
|
|
366
|
-
return matchKey[0]
|
|
367
|
-
.replace(regexStart, "")
|
|
368
|
-
.replace(regexEnd, "")
|
|
369
|
-
.replace("fixable:", "")
|
|
370
|
-
.replace(/\\/gm, "")
|
|
371
|
-
.trim();
|
|
372
|
-
} else {
|
|
373
|
-
return "";
|
|
374
|
-
}
|
|
375
|
-
} else {
|
|
376
|
-
const regexBoolean = new RegExp(`${key}:[\\s]+true[\\s]?,`, "gm");
|
|
377
|
-
const matchBoolean = regexBoolean.exec(text);
|
|
378
|
-
if (matchBoolean) {
|
|
379
|
-
if (matchBoolean[0].includes("true,")) {
|
|
380
|
-
return true;
|
|
381
|
-
} else {
|
|
382
|
-
return false;
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
return "";
|
|
386
|
-
}
|
|
387
|
-
},
|
|
388
|
-
|
|
389
|
-
getPackageVersion: function (registry) {
|
|
390
|
-
let version;
|
|
391
|
-
let result;
|
|
392
|
-
try {
|
|
393
|
-
result = cp
|
|
394
|
-
.execSync(`npm show @sap/eslint-plugin-cds --@sap:registry=${registry} --json`, {
|
|
395
|
-
cwd: process.cwd(),
|
|
396
|
-
shell: IS_WIN,
|
|
397
|
-
stdio: "pipe",
|
|
398
|
-
})
|
|
399
|
-
.toString();
|
|
400
|
-
} catch (err) {
|
|
401
|
-
console.err(`Failed to connect to ${registry} - check your connection and try again.`);
|
|
402
|
-
exit(0);
|
|
403
|
-
}
|
|
404
|
-
version = JSON.parse(result)["version"];
|
|
405
|
-
if (!version) {
|
|
406
|
-
console.err(`Failed to get latest plugin version from ${registry} - check your connection and try again.`);
|
|
407
|
-
exit(0);
|
|
408
|
-
}
|
|
409
|
-
return version;
|
|
410
|
-
},
|
|
411
|
-
|
|
412
|
-
/**
|
|
413
|
-
* Gets value for a given key in allowed keys for input of runRuleTester api
|
|
414
|
-
* @param {string} text test input for ruleTester
|
|
415
|
-
* @param {string} key key to get value for
|
|
416
|
-
* @returns Value for given key
|
|
417
|
-
*/
|
|
418
|
-
getKeyFromTest: function (text, key) {
|
|
419
|
-
let result = "";
|
|
420
|
-
if (["root", "rule", "filename", "parser"].includes(key)) {
|
|
421
|
-
const regexTestKey = new RegExp(`${key}:.*$`, "gm");
|
|
422
|
-
const matchTestKey = regexTestKey.exec(text);
|
|
423
|
-
if (matchTestKey) {
|
|
424
|
-
const quote = matchTestKey[0].replace(",", "").slice(-1);
|
|
425
|
-
const regexTestValue = new RegExp(`${quote}[\\s\\S]*?(\\${quote},?)`, "gm");
|
|
426
|
-
const matchValue = regexTestValue.exec(matchTestKey[0]);
|
|
427
|
-
if (matchValue) {
|
|
428
|
-
const regex = new RegExp(`${quote},`, "gm");
|
|
429
|
-
const regex2 = new RegExp(`${quote}`, "gm");
|
|
430
|
-
result = matchValue[0].replace(regex, "").replace(regex2, "");
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
} else if (key === "errors") {
|
|
434
|
-
const regexTestKey = new RegExp(`${key}:.*$(([\\s]+.+)+])?`, "gm");
|
|
435
|
-
const matchTestKey = regexTestKey.exec(text);
|
|
436
|
-
if (matchTestKey) {
|
|
437
|
-
result = matchTestKey[0];
|
|
438
|
-
}
|
|
439
|
-
} else if (key === "data") {
|
|
440
|
-
const regexTestKey = new RegExp(`${key}:.*}`, "gm");
|
|
441
|
-
const matchTestKey = regexTestKey.exec(text);
|
|
442
|
-
if (matchTestKey) {
|
|
443
|
-
result = matchTestKey[0];
|
|
444
|
-
}
|
|
445
|
-
} else {
|
|
446
|
-
result = `No parameter \\'${key}\\' found in ruleTest`;
|
|
447
|
-
}
|
|
448
|
-
return result;
|
|
449
|
-
},
|
|
450
|
-
|
|
451
|
-
/**
|
|
452
|
-
* Generates overview table of all rules based on rule dictionary.
|
|
453
|
-
* @param ruleDict
|
|
454
|
-
* @param release
|
|
455
|
-
* @param table
|
|
456
|
-
* @returns Markdown table
|
|
457
|
-
*/
|
|
458
|
-
genMdRules: function (ruleDict, release, table = true) {
|
|
459
|
-
let mdRules = `# @sap/eslint-plugin-cds [latest]\n\n`;
|
|
460
|
-
if (table) {
|
|
461
|
-
mdRules += `Rules in ESLint are grouped by type to help you understand their purpose. Each rule has emojis denoting:\n\n`;
|
|
462
|
-
mdRules += `✔️ if the plugin's "recommended" configuration enables the rule\n\n`;
|
|
463
|
-
mdRules += `🔧 if problems reported by the rule are automatically fixable (\`--fix\`)\n\n`;
|
|
464
|
-
mdRules += `💡 if problems reported by the rule are manually fixable (editor)\n\n`;
|
|
465
|
-
if (!release) {
|
|
466
|
-
mdRules += `🚧 if rule exists in plugin (main branch) but is not yet released (artifactory)\n\n`;
|
|
467
|
-
mdRules += "| | | | | | | |\n";
|
|
468
|
-
mdRules += "|:-:|:-:|:-:|:-:|-:|:-|:-|\n";
|
|
469
|
-
} else {
|
|
470
|
-
mdRules += "| | | | | | | |\n";
|
|
471
|
-
mdRules += "|:-:|:-:|:-:|:-:|-:|:-|:-|\n";
|
|
472
|
-
}
|
|
473
|
-
/* eslint-disable-next-line no-unused-vars */
|
|
474
|
-
Object.entries(ruleDict).forEach(([, rules]) => {
|
|
475
|
-
rules.forEach(function (rule) {
|
|
476
|
-
mdRules += release
|
|
477
|
-
? `| ${rule.recommended} | ${rule.fixable} | ${rule.hasSuggestions} | | | [${rule.name}](Rules-released.md#${rule.name}) | ${rule.details}|\n`
|
|
478
|
-
: `| ${rule.recommended} | ${rule.fixable} | ${rule.hasSuggestions} | ${rule.construction} | | [${rule.name}](Rules.md#${rule.name}) | ${rule.details}|\n`;
|
|
479
|
-
});
|
|
480
|
-
});
|
|
481
|
-
mdRules += "\n";
|
|
482
|
-
}
|
|
483
|
-
return mdRules;
|
|
484
|
-
},
|
|
485
|
-
|
|
486
|
-
/**
|
|
487
|
-
* Generates markdown documentation files for:
|
|
488
|
-
* - Overview of all rules in form of markdown table (RuleList)
|
|
489
|
-
* - List of all rules details in form of markdown page (Rules)
|
|
490
|
-
* If used internally within the @sap/eslint-plugin-cds, this
|
|
491
|
-
* also generates 'released' files, which only contain information
|
|
492
|
-
* on rules published until the currently released version.
|
|
493
|
-
* @param ruleDict
|
|
494
|
-
* @param docsPath
|
|
495
|
-
* @param release
|
|
496
|
-
*/
|
|
497
|
-
genDocFiles: function (ruleDict, docsPath, release = false) {
|
|
498
|
-
let suffix = "";
|
|
499
|
-
if (release) {
|
|
500
|
-
suffix = "-released";
|
|
501
|
-
}
|
|
502
|
-
const ruleDocsPath = path.join(docsPath, `Rules${suffix}.md`);
|
|
503
|
-
const ruleListDocsPath = path.join(docsPath, `RuleList${suffix}.md`);
|
|
504
|
-
|
|
505
|
-
if (!fs.existsSync(ruleDocsPath)) {
|
|
506
|
-
fs.writeFileSync(ruleDocsPath, "", "utf8");
|
|
507
|
-
}
|
|
508
|
-
if (!fs.existsSync(ruleListDocsPath)) {
|
|
509
|
-
fs.writeFileSync(ruleListDocsPath, "", "utf8");
|
|
510
|
-
}
|
|
511
|
-
const mdRulesCur = fs.readFileSync(ruleDocsPath, "utf8");
|
|
512
|
-
const mdRuleListCur = fs.readFileSync(ruleListDocsPath, "utf8");
|
|
513
|
-
|
|
514
|
-
// Get rules table
|
|
515
|
-
const mdRuleList = module.exports.genMdRules(ruleDict, release, true);
|
|
516
|
-
|
|
517
|
-
// Get rule details
|
|
518
|
-
let mdRules = module.exports.genMdRules(ruleDict, release, false);
|
|
519
|
-
/* eslint-disable-next-line no-unused-vars */
|
|
520
|
-
Object.entries(ruleDict).forEach(([category, rules]) => {
|
|
521
|
-
rules.forEach(function (rule) {
|
|
522
|
-
mdRules += `${rule.contents}\n\n${rule.sources}\n\n---\n\n`;
|
|
523
|
-
});
|
|
524
|
-
});
|
|
525
|
-
|
|
526
|
-
if (mdRuleListCur !== mdRuleList || mdRulesCur !== mdRules) {
|
|
527
|
-
fs.writeFileSync(ruleDocsPath, mdRules, "utf8");
|
|
528
|
-
fs.writeFileSync(ruleListDocsPath, mdRuleList, "utf8");
|
|
529
|
-
}
|
|
530
|
-
},
|
|
531
|
-
|
|
532
|
-
/**
|
|
533
|
-
* Generates custom rules documentation (markdown files)
|
|
534
|
-
* for user according to contents of:
|
|
535
|
-
* - Rule files
|
|
536
|
-
* - Test files (with valid/invalid/fixed examples)
|
|
537
|
-
* @param {string} projectPath
|
|
538
|
-
* @param {string} customRulesDir
|
|
539
|
-
*/
|
|
540
|
-
async genDocs(projectPath, customRulesDir, registry, prepareRelease = false) {
|
|
541
|
-
let docsPath, rulePath, testPath, release;
|
|
542
|
-
|
|
543
|
-
if (!projectPath) {
|
|
544
|
-
docsPath = path.join(__dirname, "../../docs");
|
|
545
|
-
rulePath = path.join(__dirname, "../rules");
|
|
546
|
-
testPath = path.join(__dirname, "../../test/rules");
|
|
547
|
-
release = JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version;
|
|
548
|
-
} else {
|
|
549
|
-
docsPath = path.join(projectPath, `${customRulesDir}/docs`);
|
|
550
|
-
rulePath = path.join(projectPath, `${customRulesDir}/rules`);
|
|
551
|
-
testPath = path.join(projectPath, `${customRulesDir}/tests`);
|
|
552
|
-
await Promise.all(
|
|
553
|
-
[docsPath, rulePath, testPath].filter((path) => !fs.existsSync(path)).map((path) => mkdirp(path))
|
|
554
|
-
);
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
if (registry) {
|
|
558
|
-
// Get rules (internal on artifactory)
|
|
559
|
-
const versionInternal = prepareRelease
|
|
560
|
-
? JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version
|
|
561
|
-
: module.exports.getPackageVersion(registry);
|
|
562
|
-
if (versionInternal) {
|
|
563
|
-
console.log(`Updating internal rules from v>=${versionInternal}:\n${registry}\n`);
|
|
564
|
-
const ruleDictInternal = module.exports.getRuleDict(docsPath, rulePath, testPath, versionInternal);
|
|
565
|
-
module.exports.genDocFiles(ruleDictInternal, docsPath);
|
|
566
|
-
}
|
|
567
|
-
// Get rules released (external on npm)
|
|
568
|
-
const npmRegistry = "https://registry.npmjs.org";
|
|
569
|
-
const versionExternal = prepareRelease
|
|
570
|
-
? JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json"))).version
|
|
571
|
-
: module.exports.getPackageVersion(npmRegistry);
|
|
572
|
-
if (versionExternal) {
|
|
573
|
-
console.log(`Updating external rules from v>=${versionExternal}:\n${npmRegistry}\n`);
|
|
574
|
-
const ruleDictExternal = module.exports.getRuleDict(docsPath, rulePath, testPath, versionExternal, release);
|
|
575
|
-
module.exports.genDocFiles(ruleDictExternal, docsPath, release);
|
|
576
|
-
}
|
|
577
|
-
} else {
|
|
578
|
-
// Get "custom" rules
|
|
579
|
-
const ruleDict = module.exports.getRuleDict(docsPath, rulePath, testPath);
|
|
580
|
-
module.exports.genDocFiles(ruleDict, docsPath);
|
|
581
|
-
}
|
|
582
|
-
console.log("Done!");
|
|
583
|
-
},
|
|
584
|
-
|
|
585
|
-
getRuleDict: function (docsPath, rulePath, testPath, versionRequired = "0.0.0", release = false) {
|
|
586
|
-
let mdRule, mdRuleSources, mdRuleContents;
|
|
587
|
-
const ruleDict = {};
|
|
588
|
-
fs.readdirSync(rulePath).filter((file) => {
|
|
589
|
-
if (path.extname(file).toLowerCase() === ".js" && file !== "index.js") {
|
|
590
|
-
const rule = path.basename(file).replace(path.extname(file), "");
|
|
591
|
-
const ruleTestPath = path.join(testPath, rule, "rule.test.js");
|
|
592
|
-
|
|
593
|
-
// Get rule meta information
|
|
594
|
-
const ruleMeta = require(path.join(rulePath, file)).meta;
|
|
595
|
-
const version = ruleMeta.docs.version;
|
|
596
|
-
|
|
597
|
-
if ((release && semver.satisfies(version, `<=${versionRequired}`)) || !release) {
|
|
598
|
-
const details = ruleMeta.docs.description;
|
|
599
|
-
const category = ruleMeta.docs.category;
|
|
600
|
-
const fixable = ruleMeta.fixable;
|
|
601
|
-
const messages = ruleMeta.messages;
|
|
602
|
-
const recommended = ruleMeta.docs.recommended;
|
|
603
|
-
const suggestions = ruleMeta.hasSuggestions;
|
|
604
|
-
|
|
605
|
-
let underConstruction = "";
|
|
606
|
-
if (!release && (version === "TBD" || semver.satisfies(version, `>${versionRequired}`))) {
|
|
607
|
-
underConstruction = "🚧";
|
|
608
|
-
console.log(` > 🚧 Rule '${rule}' still under construction.\n`);
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
const isFixable = ["code", "whitespace"].includes(fixable) ? "🔧" : "";
|
|
612
|
-
const isRecommended = recommended === true ? "✔️" : "";
|
|
613
|
-
const hasSuggestions = suggestions === true ? "💡" : "";
|
|
614
|
-
|
|
615
|
-
const ruleDictEntry = {
|
|
616
|
-
name: rule,
|
|
617
|
-
details,
|
|
618
|
-
recommended: isRecommended,
|
|
619
|
-
fixable: isFixable,
|
|
620
|
-
hasSuggestions,
|
|
621
|
-
construction: underConstruction,
|
|
622
|
-
messages,
|
|
623
|
-
version: version,
|
|
624
|
-
};
|
|
625
|
-
mdRule = module.exports.getRuleExamples(ruleTestPath, testPath, ruleDictEntry);
|
|
626
|
-
mdRuleContents = "";
|
|
627
|
-
|
|
628
|
-
mdRuleContents +=
|
|
629
|
-
!release && underConstruction
|
|
630
|
-
? `## ${rule}\n<span class='shifted'>${underConstruction} <span class='label'>${category}</span></span>\n\n`
|
|
631
|
-
: `## ${rule}\n<span class='shifted label'>${category}</span>\n\n`;
|
|
632
|
-
|
|
633
|
-
mdRuleContents += `### Rule Details\n${details}\n\n`;
|
|
634
|
-
if (mdRule) {
|
|
635
|
-
mdRuleContents += `### Examples\n${mdRule}\n\n`;
|
|
636
|
-
}
|
|
637
|
-
mdRuleContents += `### Version\nThis rule was introduced in \`@sap/eslint-plugin-cds ${version}\`.\n\n`;
|
|
638
|
-
mdRuleSources = `### Resources\n[Rule & Documentation source](${path
|
|
639
|
-
.relative(docsPath, path.join(rulePath, `${rule}.js`))
|
|
640
|
-
.replace(/\\/g, "/")})\n\n`;
|
|
641
|
-
|
|
642
|
-
ruleDictEntry.contents = mdRuleContents;
|
|
643
|
-
ruleDictEntry.sources = mdRuleSources;
|
|
644
|
-
if (Object.keys(ruleDict).includes(category)) {
|
|
645
|
-
ruleDict[category].push(ruleDictEntry);
|
|
646
|
-
} else {
|
|
647
|
-
ruleDict[category] = [
|
|
648
|
-
{
|
|
649
|
-
name: rule,
|
|
650
|
-
details,
|
|
651
|
-
recommended: isRecommended,
|
|
652
|
-
fixable: isFixable,
|
|
653
|
-
hasSuggestions,
|
|
654
|
-
version: version,
|
|
655
|
-
contents: mdRuleContents,
|
|
656
|
-
sources: mdRuleSources,
|
|
657
|
-
construction: underConstruction,
|
|
658
|
-
},
|
|
659
|
-
];
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
});
|
|
664
|
-
return ruleDict;
|
|
665
|
-
},
|
|
666
|
-
|
|
667
|
-
getRuleExamples: function (ruleTestPath, testPath, ruleDictEntry) {
|
|
668
|
-
// Get rule valid/invalid tests
|
|
669
|
-
let mdRule = "";
|
|
670
|
-
if (fs.existsSync(ruleTestPath)) {
|
|
671
|
-
const ruleTest = fs.readFileSync(ruleTestPath, "utf8");
|
|
672
|
-
const filename = module.exports.getKeyFromTest(ruleTest, "filename");
|
|
673
|
-
let errorsString = module.exports.getKeyFromTest(ruleTest, "errors");
|
|
674
|
-
const re = /(\S+):/gm;
|
|
675
|
-
errorsString = errorsString.replace(re, `"$&`).replace(/:/gm, '":').replace(/`/gm, '"');
|
|
676
|
-
const errors = JSONC.parse(`{${errorsString}}`).errors;
|
|
677
|
-
const valid = fs.readFileSync(path.join(testPath, ruleDictEntry.name, "valid", filename), "utf8");
|
|
678
|
-
let invalid = fs.readFileSync(path.join(testPath, ruleDictEntry.name, "invalid", filename), "utf8");
|
|
679
|
-
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
|
|
680
|
-
let errorsSorted = [];
|
|
681
|
-
errors.forEach((err) => {
|
|
682
|
-
if (errorsSorted.length === 0) {
|
|
683
|
-
errorsSorted = [err];
|
|
684
|
-
} else {
|
|
685
|
-
const errLast = errorsSorted[errorsSorted.length - 1];
|
|
686
|
-
if (err.line > errLast.line) {
|
|
687
|
-
errorsSorted.push(err);
|
|
688
|
-
} else if (err.line < errLast.line) {
|
|
689
|
-
errorsSorted.unshift(err);
|
|
690
|
-
} else {
|
|
691
|
-
if (err.column > errLast.column) {
|
|
692
|
-
errorsSorted.push(err);
|
|
693
|
-
} else if (err.line < errLast.line) {
|
|
694
|
-
errorsSorted.unshift(err);
|
|
695
|
-
} else {
|
|
696
|
-
errorsSorted.push(err);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
}
|
|
700
|
-
});
|
|
701
|
-
errorsSorted.reverse().forEach((err, i) => {
|
|
702
|
-
if (err.messageId) {
|
|
703
|
-
let msg = ruleDictEntry.messages[err.messageId];
|
|
704
|
-
let data;
|
|
705
|
-
if (errorsSorted[i].suggestions && errorsSorted[i].suggestions[0]) {
|
|
706
|
-
data = errorsSorted[i].suggestions[0].data;
|
|
707
|
-
}
|
|
708
|
-
if (data) {
|
|
709
|
-
Object.keys(data).forEach((d) => {
|
|
710
|
-
msg = msg.replace(`{{${d}}}`, data[d]);
|
|
711
|
-
});
|
|
712
|
-
}
|
|
713
|
-
err.message = msg;
|
|
714
|
-
}
|
|
715
|
-
const msg = err.message.replace(/"/gm, "`");
|
|
716
|
-
if (err.line) {
|
|
717
|
-
const code = invalid.split("\n");
|
|
718
|
-
code[err.line - 1] = insertAt(code[err.line - 1], "</i></b></span>", err.endColumn - 1);
|
|
719
|
-
code[err.line - 1] = insertAt(
|
|
720
|
-
code[err.line - 1],
|
|
721
|
-
`<span style="display:inline-block; position:relative; color:red; border-bottom:2pt dotted red" title="${msg}"><b><i>`,
|
|
722
|
-
err.column - 1
|
|
723
|
-
);
|
|
724
|
-
invalid = code.join("\n");
|
|
725
|
-
}
|
|
726
|
-
});
|
|
727
|
-
|
|
728
|
-
mdRule +=
|
|
729
|
-
`<span>✔️ Example of ` +
|
|
730
|
-
`<span style="color:green">correct</span> ` +
|
|
731
|
-
`code for this rule:</span>\n\n<pre><code>\n${valid}\n</code></pre>\n\n`;
|
|
732
|
-
mdRule +=
|
|
733
|
-
`<span>❌ Example of ` +
|
|
734
|
-
`<span style="color:red">incorrect</span> ` +
|
|
735
|
-
`code for this rule:</span>\n\n<pre><code>\n${invalid}\n</code></pre>`;
|
|
736
|
-
}
|
|
737
|
-
return mdRule;
|
|
738
|
-
},
|
|
739
|
-
|
|
740
|
-
/**
|
|
741
|
-
* Gets all plugin rules and stores contents for later use in isRuleDisabled()
|
|
742
|
-
* @param {*} dirname rules dirname
|
|
743
|
-
* @param {*} rulename optional rule name (for single rule unit tests with RuleTester)
|
|
744
|
-
* @returns rule object with sources and rule lists
|
|
745
|
-
*/
|
|
746
|
-
getRules: function (dirname, rulename) {
|
|
747
|
-
let rulesInfo;
|
|
748
|
-
if (Cache.has("rulesInfo")) {
|
|
749
|
-
rulesInfo = Cache.get("rulesInfo");
|
|
750
|
-
} else {
|
|
751
|
-
const rules = {};
|
|
752
|
-
const listEnvRules = [];
|
|
753
|
-
const listModelRules = [];
|
|
754
|
-
|
|
755
|
-
if (rulename) {
|
|
756
|
-
const file = `${rulename}.js`;
|
|
757
|
-
|
|
758
|
-
let rule = createRule(require(path.join(dirname, file)));
|
|
759
|
-
rules[rulename] = rule;
|
|
760
|
-
|
|
761
|
-
if (!listEnvRules.includes(rulename) && !isValidModel(file, "model")) {
|
|
762
|
-
listEnvRules.push(rulename);
|
|
763
|
-
}
|
|
764
|
-
if (!listModelRules.includes(rulename) && isValidModel(file, "model")) {
|
|
765
|
-
listModelRules.push(rulename);
|
|
766
|
-
}
|
|
767
|
-
} else {
|
|
768
|
-
fs.readdirSync(dirname).forEach((file) => {
|
|
769
|
-
if (path.extname(file) === ".js") {
|
|
770
|
-
const rulename = file.replace(".js", "");
|
|
771
|
-
|
|
772
|
-
let rule = createRule(require(path.join(dirname, file)));
|
|
773
|
-
rules[rulename] = rule;
|
|
774
|
-
|
|
775
|
-
if (!listEnvRules.includes(rulename) && !isValidModel(file, "model")) {
|
|
776
|
-
listEnvRules.push(rulename);
|
|
777
|
-
}
|
|
778
|
-
if (!listModelRules.includes(rulename) && isValidModel(file, "model")) {
|
|
779
|
-
listModelRules.push(rulename);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
});
|
|
783
|
-
}
|
|
784
|
-
const listRules = listEnvRules.concat(listModelRules);
|
|
785
|
-
|
|
786
|
-
const recommended = Object.assign(
|
|
787
|
-
{},
|
|
788
|
-
...Object.entries(rules)
|
|
789
|
-
.filter(([, v]) => v.meta.docs.recommended)
|
|
790
|
-
.map(([k, v]) => ({ [`@sap/cds/${k}`]: v.meta.severity }))
|
|
791
|
-
);
|
|
792
|
-
|
|
793
|
-
const all = Object.assign({}, ...Object.entries(rules).map(([k, v]) => ({ [`@sap/cds/${k}`]: v.meta.severity })));
|
|
794
|
-
rulesInfo = { sources: rules, all, recommended, listRules, listEnvRules, listModelRules };
|
|
795
|
-
Cache.set("rulesInfo", rulesInfo);
|
|
796
|
-
}
|
|
797
|
-
return rulesInfo;
|
|
798
|
-
},
|
|
799
|
-
|
|
800
|
-
// populateRules: function (context, customRulesDir) {
|
|
801
|
-
// const configPath = Cache.get("configpath") || "";
|
|
802
|
-
// // Allow for custom rules
|
|
803
|
-
// if (configPath) {
|
|
804
|
-
// let customRulesPath = path.join(Cache.get("configpath"), customRulesDir, "rules");
|
|
805
|
-
// let customRulesInfo;
|
|
806
|
-
// if (fs.existsSync(customRulesPath)) {
|
|
807
|
-
// customRulesInfo = module.exports.getRules(customRulesPath);
|
|
808
|
-
// Cache.set("rulesInfo", {
|
|
809
|
-
// listEnvRules: context.listEnvRules.concat(customRulesInfo.listEnvRules),
|
|
810
|
-
// listModelRules: context.listModelRules.concat(customRulesInfo.listModelRules),
|
|
811
|
-
// listRules: context.listRules.concat(customRulesInfo.listRules),
|
|
812
|
-
// });
|
|
813
|
-
// }
|
|
814
|
-
// }
|
|
815
|
-
// },
|
|
816
|
-
|
|
817
|
-
/**
|
|
818
|
-
* Generates proxy for `@sap/cds` object which adds:
|
|
819
|
-
* - Extra properties (model, environment, etc.)
|
|
820
|
-
* - Option to cache function calls (apply)
|
|
821
|
-
* @param {cds} object
|
|
822
|
-
* @returns Proxy for cds
|
|
823
|
-
*/
|
|
824
|
-
cdsProxy: function (cds, { code, filePath, configPath, id, options }) {
|
|
825
|
-
const handler = {
|
|
826
|
-
get(target, prop, receiver) {
|
|
827
|
-
let value;
|
|
828
|
-
switch (prop) {
|
|
829
|
-
case "model":
|
|
830
|
-
value = module.exports.getModel(code, filePath, configPath, id, cds);
|
|
831
|
-
break;
|
|
832
|
-
case "environment":
|
|
833
|
-
value = module.exports.getEnvironment(options);
|
|
834
|
-
break;
|
|
835
|
-
case "getLocation":
|
|
836
|
-
value = getLocation;
|
|
837
|
-
break;
|
|
838
|
-
case "getRange":
|
|
839
|
-
value = getRange;
|
|
840
|
-
break;
|
|
841
|
-
default:
|
|
842
|
-
break;
|
|
843
|
-
}
|
|
844
|
-
if (value) {
|
|
845
|
-
return value;
|
|
846
|
-
} else {
|
|
847
|
-
value = Reflect.get(target, prop, receiver);
|
|
848
|
-
if (value && typeof value == "object") {
|
|
849
|
-
value = new Proxy(value, handler);
|
|
850
|
-
}
|
|
851
|
-
return value;
|
|
852
|
-
}
|
|
853
|
-
},
|
|
854
|
-
apply(target, thisArg, argumentsList) {
|
|
855
|
-
// NOTE: Possible to add caching for expensive function calls
|
|
856
|
-
// here as the rule set grows further
|
|
857
|
-
const result = Reflect.apply(target, this, argumentsList);
|
|
858
|
-
return result;
|
|
859
|
-
},
|
|
860
|
-
};
|
|
861
|
-
return new Proxy(cds, handler);
|
|
862
|
-
},
|
|
863
|
-
/**
|
|
864
|
-
* Generates proxy for ESLint's context object which adds caching
|
|
865
|
-
* @param {CDSRuleReport} ESLint's context object
|
|
866
|
-
* @returns {Rule.ReportDescriptor}
|
|
867
|
-
*/
|
|
868
|
-
reportProxy: function (ruleReport) {
|
|
869
|
-
const handler = {
|
|
870
|
-
get(target, prop, receiver) {
|
|
871
|
-
const value = Reflect.get(target, prop, receiver);
|
|
872
|
-
if (typeof value !== "object") {
|
|
873
|
-
return value;
|
|
874
|
-
}
|
|
875
|
-
if (value) {
|
|
876
|
-
return new Proxy(value, handler);
|
|
877
|
-
}
|
|
878
|
-
return {
|
|
879
|
-
err: `Property ${prop} prop does not exist on object ${ruleReport}!`,
|
|
880
|
-
};
|
|
881
|
-
},
|
|
882
|
-
apply(target, thisArg, argumentsList) {
|
|
883
|
-
let report = false;
|
|
884
|
-
if (argumentsList.length > 0) {
|
|
885
|
-
argumentsList.forEach((lint) => {
|
|
886
|
-
if (lint) {
|
|
887
|
-
// Do not consider disabled content
|
|
888
|
-
if (!isRuleDisabled(lint, thisArg)) {
|
|
889
|
-
// Do not resctrict by file extension
|
|
890
|
-
const isModelLint = lint.file && !lint.err;
|
|
891
|
-
if (isModelLint && module.exports.isDedicatedFile(lint, thisArg)) {
|
|
892
|
-
// Needed to still show lint messsages on close/re-open of file
|
|
893
|
-
if (isVSCodeEditor()) {
|
|
894
|
-
report = true;
|
|
895
|
-
} else {
|
|
896
|
-
if (module.exports.isReportUnique(lint, "modelReports")) {
|
|
897
|
-
report = true;
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
if (!lint.loc) {
|
|
902
|
-
lint.loc = module.exports.addDefaultLoc();
|
|
903
|
-
}
|
|
904
|
-
if (
|
|
905
|
-
!isModelLint &&
|
|
906
|
-
!lint.err &&
|
|
907
|
-
module.exports.isReportUnique(lint, "envReports", thisArg.configPath)
|
|
908
|
-
) {
|
|
909
|
-
report = true;
|
|
910
|
-
}
|
|
911
|
-
if (lint.err && (lint.file || module.exports.isReportUnique(lint, "errReports", thisArg.configPath))) {
|
|
912
|
-
report = true;
|
|
913
|
-
}
|
|
914
|
-
if (report) {
|
|
915
|
-
return thisArg._context.report(lint);
|
|
916
|
-
}
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
});
|
|
920
|
-
}
|
|
921
|
-
},
|
|
922
|
-
};
|
|
923
|
-
return new Proxy(ruleReport, handler);
|
|
924
|
-
},
|
|
925
|
-
|
|
926
|
-
resolveFilePath: (file) => (path.isAbsolute(file) ? file : path.join(Cache.get("configpath"), file)),
|
|
927
|
-
|
|
928
|
-
isDedicatedFile: function (lint, thisArg) {
|
|
929
|
-
let lintReports = new Set();
|
|
930
|
-
const id = thisArg.id;
|
|
931
|
-
const lintFilePath = module.exports.resolveFilePath(lint.file);
|
|
932
|
-
|
|
933
|
-
if (lintFilePath === thisArg.filePath || lint.file === "<stdin>.cds") {
|
|
934
|
-
if (Cache.has(`reportsRootModel:${thisArg.filePath}:${id}`)) {
|
|
935
|
-
lintReports = Cache.get(`reportsRootModel:${thisArg.filePath}:${id}`);
|
|
936
|
-
if (lintReports.has(lint)) {
|
|
937
|
-
lintReports.delete(lint);
|
|
938
|
-
}
|
|
939
|
-
if (lintReports.size === 0) {
|
|
940
|
-
Cache.remove(`reportsRootModel:${thisArg.filePath}:${id}`);
|
|
941
|
-
} else {
|
|
942
|
-
Cache.set(`reportsRootModel:${thisArg.filePath}:${id}`, lintReports);
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
return true;
|
|
946
|
-
} else {
|
|
947
|
-
if (Cache.has(`reportsRootModel:${lintFilePath}:${id}`)) {
|
|
948
|
-
lintReports = Cache.get(`reportsRootModel:${lintFilePath}:${id}`);
|
|
949
|
-
}
|
|
950
|
-
lintReports.add(lint);
|
|
951
|
-
Cache.set(`reportsRootModel:${lintFilePath}:${id}`, lintReports);
|
|
952
|
-
return false;
|
|
953
|
-
}
|
|
954
|
-
},
|
|
955
|
-
|
|
956
|
-
isReportUnique: function (lint, name, uniqueness) {
|
|
957
|
-
let report = false;
|
|
958
|
-
if (lint.file) lint.file = module.exports.resolveFilePath(lint.file);
|
|
959
|
-
if (!uniqueness) {
|
|
960
|
-
uniqueness = JSON.stringify(lint);
|
|
961
|
-
}
|
|
962
|
-
if (!Cache.has(name) && uniqueness) {
|
|
963
|
-
const lintString = `${uniqueness}:${JSON.stringify(lint)}`;
|
|
964
|
-
Cache.set(name, [lintString]);
|
|
965
|
-
report = true;
|
|
966
|
-
} else {
|
|
967
|
-
if (uniqueness) {
|
|
968
|
-
const lintMessages = Cache.has(name) ? Cache.get(name) : [];
|
|
969
|
-
const lintString = `${uniqueness}:${JSON.stringify(lint)}`;
|
|
970
|
-
if (!lintMessages.includes(lintString)) {
|
|
971
|
-
lintMessages.push(lintString);
|
|
972
|
-
Cache.set(name, lintMessages);
|
|
973
|
-
report = true;
|
|
974
|
-
}
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
return report;
|
|
978
|
-
},
|
|
979
|
-
|
|
980
|
-
addDefaultLoc: () => ({
|
|
981
|
-
start: { line: 0, column: -1 },
|
|
982
|
-
end: { line: 0, column: -1 },
|
|
983
|
-
}),
|
|
984
|
-
|
|
985
|
-
getModel: function (code, filePath, configPath) {
|
|
986
|
-
let model;
|
|
987
|
-
|
|
988
|
-
if (Cache.has("test")) {
|
|
989
|
-
return Cache.get(`model:${configPath}`);
|
|
990
|
-
}
|
|
991
|
-
|
|
992
|
-
if (!Cache.has(`model:${configPath}`)) {
|
|
993
|
-
const isValidPluginFile = isValidFile(filePath, "FILES");
|
|
994
|
-
|
|
995
|
-
if (isValidPluginFile) {
|
|
996
|
-
model = initRootModel(configPath);
|
|
997
|
-
// Set ref file associate to root model (to iterate rules only once)
|
|
998
|
-
const refFile = (model && model.$sources) ? ((model.$sources.includes(filePath)) ? filePath : model.$sources[0]) : undefined;
|
|
999
|
-
Cache.set(`initModel:${configPath}`, refFile);
|
|
1000
|
-
if (!refFile) return
|
|
1001
|
-
if (module.exports.isParkedModelFile(filePath, configPath)) {
|
|
1002
|
-
return compileModelFromFile(code, filePath);
|
|
1003
|
-
} else if (model) {
|
|
1004
|
-
return model;
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
} else {
|
|
1008
|
-
const isValidModelFile = isValidFile(filePath, "MODEL_FILES");
|
|
1009
|
-
|
|
1010
|
-
if (module.exports.isParkedModelFile(filePath, configPath)) {
|
|
1011
|
-
return compileModelFromFile(code, filePath);
|
|
1012
|
-
} else if (isValidModelFile) {
|
|
1013
|
-
const fileChanged = hasFileChanged(code, filePath, configPath);
|
|
1014
|
-
if (fileChanged) {
|
|
1015
|
-
Cache.remove("modelReports");
|
|
1016
|
-
Cache.remove("errReports");
|
|
1017
|
-
model = updateModel(code, filePath, configPath);
|
|
1018
|
-
} else {
|
|
1019
|
-
model = Cache.get(`model:${configPath}`);
|
|
1020
|
-
}
|
|
1021
|
-
} else {
|
|
1022
|
-
model = Cache.get(`model:${configPath}`);
|
|
1023
|
-
}
|
|
1024
|
-
return model;
|
|
1025
|
-
}
|
|
1026
|
-
},
|
|
1027
|
-
|
|
1028
|
-
isParkedModelFile: (filePath, configPath) =>
|
|
1029
|
-
isValidFile(filePath, "MODEL_FILES") && !isFileInModel(filePath, configPath),
|
|
1030
|
-
|
|
1031
|
-
getEnvironment: function (options) {
|
|
1032
|
-
let environment;
|
|
1033
|
-
if (options) {
|
|
1034
|
-
const hasEnvTestCases = options && options[0] && options[0].environment;
|
|
1035
|
-
if (hasEnvTestCases) {
|
|
1036
|
-
environment = options[0].environment;
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
return environment;
|
|
1040
|
-
},
|
|
1041
|
-
createRule,
|
|
1042
|
-
};
|
|
4
|
+
const findFuzzy = require("./findFuzzy");
|
|
5
|
+
|
|
6
|
+
module.exports = {
|
|
7
|
+
findFuzzy,
|
|
8
|
+
/**
|
|
9
|
+
*
|
|
10
|
+
* @param {*} e
|
|
11
|
+
*/
|
|
12
|
+
splitEntityName: function (e) {
|
|
13
|
+
// Entity names from CSN are of the form:
|
|
14
|
+
// <namespace>.<service>.<entity>.<'texts'|'localized'>|<composition value>
|
|
15
|
+
let prefix = "";
|
|
16
|
+
let suffix = "";
|
|
17
|
+
let entityName = e.name;
|
|
18
|
+
const names = entityName.split(".");
|
|
19
|
+
entityName = names[names.length - 1];
|
|
20
|
+
|
|
21
|
+
if (entityName) {
|
|
22
|
+
// Managed composition get compiler tag `_up`
|
|
23
|
+
let isManagedComposition = false;
|
|
24
|
+
if (e.elements) {
|
|
25
|
+
isManagedComposition = Object.keys(e.elements).some((k) => k === "up_");
|
|
26
|
+
}
|
|
27
|
+
// Check for compiler tags
|
|
28
|
+
let compilerTagsToExclude = ["texts", "localized"];
|
|
29
|
+
const isCompilerTag = compilerTagsToExclude.includes(entityName);
|
|
30
|
+
|
|
31
|
+
if (isManagedComposition || isCompilerTag) {
|
|
32
|
+
suffix = names[names.length - 1];
|
|
33
|
+
entityName = names[names.length - 2];
|
|
34
|
+
}
|
|
35
|
+
prefix = e.name.split(`.${entityName}`)[0];
|
|
36
|
+
}
|
|
37
|
+
return { prefix, entity: entityName, suffix };
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
_findInCode: function (miss, code) {
|
|
41
|
+
// middle
|
|
42
|
+
let match = new RegExp(SEP + miss + SEP).exec(code);
|
|
43
|
+
if (match) return match.index + 1;
|
|
44
|
+
// end of line
|
|
45
|
+
match = new RegExp(SEP + miss + EOL).exec(code);
|
|
46
|
+
if (match) return match.index + 1;
|
|
47
|
+
// start of doc
|
|
48
|
+
match = new RegExp("^" + miss + SEP).exec(code);
|
|
49
|
+
if (match) return match.index;
|
|
50
|
+
// somewhere (fallback)
|
|
51
|
+
return code.indexOf(miss);
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
isEmptyString: function (value) {
|
|
55
|
+
if (typeof value !== "string" || (typeof value === "string" && value && value.length > 0)) {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
return true;
|
|
59
|
+
},
|
|
60
|
+
|
|
61
|
+
isEmptyObject: function (value) {
|
|
62
|
+
function isEmpty(object) {
|
|
63
|
+
for (const property in object) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
if (typeof value !== "object" || (typeof value === "object" && !isEmpty(value)) ||
|
|
69
|
+
(typeof value === "object" && value && value.length > 0)) {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
return true;
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
isStringInArray(str, arr, caps=false) {
|
|
76
|
+
const notIncluded = !arr.includes(str);
|
|
77
|
+
if (!caps && notIncluded) {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
if (caps && notIncluded && !arr.includes(str.toLowerCase()) && !arr.includes(str.toUpperCase())) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
},
|
|
85
|
+
|
|
86
|
+
getReplacementsSuggestions: function (context, value, loc) {
|
|
87
|
+
let invalid;
|
|
88
|
+
const lineToReplace = context.sourcecode.lines[loc.line];
|
|
89
|
+
var regExp = /\[([^)]+)\]/;
|
|
90
|
+
var matches = regExp.exec(lineToReplace);
|
|
91
|
+
if (matches && matches[0]) {
|
|
92
|
+
invalid = matches[0];
|
|
93
|
+
}
|
|
94
|
+
const startIndex = lineToReplace.indexOf(invalid);
|
|
95
|
+
const candidates = `['${value}']`;
|
|
96
|
+
const suggest = {
|
|
97
|
+
messageId: "ReplaceItemWith",
|
|
98
|
+
data: { invalid, candidates },
|
|
99
|
+
fix: (fixer) => fixer.replaceTextRange([startIndex, startIndex + invalid.length] + 1, candidates),
|
|
100
|
+
};
|
|
101
|
+
return ({
|
|
102
|
+
messageId: "InvalidItem",
|
|
103
|
+
data: { invalid, candidates },
|
|
104
|
+
loc: {
|
|
105
|
+
start: { line: loc.line + 1, column: startIndex },
|
|
106
|
+
end: { line: loc.line + 1, column: startIndex + invalid.length },
|
|
107
|
+
},
|
|
108
|
+
file: loc.file,
|
|
109
|
+
suggest,
|
|
110
|
+
severity: "warn",
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
};
|