-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgetModuleInfo.ts
More file actions
277 lines (228 loc) · 8.44 KB
/
getModuleInfo.ts
File metadata and controls
277 lines (228 loc) · 8.44 KB
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
import { execFileSync } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { Semaphore, uniq } from 'es-toolkit';
import Semver from 'semver';
import { generateChangelog } from './generateChangelog.js';
import { getRawContent, getRepoInfo } from './gh.js';
import { modules } from './modules.js';
import {
API_DIR,
METADATA_DIR,
MODULE_DIR,
PACKAGE_JSON_PATH,
POLICIES_GENERATED_DIR,
getExisting,
getModuleInfoPath,
getModuleMarkdownPath,
getModuleStoragePath,
} from './paths.js';
import type { ModuleInfo, ModuleSpec, VersionInfo } from './types.js';
const getFilteredVersions = (specs: ModuleSpec, versions: string[]): VersionInfo[] => {
const compatibilityVersions = Object.keys(specs.compatibility);
const minVersion = Math.min(...compatibilityVersions.map((v) => parseInt(v, 10)));
const prefilteredVersions = versions.filter((v) => Semver.satisfies(v, `>=${minVersion}`));
const publishedMajorVersions = uniq(prefilteredVersions.map((v) => Semver.major(v)));
const semveredMajors = compatibilityVersions.map((v) => `${v}.0.0`);
return publishedMajorVersions.map((major) => {
const closestMatchingVersion = Semver.maxSatisfying(semveredMajors, `<= ${major}`);
return {
fullVersion: Semver.maxSatisfying(prefilteredVersions, `^${major}`)!,
major,
nodeVersion: closestMatchingVersion ? specs.compatibility[Semver.major(closestMatchingVersion)] : '',
};
});
};
const repos: Record<string, Partial<ModuleInfo>> = {};
const limit = new Semaphore(4);
const processModule = async (moduleName: string, specs: ModuleSpec) => {
console.info(`Processing ${moduleName}`);
await fs.mkdir(getModuleStoragePath(moduleName), {
recursive: true,
});
const filePath = getModuleInfoPath(moduleName);
const existing = await getExisting<ModuleInfo>(filePath);
// Get published versions from npm
const versions = JSON.parse(
execFileSync('npm', ['view', specs.package, 'versions', '--json'], {
encoding: 'utf8',
}),
) as string[];
const currentModule: ModuleInfo = {
api: false,
forks: 0,
link: '',
name: moduleName,
package: specs.package,
slogan: '',
stars: 0,
updated: '',
versions: [],
versionsArray: [],
};
repos[moduleName] = currentModule;
// Keep only latest versions from majors listed in specs
const filteredVersions = getFilteredVersions(specs, versions);
currentModule.versionsArray = filteredVersions.map((v) => v.fullVersion).toSorted((a, b) => Semver.compare(b, a));
const versionLimit = new Semaphore(10);
const versionTasks = filteredVersions.map(async ({ nodeVersion, fullVersion, major }) => {
const apiPath = getModuleMarkdownPath(moduleName, major);
const apiExists = await fs
.access(apiPath)
.then(() => true)
.catch(() => false);
const existingVersion = existing?.versions.find((v) => v.name === fullVersion);
if (existingVersion && apiExists) {
console.info(`[docs] Skipping ${moduleName}@${major}`);
return {
apiExists: true,
branch: existingVersion.branch,
license: existingVersion.license,
name: existingVersion.name,
node: existingVersion.node,
};
}
await versionLimit.acquire();
try {
console.info(`[docs] Processing ${moduleName}@${fullVersion}`);
const tagName = `v${fullVersion}`;
const api = await getRawContent(moduleName, 'API.md', tagName);
await fs.mkdir(path.dirname(apiPath), { recursive: true });
await fs.writeFile(apiPath, api.data);
console.info(`[docs] Wrote ${apiPath}`);
return {
apiExists: true,
branch: tagName,
license: 'BSD',
name: fullVersion,
node: nodeVersion,
};
} finally {
versionLimit.release();
}
});
const versionResults = await Promise.all(versionTasks);
for (const result of versionResults) {
currentModule.versions.push({
branch: result.branch,
license: result.license,
name: result.name,
node: result.node,
});
if (result.apiExists) {
currentModule.api = true;
}
}
currentModule.versions.sort((a, b) => Semver.compare(a.name, b.name));
const [readme, repoInfo] = await Promise.all([
existing ? Promise.resolve({ data: '' }) : getRawContent(moduleName, 'README.md'),
existing
? Promise.resolve({
data: {
forks_count: existing.forks,
html_url: existing.link,
pushed_at: existing.updated,
stargazers_count: existing.stars,
},
})
: getRepoInfo(moduleName),
]);
const readmeMatch = readme.data.match(/####(.*)/gm);
const rawSlogan = readmeMatch === null ? (existing?.slogan ?? 'Description coming soon...') : readmeMatch[0].slice(5);
currentModule.slogan = rawSlogan.trim();
currentModule.forks = repoInfo.data.forks_count;
currentModule.stars = repoInfo.data.stargazers_count;
currentModule.updated = repoInfo.data.pushed_at;
currentModule.link = repoInfo.data.html_url;
const moduleDir = getModuleStoragePath(moduleName);
await fs.mkdir(moduleDir, { recursive: true });
await fs.writeFile(filePath, JSON.stringify(currentModule, null, 2));
if (moduleName === 'joi') {
await fs.mkdir(API_DIR, { recursive: true });
}
await generateChangelog(moduleName);
await fs.writeFile(filePath, JSON.stringify(currentModule, null, 2));
repos[moduleName] = {
forks: currentModule.forks,
link: currentModule.link,
package: currentModule.package,
slogan: currentModule.slogan,
stars: currentModule.stars,
updated: currentModule.updated,
versions: currentModule.versions,
versionsArray: currentModule.versionsArray,
};
};
const moduleTasks = Object.entries(modules).map(async ([moduleName, specs]) => {
await limit.acquire();
try {
await processModule(moduleName, specs);
} finally {
limit.release();
}
});
await Promise.all(moduleTasks);
const sortedRepos = Object.fromEntries(Object.keys(modules).map((name) => [name, repos[name]]));
const policies: [string, string, string?][] = [
['coc', 'CODE_OF_CONDUCT'],
['contributing', 'CONTRIBUTING'],
['license', 'LICENSE'],
['security', 'SECURITY'],
['styleguide', 'STYLE', 'assets'],
['support', 'SUPPORT'],
];
await fs.mkdir(POLICIES_GENERATED_DIR, { recursive: true });
await Promise.all(
policies.map(async ([policy, fileName, repo]) => {
const policyPath = path.join(POLICIES_GENERATED_DIR, `${policy}.md`);
const existingPolicy = await fs.readFile(policyPath, 'utf8').catch(() => null);
if (existingPolicy) {
console.info(`[policy] Skipping ${policy}`);
return;
}
const { data } = await getRawContent(repo ?? '.github', `${fileName}.md`, 'master');
await fs.writeFile(policyPath, data);
}),
);
await fs.mkdir(METADATA_DIR, { recursive: true });
await fs.writeFile(path.join(METADATA_DIR, 'modules.json'), JSON.stringify(sortedRepos, null, 2));
console.info('Updating joi dependencies...');
const packageJson = JSON.parse(await fs.readFile(PACKAGE_JSON_PATH, 'utf8'));
const joiMajors = Object.keys(modules.joi.compatibility);
const joiRepo = repos.joi;
let changed = false;
for (const majorStr of joiMajors) {
const major = parseInt(majorStr, 10);
const depName = `joi-${major}`;
const latestVersion = joiRepo?.versionsArray?.find((v) => Semver.major(v) === major);
if (latestVersion) {
const depValue = `npm:joi@${latestVersion}`;
if (packageJson.dependencies[depName] !== depValue) {
packageJson.dependencies[depName] = depValue;
changed = true;
}
} else {
console.warn(`Could not find latest version for joi major ${major}`);
}
}
if (changed) {
await fs.writeFile(PACKAGE_JSON_PATH, `${JSON.stringify(packageJson, null, 2)}\n`);
console.info('Running pnpm install...');
execFileSync('pnpm', ['install'], { stdio: 'inherit' });
}
// Generate module/index.md
const moduleIndexMdPath = path.join(MODULE_DIR, 'index.md');
const moduleIndexContent = `# Modules
The joi ecosystem consists of several modules.
<ModuleIndex />
`;
await fs.mkdir(MODULE_DIR, { recursive: true });
await fs.writeFile(moduleIndexMdPath, moduleIndexContent);
console.info('Running oxfmt...');
try {
execFileSync('oxfmt', ['./generated'], { stdio: 'inherit' });
// Apparently oxfmt sometimes needs a 2nd pass
execFileSync('oxfmt', ['./generated'], { stdio: 'inherit' });
} catch (error: unknown) {
console.error('Failed to run oxfmt:', error instanceof Error ? error.message : error);
}