-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdocs.js
272 lines (240 loc) · 7.68 KB
/
docs.js
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
// @ts-check
import { ESLint } from 'eslint';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { TEST_FILE_PATTERNS } from '../src/lib/patterns.js';
import {
configNames,
getAllEnabledRuleIds,
importConfig,
isConfigForTests,
} from './helpers/configs.js';
import { configRulesToMarkdown } from './helpers/format-config.js';
import { configsToMarkdown } from './helpers/format-readme.js';
import {
findRuleEntry,
getRulesMetadata,
ruleLevelFromEntry,
} from './helpers/rules.js';
const currentDir = fileURLToPath(path.dirname(import.meta.url));
const readmePath = path.join(currentDir, '..', 'README.md');
const docsDir = path.join(currentDir, '..', 'docs');
await generateDocs();
async function generateDocs() {
const configs = await loadConfigs(configNames);
const peerDeps = await loadPeerDependencies(configs);
await fs.mkdir(docsDir, { recursive: true });
await Promise.all(
configs.map(config => generateConfigDocs(config, configs, peerDeps)),
);
await generateReadmeDocs(configs, peerDeps);
}
/**
* @param {import('./helpers/types.js').ConfigName[]} names
* @returns {Promise<import('./helpers/types.js').ExportedConfig[]>}
*/
function loadConfigs(names) {
return Promise.all(
names.map(async name => ({
name,
flatConfig: await importConfig(name),
})),
);
}
/**
* @param {import('./helpers/types.js').ExportedConfig[]} configs
* @returns {Promise<import('./helpers/types.js').PeerDep[]>}
*/
async function loadPeerDependencies(configs) {
const packageJson = await import('../package.json', {
with: { type: 'json' },
}).then(m => m.default);
const pkgConfigs = configs.reduce(
/** @param {Record<string, string[]>} acc */
(acc, config) => {
const plugins = config.flatConfig.flatMap(cfg =>
Object.keys(cfg.plugins ?? {}),
);
const usedPackages = Object.keys(packageJson.peerDependencies).filter(
pkg => {
if (pkg === 'eslint') {
return false;
}
const alias = pkg.replace(/eslint-plugin-?/, '').replace(/\/$/, '');
return (
plugins.includes(pkg) ||
plugins.includes(alias) ||
plugins.map(plugin => plugin.replace(/^@/, '')).includes(alias)
);
},
);
return {
...acc,
...Object.fromEntries(
usedPackages.map(pkg => [pkg, [...(acc[pkg] ?? []), config.name]]),
),
};
},
{},
);
/** @type {Record<string, {optional: boolean}>} */
const peerDependenciesMeta = packageJson.peerDependenciesMeta;
return Object.entries(packageJson.peerDependencies).map(([pkg, version]) => ({
pkg,
version,
optional: peerDependenciesMeta[pkg]?.optional ?? false,
usedByConfigs: pkgConfigs[pkg] ?? [],
}));
}
/**
* Update auto-generated part of README.md
* @param {import('./helpers/types.js').ExportedConfig[]} configs Exported configs
* @param {import('./helpers/types.js').PeerDep[]} peerDeps Peer dependencies
*/
async function generateReadmeDocs(configs, peerDeps) {
const extended = Object.fromEntries(
configs.map(config => [config.name, getExtendedConfigs(config)]),
);
const buffer = await fs.readFile(readmePath);
const mdPrevious = buffer.toString('utf8');
const startComment = '<!-- begin autogenerated -->';
const endComment = '<!-- end autogenerated -->';
const startIndex = mdPrevious.indexOf(startComment);
const endIndex = mdPrevious.indexOf(
endComment,
startIndex + startComment.length,
);
const mdGenerated = configsToMarkdown(configNames, peerDeps, extended);
const mdGeneratedBlock = [
startComment,
mdGenerated.replace(/\n$/, ''),
endComment,
].join('\n\n');
const mdUpdated =
startIndex < 0
? [mdPrevious, mdGeneratedBlock].join('\n')
: [
mdPrevious.slice(0, startIndex),
mdGeneratedBlock,
mdPrevious.slice(endIndex + endComment.length),
].join('');
await fs.writeFile(readmePath, mdUpdated);
console.info(`Updated Markdown docs in ${readmePath}`);
}
/**
* Generate Markdown file for specified ESLint config.
* @param {import('./helpers/types.js').ExportedConfig} config Exported config
* @param {import('./helpers/types.js').ExportedConfig[]} allConfigs All exported configs
* @param {import('./helpers/types.js').PeerDep[]} peerDeps Peer dependencies
*/
async function generateConfigDocs(config, allConfigs, peerDeps) {
const extendedConfigs = Object.fromEntries(
getExtendedConfigs(config).map(otherName => {
const otherConfig = allConfigs.find(({ name }) => name === otherName);
const otherRuleIds = getAllEnabledRuleIds(otherConfig?.flatConfig ?? []);
return [otherName, otherRuleIds];
}),
);
const extendedRuleIds = new Set(Object.values(extendedConfigs).flat());
const ruleIds = getAllEnabledRuleIds(config.flatConfig).filter(
ruleId => !extendedRuleIds.has(ruleId),
);
const eslint = new ESLint();
const dummyFile = 'eslint.config.js';
await eslint.lintFiles(dummyFile);
const rulesMeta = getRulesMetadata(
config.flatConfig,
ruleIds,
eslint,
dummyFile,
);
const markdown = configRulesToMarkdown(
config.name,
ruleIds.map(id => findRuleData(id, config, rulesMeta)),
Object.entries(extendedConfigs).map(([alias, rules]) => ({
alias,
rulesCount: rules.length,
})),
peerDeps,
{
hideOverrides: isConfigForTests(config.name),
},
);
const filePath = path.join(docsDir, `${config.name}.md`);
await fs.writeFile(filePath, markdown);
console.info(`Generated Markdown docs in ${filePath}`);
}
/**
* Look up rule's metadata, level, custom options and overrides for given config.
* @param {string} id Rule ID
* @param {import('./helpers/types.js').ExportedConfig} config Configuration
* @param {Record<string, import('eslint').Rule.RuleMetaData>} rules Rules metadata
* @returns {import('./helpers/types.js').RuleData} Rule data
*/
function findRuleData(id, config, rules) {
const meta = rules[id];
if (!meta) {
throw new Error(`Can't find metadata for rule ${id}`);
}
const entry =
findRuleEntry(
config.flatConfig.filter(
({ name }) =>
name?.startsWith('code-pushup/') &&
(name.endsWith('/customized') || name.endsWith('/additional')),
),
id,
) ??
findRuleEntry(
config.flatConfig.filter(({ files }) => files !== TEST_FILE_PATTERNS),
id,
);
if (entry == null) {
throw new Error(
`Internal logic error - no entry found for rule ${id} in ${config.name} config`,
);
}
const level = ruleLevelFromEntry(entry);
if (level === 'off') {
throw new Error(
`Internal logic error - rule ${id} turned off in ${config.name} config`,
);
}
const testEntry = findRuleEntry(
config.flatConfig.filter(({ files }) => files === TEST_FILE_PATTERNS),
id,
);
const testLevel = testEntry == null ? null : ruleLevelFromEntry(testEntry);
return {
id,
meta,
level,
...(Array.isArray(entry) &&
entry.length > 1 && {
options: entry.slice(1),
}),
...(testLevel &&
testLevel !== level && {
testOverride: {
level: testLevel,
},
}),
};
}
/**
* Get all extended code-pushup configs from flat config.
* @param {import('./helpers/types.js').ExportedConfig} config Exported config
*/
function getExtendedConfigs(config) {
const allExtended = [
...new Set(
config.flatConfig
.map(cfg => cfg.name)
.filter(name => name?.startsWith('code-pushup/'))
.map(name => name?.split('/')[1])
.filter(name => name != null),
),
];
return allExtended.filter(name => name !== config.name).slice(-1);
}