-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfix-version-menu.js
More file actions
259 lines (230 loc) · 8.84 KB
/
fix-version-menu.js
File metadata and controls
259 lines (230 loc) · 8.84 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
#!/usr/bin/env node
/*
* fix-version-menu.js
*
* Post-processing step for a Docusaurus build: rewrites the version dropdown
* links in built HTML so that switching version keeps the user on the same
* page (matched by slug) instead of falling back to /GettingStarted/installation.
*
* Usage:
* node fix-version-menu.js [<gh-pages-dir>] [--dry-run] [--out <dir>]
*
* Defaults: gh-pages-dir = ./gh-pages
* Scope: only HTML files under each version's commands/ directory.
*
* --out <dir> Mirror the entire input tree to <dir> and apply the fixes
* there, leaving the input untouched. Output is a drop-in
* replacement for <gh-pages-dir>.
* --dry-run Print intended substitutions without writing anything.
*/
const fs = require('fs');
const path = require('path');
const argv = process.argv.slice(2);
const dryRun = argv.includes('--dry-run');
let outDir = null;
const positional = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === '--dry-run') continue;
if (a === '--out') {
outDir = argv[++i];
if (!outDir) {
console.error('--out requires a directory argument');
process.exit(1);
}
continue;
}
if (a.startsWith('--out=')) {
outDir = a.slice('--out='.length);
continue;
}
if (a.startsWith('--')) {
console.error(`Unknown flag: ${a}`);
process.exit(1);
}
positional.push(a);
}
const ghPagesDir = path.resolve(positional[0] || './gh-pages');
const outDirResolved = outDir ? path.resolve(outDir) : null;
if (!fs.existsSync(ghPagesDir) || !fs.statSync(ghPagesDir).isDirectory()) {
console.error(`Directory not found: ${ghPagesDir}`);
process.exit(1);
}
// --- Detect versions ----------------------------------------------------------
// version key "" = unversioned latest; otherwise the directory name ("21", "21-R2", "next", ...).
// A directory is treated as a version iff it contains a "commands/" subdirectory.
function urlPrefixFor(key) {
if (key === '') return '/docs/';
return `/docs/${key}/`;
}
const versions = [];
if (fs.existsSync(path.join(ghPagesDir, 'commands'))) {
versions.push({ key: '', dir: ghPagesDir, urlPrefix: '/docs/' });
}
for (const ent of fs.readdirSync(ghPagesDir, { withFileTypes: true })) {
if (!ent.isDirectory()) continue;
if (ent.name === 'commands') continue;
const sub = path.join(ghPagesDir, ent.name);
if (fs.existsSync(path.join(sub, 'commands'))) {
versions.push({ key: ent.name, dir: sub, urlPrefix: urlPrefixFor(ent.name) });
}
}
if (versions.length === 0) {
console.error(`No versions with a commands/ directory found under ${ghPagesDir}`);
process.exit(1);
}
// --- Build slug index per version --------------------------------------------
// A slug is the page path relative to the version root, without the .html suffix.
// e.g. gh-pages/21-R2/commands/alert.html -> "commands/alert" under key "21-R2".
function walk(dir, base, out) {
if (!fs.existsSync(dir)) return;
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) walk(p, base, out);
else if (ent.isFile() && ent.name.endsWith('.html')) {
const rel = path.relative(base, p).split(path.sep).join('/');
out.add(rel.replace(/\.html$/, ''));
}
}
}
const slugsByVersion = new Map();
for (const v of versions) {
const set = new Set();
walk(path.join(v.dir, 'commands'), v.dir, set);
slugsByVersion.set(v.key, set);
}
const versionKeys = new Set(versions.map((v) => v.key));
// --- Helpers ------------------------------------------------------------------
// A segment looks like a version if it's `next`, a known on-disk version,
// or matches the 4D version pattern (e.g. "18", "21-R2", "21R3").
function isVersionSegment(seg) {
if (versionKeys.has(seg)) return true;
if (seg === 'next') return true;
return /^\d+(?:-?R\d+)?$/.test(seg);
}
// Given an href like "/docs/<seg>/<rest>" or "/docs/<rest>", figure out which
// version the link belongs to. Returns { key, urlPrefix, rest } or null when
// the link points at a version we can't verify (e.g. an old version that
// isn't present on disk in this build).
function classifyHref(href) {
const m = href.match(/^\/docs\/(?:([^/]+)\/)?(.+)$/);
if (!m) return null;
const seg = m[1];
const rest = m[2];
if (seg !== undefined) {
if (versionKeys.has(seg)) {
return { key: seg, urlPrefix: urlPrefixFor(seg), rest };
}
if (isVersionSegment(seg)) {
// Version-shaped but not present on disk: we can't verify the target.
return null;
}
// First segment is a path component of the unversioned latest.
return { key: '', urlPrefix: '/docs/', rest: `${seg}/${rest}` };
}
return { key: '', urlPrefix: '/docs/', rest };
}
// Read the current page's slug from its active version-dropdown link.
function getPageSlug(html) {
const m = html.match(
/<a aria-current=page class="dropdown__link dropdown__link--active" href=([^ >]+)>/
);
if (!m) return null;
const c = classifyHref(m[1]);
return c ? c.rest : null;
}
// Rewrite a single <ul class=dropdown__menu>...</ul> block.
function rewriteDropdownBlock(block, pageSlug, fixes) {
return block.replace(/<a\b([^>]*?)>/g, (match, attrs) => {
if (!/\bclass=("dropdown__link[^"]*"|dropdown__link\b)/.test(attrs)) return match;
const hrefMatch = attrs.match(/(\bhref=)([^ >]+)/);
if (!hrefMatch) return match;
const oldHref = hrefMatch[2];
const c = classifyHref(oldHref);
if (!c) return match;
const targetSlugs = slugsByVersion.get(c.key);
if (!targetSlugs || !targetSlugs.has(pageSlug)) return match;
const newHref = c.urlPrefix + pageSlug;
if (newHref === oldHref) return match;
fixes.push({ from: oldHref, to: newHref });
const newAttrs = attrs.replace(/(\bhref=)([^ >]+)/, `$1${newHref}`);
return `<a${newAttrs}>`;
});
}
// --- Per-file processing ------------------------------------------------------
function processFile(file) {
const html = fs.readFileSync(file, 'utf8');
const slug = getPageSlug(html);
if (!slug) return { file, fixes: [], skipped: 'no active dropdown link' };
const blockRe = /<ul class=dropdown__menu>([\s\S]*?)<\/ul>/g;
const blocks = [];
let m;
while ((m = blockRe.exec(html)) !== null) {
blocks.push({ start: m.index, end: m.index + m[0].length, content: m[0], inner: m[1] });
}
const fixes = [];
let newHtml = html;
let offset = 0;
for (const b of blocks) {
// Skip the locale dropdown: its <a> items carry a `lang=` attribute.
if (/<a\b[^>]*\blang=/.test(b.inner)) continue;
const rewritten = rewriteDropdownBlock(b.content, slug, fixes);
if (rewritten !== b.content) {
newHtml =
newHtml.slice(0, b.start + offset) + rewritten + newHtml.slice(b.end + offset);
offset += rewritten.length - b.content.length;
}
}
return { file, slug, fixes, newHtml, changed: newHtml !== html };
}
// --- Walk and apply -----------------------------------------------------------
function* walkHtml(dir) {
if (!fs.existsSync(dir)) return;
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) yield* walkHtml(p);
else if (ent.isFile() && ent.name.endsWith('.html')) yield p;
}
}
// When --out is given, mirror the entire input tree first so the output is a
// drop-in replacement. Then we overwrite the in-scope HTML files we rewrite.
if (outDirResolved && !dryRun) {
if (path.relative(ghPagesDir, outDirResolved) === '' || outDirResolved === ghPagesDir) {
console.error('--out must point to a different directory than the input.');
process.exit(1);
}
fs.mkdirSync(outDirResolved, { recursive: true });
fs.cpSync(ghPagesDir, outDirResolved, { recursive: true });
}
let totalFixes = 0;
let totalFiles = 0;
for (const v of versions) {
for (const file of walkHtml(path.join(v.dir, 'commands'))) {
const result = processFile(file);
if (result.skipped) {
console.log(`${path.relative(process.cwd(), file)}: skipped (${result.skipped})`);
continue;
}
if (result.fixes.length === 0) continue;
totalFiles++;
totalFixes += result.fixes.length;
const rel = path.relative(process.cwd(), file);
const suffix = dryRun
? ' (dry-run)'
: outDirResolved
? ` -> ${path.relative(process.cwd(), path.join(outDirResolved, path.relative(ghPagesDir, file)))}`
: '';
console.log(`${rel}: ${result.fixes.length} link(s) fixed${suffix}`);
for (const fx of result.fixes) console.log(` ${fx.from} -> ${fx.to}`);
if (!dryRun && result.changed) {
const dest = outDirResolved
? path.join(outDirResolved, path.relative(ghPagesDir, file))
: file;
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, result.newHtml);
}
}
}
console.log(
`\nTotal: ${totalFixes} link(s) fixed across ${totalFiles} file(s)${dryRun ? ' (dry-run)' : ''}.`
);