forked from typescript-eslint/typescript-eslint
/
generated-rule-docs.ts
401 lines (372 loc) · 11 KB
/
generated-rule-docs.ts
1
2
3
4
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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import * as fs from 'fs';
import type * as unist from 'unist';
import * as mdast from 'mdast';
import * as path from 'path';
import { format } from 'prettier';
import type { Plugin } from 'unified';
import { compile, JSONSchema } from 'json-schema-to-typescript';
import * as tseslintParser from '@typescript-eslint/parser';
import * as eslintPlugin from '@typescript-eslint/eslint-plugin';
import { EOL } from 'os';
import { JSONSchema7 } from 'json-schema';
/**
* Rules whose options schema generate annoyingly complex schemas.
*
* @remarks These need to be typed in manually in their .md docs file.
* @todo Get these schemas printing nicely in their .md docs files!
*/
const COMPLICATED_RULE_OPTIONS = new Set([
'member-ordering',
'naming-convention',
]);
const sourceUrlPrefix =
'https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/';
const eslintPluginDirectory = path.resolve(
path.join(__dirname, '../../eslint-plugin'),
);
export const generatedRuleDocs: Plugin = () => {
return async (root, file) => {
if (file.stem == null) {
return;
}
const rule = eslintPlugin.rules[file.stem];
const meta = rule?.meta;
if (!meta?.docs) {
return;
}
const parent = root as unist.Parent;
// 1. Remove the " 🛑 This file is source code, not the primary documentation location! 🛑"
parent.children.splice(
parent.children.findIndex(v => v.type === 'blockquote'),
1,
);
// 2. Add a description of the rule at the top of the file
parent.children.unshift({
children: [
{
children: meta.docs.description
.split(/`(.+?)`/)
.map((value, index, array) => ({
type: index % 2 === 0 ? 'text' : 'inlineCode',
value: index === array.length - 1 ? `${value}.` : value,
})),
type: 'paragraph',
},
],
type: 'blockquote',
} as mdast.Blockquote);
// 3. Add a rule attributes list...
const attributesH2Index =
// ...before the first h2, if it exists...
parent.children.findIndex(
child => nodeIsHeading(child) && child.depth === 2,
) ??
// ...or at the very end, if not.
parent.children.length;
// The actual content will be injected on client side.
const attributesNode = {
type: 'jsx',
value: `<rule-attributes name="${file.stem}" />`,
};
parent.children.splice(attributesH2Index, 0, attributesNode);
// 4. Make sure the appropriate headers exist to place content under
const [howToUseH2Index, optionsH2Index] = ((): [number, number] => {
let howToUseH2Index = parent.children.findIndex(
createH2TextFilter('How to Use'),
);
let optionsH2Index = parent.children.findIndex(
createH2TextFilter('Options'),
);
const relatedToH2Index = parent.children.findIndex(
createH2TextFilter('Related To'),
);
let whenNotToUseItH2Index = parent.children.findIndex(
createH2TextFilter('When Not To Use It'),
);
if (meta.docs.extendsBaseRule) {
if (howToUseH2Index === -1) {
if (optionsH2Index !== -1) {
howToUseH2Index = optionsH2Index;
optionsH2Index += 1;
if (whenNotToUseItH2Index !== -1) {
whenNotToUseItH2Index += 1;
}
} else {
howToUseH2Index =
whenNotToUseItH2Index === -1
? parent.children.length
: ++whenNotToUseItH2Index;
}
parent.children.splice(howToUseH2Index, 0, {
children: [
{
type: 'text',
value: 'How to Use',
},
],
depth: 2,
type: 'heading',
} as mdast.Heading);
}
}
if (optionsH2Index === -1) {
optionsH2Index =
whenNotToUseItH2Index === -1
? relatedToH2Index === -1
? parent.children.length
: relatedToH2Index
: whenNotToUseItH2Index;
parent.children.splice(optionsH2Index, 0, {
children: [
{
type: 'text',
value: 'Options',
},
],
depth: 2,
type: 'heading',
} as mdast.Heading);
optionsH2Index += 1;
}
return [howToUseH2Index, optionsH2Index];
})();
// 5. Add a description of how to use / options for the rule
const optionLevel = meta.docs.recommended === 'error' ? 'error' : 'warn';
if (meta.docs.extendsBaseRule) {
parent.children.splice(optionsH2Index + 1, 0, {
children: [
{
value: 'See ',
type: 'text',
},
{
children: [
{
type: 'inlineCode',
value: `eslint/${file.stem}`,
},
{
type: 'text',
value: ' options',
},
],
type: 'link',
url: `https://eslint.org/docs/rules/${file.stem}#options`,
},
{
type: 'text',
value: '.',
},
],
type: 'paragraph',
} as mdast.Paragraph);
parent.children.splice(howToUseH2Index + 1, 0, {
lang: 'js',
type: 'code',
meta: 'title=".eslintrc.cjs"',
value: `module.exports = {
// Note: you must disable the base rule as it can report incorrect errors
"${file.stem}": "off",
"@typescript-eslint/${file.stem}": "${optionLevel}"
};`,
} as mdast.Code);
} else {
parent.children.splice(optionsH2Index, 0, {
lang: 'js',
type: 'code',
meta: 'title=".eslintrc.cjs"',
value: `module.exports = {
"rules": {
"@typescript-eslint/${file.stem}": "${optionLevel}"
}
};`,
} as mdast.Code);
if (meta.schema.length === 0) {
parent.children.splice(optionsH2Index + 1, 0, {
children: [
{
type: 'text',
value: 'This rule is not configurable.',
},
],
type: 'paragraph',
} as mdast.Paragraph);
} else if (!COMPLICATED_RULE_OPTIONS.has(file.stem)) {
const optionsSchema: JSONSchema =
meta.schema instanceof Array
? meta.schema[0]
: meta.schema.type === 'array'
? {
...(meta.schema.definitions
? { definitions: meta.schema.definitions }
: {}),
...(meta.schema.$defs
? { $defs: (meta.schema as JSONSchema7).$defs }
: {}),
...(meta.schema.prefixItems as [JSONSchema])[0],
}
: meta.schema;
parent.children.splice(
optionsH2Index + 2,
0,
{
children: [
{
type: 'text',
value: `This rule accepts an options ${
'enum' in optionsSchema
? 'string of the following possible values'
: 'object with the following properties'
}:`,
} as mdast.Text,
],
type: 'paragraph',
} as mdast.Paragraph,
{
lang: 'ts',
type: 'code',
value: [
(
await compile(
{
title: `Options`,
...optionsSchema,
},
file.stem,
{
additionalProperties: false,
bannerComment: '',
declareExternallyReferenced: true,
},
)
).replace(/^export /gm, ''),
format(
`const defaultOptions: Options = ${JSON.stringify(
rule.defaultOptions,
)};`,
{
parser: tseslintParser.parse,
},
),
]
.join(EOL)
.trim(),
} as mdast.Code,
);
}
}
// 6. Add a notice about coming from ESLint core for extension rules
if (meta.docs.extendsBaseRule) {
parent.children.push({
children: [
{
type: 'jsx',
value: '<sup>',
},
{
type: 'text',
value: 'Taken with ❤️ ',
},
{
type: 'link',
title: null,
url: `https://github.com/eslint/eslint/blob/main/docs/rules/${file.stem}.md`,
children: [
{
type: 'text',
value: 'from ESLint core',
},
],
},
{
type: 'jsx',
value: '</sup>',
},
],
type: 'paragraph',
} as mdast.Paragraph);
}
// 7. Also add a link to view the rule's source and test code
parent.children.push(
{
children: [
{
type: 'text',
value: 'Resources',
},
],
depth: 2,
type: 'heading',
} as mdast.Heading,
{
children: [
{
children: [
{
children: [
{
type: 'link',
url: `${sourceUrlPrefix}src/rules/${file.stem}.ts`,
children: [
{
type: 'text',
value: 'Rule source',
},
],
},
],
type: 'paragraph',
},
],
type: 'listItem',
},
{
children: [
{
children: [
{
type: 'link',
url: getUrlForRuleTest(file.stem),
children: [
{
type: 'text',
value: 'Test source',
},
],
},
],
type: 'paragraph',
},
],
type: 'listItem',
},
],
type: 'list',
} as mdast.List,
);
};
};
function nodeIsHeading(node: unist.Node): node is mdast.Heading {
return node.type === 'heading';
}
function createH2TextFilter(
text: string,
): (node: unist.Node) => node is mdast.Heading {
return (node: unist.Node): node is mdast.Heading =>
nodeIsHeading(node) &&
node.depth === 2 &&
node.children.length === 1 &&
node.children[0].type === 'text' &&
node.children[0].value === text;
}
function getUrlForRuleTest(ruleName: string): string {
for (const localPath of [
`tests/rules/${ruleName}.test.ts`,
`tests/rules/${ruleName}/`,
]) {
if (fs.existsSync(`${eslintPluginDirectory}/${localPath}`)) {
return `${sourceUrlPrefix}${localPath}`;
}
}
throw new Error(`Could not find test file for ${ruleName}.`);
}