-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathfetch-readmes.mjs
More file actions
208 lines (185 loc) · 4.88 KB
/
Copy pathfetch-readmes.mjs
File metadata and controls
208 lines (185 loc) · 4.88 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
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const { GH_TOKEN } = process.env;
if (!GH_TOKEN) {
throw new Error('GH_TOKEN environment variable is not set');
}
const BASE_HEADERS = {
Authorization: `Bearer ${GH_TOKEN}`,
'X-GitHub-Api-Version': '2022-11-28',
};
const parseNextLink = linkHeader => {
if (!linkHeader) return null;
const match = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
return match ? match[1] : null;
};
const discoverRepos = async () => {
const loaders = [];
const plugins = [];
let url =
'https://api.github.com/orgs/webpack/repos?per_page=100&type=public';
while (url) {
const res = await fetch(url, { headers: BASE_HEADERS });
if (!res.ok)
throw new Error(
`Failed to list org repos: ${res.status} ${res.statusText}`
);
const repos = await res.json();
for (const repo of repos) {
if (repo.archived) continue;
if (repo.name.endsWith('-loader')) {
loaders.push(repo.full_name);
} else if (
repo.name.endsWith('-webpack-plugin') ||
repo.name.endsWith('-plugin')
) {
plugins.push(repo.full_name);
}
}
url = parseNextLink(res.headers.get('link'));
}
return { loaders, plugins };
};
const stripLeadingDiv = content =>
content.replace(/^\s*<div[\s\S]*?<\/div>\n*/i, '');
// Remove badge lines - lines consisting only of [![...][ref]][ref] or [](url) links
const stripBadges = content =>
content
.replace(
/^(\[!\[[^\]]*\](?:\[[^\]]*\]|\([^)]*\))\]\s*(?:\[[^\]]*\]|\([^)]*\))\s*)+$/gm,
''
)
.replace(/\n{3,}/g, '\n\n');
const SUPPORTED_LANGS = new Set([
'bash',
'c',
'c++',
'cjs',
'coffee',
'coffeescript',
'console',
'cpp',
'diff',
'docker',
'dockerfile',
'glsl',
'gql',
'graphql',
'http',
'ini',
'java',
'javascript',
'js',
'json',
'jsx',
'mjs',
'powershell',
'ps',
'ps1',
'regex',
'regexp',
'sh',
'shell',
'shellscript',
'shellsession',
'sql',
'ts',
'tsx',
'typescript',
'xml',
'yaml',
'yml',
'zsh',
]);
const sanitizeCodeFences = content =>
content.replace(/^```([a-zA-Z0-9_+-]+)\b/gm, (match, lang) =>
SUPPORTED_LANGS.has(lang.toLowerCase()) ? match : '```'
);
// remark-gfm does not support GitHub alert syntax (> [!TYPE]); rewrite to bold label inside the blockquote.
const GFM_ALERT_LABELS = {
NOTE: 'Note',
TIP: 'Tip',
IMPORTANT: 'Important',
WARNING: 'Warning',
CAUTION: 'Caution',
};
const GFM_ALERT_RE =
/^([ \t]*>[ \t]*)\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*$/gim;
const transformGfmAlerts = content =>
content.replace(
GFM_ALERT_RE,
(_, prefix, type) => `${prefix}**${GFM_ALERT_LABELS[type]}:**`
);
const processContent = content =>
transformGfmAlerts(sanitizeCodeFences(stripBadges(stripLeadingDiv(content))));
const fetchReadme = async fullName => {
const url = `https://api.github.com/repos/${fullName}/readme`;
const res = await fetch(url, {
headers: { ...BASE_HEADERS, Accept: 'application/vnd.github.raw' },
});
return res.ok
? { ok: true, text: await res.text() }
: { ok: false, status: res.status };
};
const processRepos = async (
repos,
{ layout, groupName, basePath, outputDir }
) => {
mkdirSync(outputDir, { recursive: true });
const repoName = r => r.split('/')[1];
console.log(
`Discovered ${groupName.toLowerCase()}: ${repos.map(repoName).join(', ')}`
);
const fetched = [];
for (const fullName of repos) {
const name = repoName(fullName);
const result = await fetchReadme(fullName);
if (!result.ok) {
console.log(`Failed: ${name} — ${result.status}`);
continue;
}
const content = `---\nlayout: ${layout}\n---\n\n${processContent(result.text)}`;
writeFileSync(join(outputDir, `${name}.md`), content, 'utf8');
fetched.push(name);
console.log(`Fetched: ${name}`);
}
const siteJson = {
sidebar: [
{
groupName,
items: fetched
.sort()
.map(name => ({ link: `${basePath}/${name}`, label: name })),
},
],
};
writeFileSync(
join(outputDir, 'site.json'),
JSON.stringify(siteJson, null, 2) + '\n',
'utf8'
);
console.log(
`Written: ${outputDir}/site.json (${fetched.length} ${groupName.toLowerCase()})`
);
};
const args = process.argv.slice(2);
const runLoaders = args.includes('--loaders') || args.length === 0;
const runPlugins = args.includes('--plugins') || args.length === 0;
const root = new URL('..', import.meta.url).pathname;
const { loaders, plugins } = await discoverRepos();
if (runLoaders) {
await processRepos(loaders, {
layout: 'loader',
groupName: 'Loaders',
basePath: '/loaders',
outputDir: join(root, 'pages/loaders'),
});
}
if (runPlugins) {
await processRepos(plugins, {
layout: 'plugin',
groupName: 'Plugins',
basePath: '/plugins',
outputDir: join(root, 'pages/plugins'),
});
}