forked from dlang/dlang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chmgen.d
499 lines (412 loc) · 13.7 KB
/
chmgen.d
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// D HTML to CHM converter/generator
// By Vladimir Panteleev <vladimir@thecybershadow.net> (2007-2015)
// Placed in the Public Domain
// Written in the D Programming Language, version 2
import std.algorithm;
import std.exception;
import std.file;
import std.getopt;
import std.range;
import std.stdio : File, stderr;
import std.string;
import std.regex;
import std.path;
string docRoot = `.`;
// ********************************************************************
struct KeyLink { string anchor; int confidence; bool sawAnchor; }
KeyLink[string][string] keywords; // keywords[keyword][original url w/o anchor] = anchor/confidence
string[] keywordList; // Sorted alphabetically, case-insensitive
bool[string] sawAnchor;
void addKeyword(string keyword, string link, int confidence, bool isAnchor = true)
{
keyword = keyword.strip();
if (!keyword.length)
return;
link = link.strip();
while (link.skipOver("./")) {}
if (link.endsWith("/"))
link ~= "index.html";
string file = link.stripAnchor();
string anchor = link.getAnchor();
if (keyword !in keywords
|| file !in keywords[keyword]
|| keywords[keyword][file].confidence < confidence)
keywords[keyword][file] = KeyLink(anchor, confidence);
if (anchor.length)
{
if (link !in sawAnchor)
sawAnchor[link] = false;
if (isAnchor)
sawAnchor[link] = true;
}
}
class Page
{
string fileName, title;
}
Page[string] pages;
// ********************************************************************
void main(string[] args)
{
bool onlyTags;
getopt(args,
"only-tags", &onlyTags,
"root", &docRoot,
);
bool chm = !onlyTags;
if (chm)
{
if (exists(`chm`))
rmdirRecurse(`chm`);
mkdirRecurse(`chm/files`);
}
enforce(exists(docRoot ~ `/phobos/index.html`),
`Phobos documentation not present. Please place Phobos documentation HTML files into the "phobos" subdirectory.`);
string[] files = chain(
dirEntries(docRoot ~ `/` , "*.html", SpanMode.shallow),
dirEntries(docRoot ~ `/phobos/` , "*.html", SpanMode.shallow),
dirEntries(docRoot ~ `/spec/` , "*.html", SpanMode.shallow),
dirEntries(docRoot ~ `/changelog/`, "*.html", SpanMode.shallow),
// dirEntries(docRoot ~ `/js/` , SpanMode.shallow),
dirEntries(docRoot ~ `/css/` , SpanMode.shallow),
dirEntries(docRoot ~ `/images/` , "*.*" , SpanMode.shallow),
only(docRoot ~ `/favicon.ico`)
).array();
foreach (filePath; files)
{
scope(failure) stderr.writeln("Error while processing file: ", filePath);
auto page = new Page;
auto fileName = page.fileName = filePath[docRoot.length+1 .. $].forwardSlashes();
pages[fileName] = page;
auto outPath = `chm/files/` ~ fileName;
outPath.dirName().mkdirRecurse();
if (fileName.endsWith(`.html`))
{
stderr.writeln("Processing ", fileName);
auto src = filePath.readText();
// Find title
foreach (m; src.match(re!`<title>(.*?) - D Programming Language</title>`))
page.title = m.captures[1];
// Add document CSS class
src = src.replaceAll(re!`(<body id='.*?' class='.*?)('>)`, `$1 chm$2`);
// Fix links
enum attrs = `(?:(?:\w+=\"[^"]*\")?\s*)*`;
src = src.replaceAll(re!(`(<a `~attrs~`href="\.\.?)"`), `$1/index.html"`);
// Find anchors
enum name = `(?:name|id)`;
foreach (m; src.matchAll(re!(`<a `~attrs~name~`="(\.?[^"]*)"`~attrs~`>(.*?)</a>`)))
addKeyword(m.captures[2].replaceAll(re!`<.*?>`, ``), fileName ~ "#" ~ m.captures[1], 5);
foreach (m; src.matchAll(re!(`<a `~attrs~name~`="(\.?([^"]*?)(\.\d+)?)"`~attrs~`>`)))
addKeyword(m.captures[2], fileName ~ "#" ~ m.captures[1], 1);
foreach (m; src.matchAll(re!(`<div class="quickindex" id="(quickindex\.(.+?))"></div>`)))
addKeyword(m.captures[2], fileName ~ "#" ~ m.captures[1], 1);
foreach (m; src.matchAll(re!(`<a `~attrs~`href="([^"]*)"`~attrs~`>(.*?)</a>`)))
if (!m.captures[1].canFind("://"))
addKeyword(m.captures[2].replaceAll(re!`<.*?>`, ``), absoluteUrl(fileName, m.captures[1].strip()), 4, false);
// Disable scripts
src = src.replaceAll(re!`<script.*?</script>`, ``);
src = src.replaceAll(re!`<script.*?\bsrc=.*?>`, ``);
// Remove external stylesheets
src = src.replaceAll(re!`<link rel="stylesheet" href="http.*?>`, ``);
if (chm)
std.file.write(outPath, src);
}
else
{
if (chm)
{
stderr.writeln("Copying ", fileName);
copy(filePath, outPath);
}
}
}
foreach (keyword, urlList; keywords)
keywordList ~= keyword;
keywordList.multiSort!(q{icmp(a, b) < 0}, q{a < b});
if (chm)
{
loadNavigation();
lint();
writeCHM();
}
writeTags();
stderr.writeln("Done!");
}
// ************************************************************
class Nav
{
string title, url;
Nav[] children;
}
Nav nav;
void loadNavigation()
{
stderr.writeln("Loading navigation");
import std.json;
auto text = "chm-nav.json"
.readText()
.replace("\r", "")
.replace("\n", "")
// .replaceAll(re!`/\*.*?\*/`, "")
.replaceAll(re!`,\s*\]`, `]`)
;
scope(failure) std.file.write("error.json", text);
auto json = text.parseJSON();
Nav[string] subNavs;
foreach_reverse (node; json.array)
{
auto hook = node["hook"].str;
auto root = node["root"].str;
Nav parseNav(JSONValue json)
{
if (json.type == JSON_TYPE.ARRAY)
{
auto nodes = json.array;
auto parsedNodes = nodes.map!parseNav.array().filter!`a`.array();
if (!parsedNodes.length)
{
if (/*warn*/true)
stderr.writeln("Warning: Empty navigation group");
return null;
}
auto root = parsedNodes[0];
root.children = parsedNodes[1..$];
return root;
}
else
{
auto obj = json.object;
auto nav = new Nav;
nav.title = obj["t"].str.strip();
if ("a" in obj)
{
auto url = absoluteUrl(root, obj["a"].str.strip());
if (url.canFind(`://`))
{
stderr.writeln("Skipping external navigation item: " ~ url);
return null;
}
else
if (!exists(`chm/files/` ~ url))
{
if (/*warn*/true)
stderr.writeln("Warning: Item in navigation does not exist: " ~ url);
else
stderr.writeln("Skipping non-existent navigation item: " ~ url);
//url = "http://dlang.org/" ~ url;
return null;
}
else
nav.url = `files\` ~ url.backSlashes();
}
auto psubNav = nav.title in subNavs;
if (psubNav)
{
// if (nav.title != psubNav.title)
// stderr.writefln("Warning: Sub-navigation title mismatch: %s / %s", nav.title, psubNav.title);
// if (nav.url != psubNav.url)
// stderr.writefln("Warning: Sub-navigation url mismatch: %s / %s", nav.url, psubNav.url);
nav.url = psubNav.url;
nav.children = psubNav.children;
}
return nav;
}
}
auto nav = parseNav(node["nav"]);
subNavs[hook] = nav;
}
.nav = subNavs[""];
}
// ************************************************************
void lint()
{
// Unknown URLs (links to pages we did not see)
{
bool[string] unknownPages;
foreach (keyword; keywordList)
foreach (page, link; keywords[keyword])
if (page !in pages)
unknownPages[page] = true;
foreach (url; unknownPages.keys.sort())
stderr.writeln("Warning: Unknown page: " ~ url);
}
// Unknown anchors
{
foreach (url; sawAnchor.keys.sort())
if (!sawAnchor[url])
stderr.writeln("Warning: Link to unknown anchor: " ~ url);
}
// Pages not in navigation
{
bool[string] sawPage;
void visit(Nav nav)
{
if (nav.url)
{
auto url = nav.url
[6..$] // strip "files/"
.forwardSlashes();
sawPage[url] = true;
}
foreach (child; nav.children)
visit(child);
}
visit(nav);
foreach (url; pages.keys.sort())
if (url.endsWith(".html") && url !in sawPage)
stderr.writeln("Warning: Page not in navigation: " ~ url);
}
}
// ************************************************************
void writeCHM()
{
stderr.writeln("Writing project file");
auto f = File(`chm\d.hhp`, "wt");
f.writeln(
`[OPTIONS]
Binary Index=No
Compatibility=1.1 or later
Compiled file=d.chm
Contents file=d.hhc
Default Window=main
Default topic=files\index.html
Display compile progress=No
Full-text search=Yes
Index file=d.hhk
Language=0x409 English (United States)
Title=D
[WINDOWS]
main="D Programming Language","d.hhc","d.hhk","files\index.html","files\index.html",,,,,0x63520,,0x380e,[0,0,800,570],0x918f0000,,,,,,0
[FILES]`);
string[] htmlList;
foreach (page; pages)
if (page.fileName.endsWith(`.html`))
htmlList ~= `files\` ~ page.fileName.backSlashes();
htmlList.sort();
foreach (s; htmlList)
f.writeln(s);
f.writeln(`
[INFOTYPES]`);
f.close();
// ************************************************************
stderr.writeln("Writing TOC file");
void dumpNav(Nav nav, int level=0)
{
if (nav.title && (nav.url || nav.children.length))
{
auto t = "\t".replicate(level);
f.writeln(t,
`<LI><OBJECT type="text/sitemap">`
`<param name="Name" value="`, nav.title, `">`
`<param name="Local" value="`, nav.url, `">`
`</OBJECT>`);
if (nav.children.length)
{
f.writeln(t, `<UL>`);
foreach (child; nav.children)
dumpNav(child, level+1);
f.writeln(t, `</UL>`);
}
}
else
foreach (child; nav.children)
dumpNav(child, level);
}
f.open(`chm\d.hhc`, "wt");
f.writeln(
`<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML><BODY>
<OBJECT type="text/site properties"><param name="Window Styles" value="0x800025"></OBJECT>
<UL>`);
dumpNav(nav);
f.writeln(`</UL>
</BODY></HTML>`);
f.close();
// ************************************************************
stderr.writeln("Writing index file");
f.open(`chm\d.hhk`, "wt");
f.writeln(
`<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML><BODY>
<UL>`);
foreach (keyword; keywordList)
{
f.writeln(
` <LI> <OBJECT type="text/sitemap">
<param name="Name" value="`, keyword, `">`);
foreach (url; keywords[keyword].keys.sort())
if (url in pages)
{
f.writeln(
` <param name="Name" value="`, pages[url].title, `">
<param name="Local" value="files\`, url.backSlashes(), keywords[keyword][url].anchor, `">`);
}
f.writeln(
` </OBJECT>`);
}
f.writeln(
`</UL>
</BODY></HTML>`);
f.close();
}
// ************************************************************
void writeTags()
{
stderr.writeln("Writing tags file");
File f;
f.open(`d.tag`, "wt");
f.writeln("[");
foreach (keyword; keywordList)
{
static struct IndexEntry { string keyword; string[] urls; }
IndexEntry entry;
entry.keyword = keyword;
foreach (url, link; keywords[keyword])
if (url in pages)
entry.urls ~= `http://dlang.org/` ~ url ~ link.anchor;
f.writeln(entry, ",");
}
f.writeln("]");
f.close();
}
// ********************************************************************
string forwardSlashes(string s)
{
return s.replace(`\`, `/`);
}
// ' * '
string backSlashes(string s)
{
return s.replace(`/`, `\`);
}
string getAnchor(string s)
{
return s.findSplitBefore("#")[1];
}
string stripAnchor(string s)
{
return s.findSplit("#")[0];
}
string absoluteUrl(string base, string url)
{
if (url.canFind("://"))
return url;
assert(!base.canFind('\\'), format("%s", [base, url]));
assert(!url .canFind('\\'));
enforce(url.length, "Empty URL");
if (url[0]=='#')
return base ~ url;
auto pathSegments = base.length ? base.split(`/`)[0..$-1] : null;
auto urlSegments = url.split(`/`);
while (urlSegments.startsWith([`..`]))
{
urlSegments = urlSegments[1..$];
pathSegments = pathSegments[0..$-1];
}
return (pathSegments ~ urlSegments).join(`/`);
}
Regex!char re(string pattern, alias flags = [])()
{
static Regex!char r;
if (r.empty)
r = regex(pattern, flags);
return r;
}