-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-docs.ts
369 lines (300 loc) · 9.45 KB
/
generate-docs.ts
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
import fs from "fs";
import path from "path";
import shell from "shelljs";
import { runner } from "../src";
import { globToItemList } from "../src/utils";
import type { TRunnerResult } from "../src";
const SOURCE_REGEX =
/^\s*\/\/ <(?<marker>DOCSTART|DOCEND) SOURCE (?<key>[^\s]+)>\s*$/;
const TARGET_REGEX =
/^\s*<!-- <(?<marker>DOCSTART|DOCEND) TARGET (?<key>[^\s]+)> -->\s*$/;
const ROOT_DIR_PATH = path.resolve(__dirname, "..");
const README_FILE_PATH = path.resolve(ROOT_DIR_PATH, "README.md");
main().catch((error) => {
console.error(error);
process.exit(1);
});
async function main() {
const shouldWrite = process.argv.includes("--write");
// First, copy docstrings from source code to the README
const dependencyPathList = await codegen({ shouldWrite });
if (shouldWrite) {
// Then stamp the file
await stamp({ dependencyPathList, shouldWrite });
// Run Prettier
fatalExec("prettier --write README.md");
// For this particular markdown file, Prettier needs to make significant changes
// (such as updating some triple backticks to quadruple backticks), so we'll need to
// stamp the file again (i.e. update the stamp) after Prettier finishes
await stamp({ dependencyPathList, shouldWrite });
}
// Finally, verify
const finalRunnerResult = await stamp({ dependencyPathList, shouldWrite });
if (
finalRunnerResult.status !== "OK" ||
finalRunnerResult.didWrite !== false
) {
console.error(finalRunnerResult);
throw new Error(
`Expected runner result to be "OK", got ${finalRunnerResult.status}`
);
}
}
async function stamp({
dependencyPathList,
shouldWrite,
}: {
dependencyPathList: Array<string>;
shouldWrite: boolean;
}): Promise<TRunnerResult> {
const runnerResult = await runner({
targetFilePath: README_FILE_PATH,
dependencyGlobList: dependencyPathList,
shouldWrite,
initialStampPlacer: ({ content, stamp }) => {
const lineList = content.split("\n");
const startIndex = lineList.findIndex((line) =>
line.includes(`<!-- <CODESTAMP START> -->`)
);
invariant(startIndex !== -1, `Couldn't found start line`);
const endIndex = lineList.findIndex((line) =>
line.includes(`<!-- <CODESTAMP END> -->`)
);
invariant(endIndex !== -1, `Couldn't found end line`);
lineList.splice(
startIndex + 1,
0,
` - And here's the stamp: \`${stamp}\``
);
return lineList.join("\n");
},
initialStampRemover: ({ content, stamp }) => {
const lineList = content.split("\n");
const startIndex = lineList.findIndex((line) =>
line.includes(`<!-- <CODESTAMP START> -->`)
);
invariant(startIndex !== -1, `Couldn't found start line`);
const endIndex = lineList.findIndex((line) =>
line.includes(`<!-- <CODESTAMP END> -->`)
);
invariant(endIndex !== -1, `Couldn't found end line`);
lineList.splice(startIndex + 1, endIndex - startIndex - 1);
return lineList.join("\n");
},
fileTransformerForHashing: (param) => {
if (param.type === "DEPENDENCY") {
return param.content;
}
if (path.extname(param.absoluteFilePath) !== ".md") {
throw new Error(`Expected a .md file, got ${param.absoluteFilePath}`);
}
// Remove all empty lines and whitespaces before hashing
return param.content
.split("\n")
.filter((line) => !line.includes(param.stamp)) // also exclude the stamp line
.map((line) => line.trim())
.filter(Boolean)
.join("\n");
},
silent: false,
});
if (runnerResult.shouldFatalIfDesired) {
process.exit(1);
}
return runnerResult;
}
async function codegen({
shouldWrite,
}: {
shouldWrite: boolean;
}): Promise<Array<string>> {
const result: Array<string> = [];
const markdownContent = await fs.promises.readFile(README_FILE_PATH, "utf-8");
const markdownLineList = markdownContent.split("\n");
const instructionList = getInsertionInstructionList(markdownLineList);
const sourceCodeContentMap = await genSourceCodeContentMap();
for (const instruction of instructionList) {
const { keyToInsertAfter } = instruction;
const markdownSegment = markdownLineList
.slice(instruction.start, instruction.end + 1)
.join("\n");
result.push(markdownSegment);
if (keyToInsertAfter == null) {
continue;
}
const contentToInsert = sourceCodeContentMap[keyToInsertAfter]?.content;
if (contentToInsert == null) {
throw new Error(
`Key "${keyToInsertAfter}" was not found in the source code`
);
}
result.push(transformContent(contentToInsert));
}
if (shouldWrite) {
await fs.promises.writeFile(README_FILE_PATH, result.join("\n"), "utf-8");
}
return [
...new Set(
Object.keys(sourceCodeContentMap).map(
(key) => sourceCodeContentMap[key]!.absoluteFilePath!
)
),
];
}
function transformContent(rawContent: string): string {
let content = rawContent;
if (rawContent[rawContent.length - 1] === "{") {
content = rawContent.substring(0, rawContent.length - 1);
}
return ["```typescript", content, "```"].join("\n");
}
type TSourceCodeContentMap = {
[key: string]: {
content: string;
absoluteFilePath: string;
};
};
async function genSourceCodeContentMap(): Promise<TSourceCodeContentMap> {
const contentMap: TSourceCodeContentMap = {};
const sourceFileList = await globToItemList({
rawPattern: "src/*.ts",
cwd: ROOT_DIR_PATH,
});
for (const sourceFile of sourceFileList) {
const { absoluteFilePath } = sourceFile;
const lineList = sourceFile.content.split("\n");
const markerMap = getMarkerMap({ lineList, regex: SOURCE_REGEX });
for (const key in markerMap) {
const { DOCSTART, DOCEND } = markerMap[key]!;
const content = lineList
.slice(DOCSTART.index + 1, DOCEND.index)
.join("\n");
if (!content.includes(key)) {
throw new Error(`Content doesn't include key: ${key}`);
}
if (contentMap[key] != null) {
throw new Error(`Duplicate key found: ${key}`);
}
contentMap[key] = { content, absoluteFilePath };
}
}
return contentMap;
}
type TMarkerMap = {
[key: string]: {
DOCSTART: { rawLine: string; index: number; key: string };
DOCEND: { rawLine: string; index: number; key: string };
};
};
function getMarkerMap({
lineList,
regex,
}: {
lineList: Array<string>;
regex: RegExp;
}): TMarkerMap {
const markerMap: TMarkerMap = {};
lineList.forEach((line, index) => {
const maybeMatch = line.match(regex);
if (maybeMatch) {
const key = maybeMatch.groups!.key!;
const marker = maybeMatch.groups!.marker!;
if (marker !== "DOCEND" && marker !== "DOCSTART") {
throw new Error(`Unknown marker ${marker}`);
}
markerMap[key] = markerMap[key] ?? ({} as any);
if (markerMap[key]![marker] != null) {
throw new Error(`Duplicate marker found for ${key}: ${marker}`);
}
markerMap[key]![marker] = {
rawLine: line,
index,
key,
};
}
});
const sortedMarkerMap = sortObject(
markerMap,
(item1, item2) => item1.value.DOCSTART.index - item2.value.DOCSTART.index
);
// Sanity check
Object.keys(sortedMarkerMap).forEach((key, index, keyList) => {
const item = sortedMarkerMap[key]!;
invariant(item.DOCSTART.index < item.DOCEND.index);
if (index !== keyList.length - 1) {
const nextKey = keyList[index + 1]!;
const nextItem = sortedMarkerMap[nextKey]!;
invariant(item.DOCEND.index < nextItem.DOCSTART.index);
}
});
return sortedMarkerMap;
}
type TInsertionInstructionList = Array<{
// All inclusive
start: number;
end: number;
keyToInsertAfter: string | null;
}>;
function getInsertionInstructionList(
lineList: Array<string>
): TInsertionInstructionList {
const insertionOrder: TInsertionInstructionList = [];
const markerMap = getMarkerMap({
lineList,
regex: TARGET_REGEX,
});
const keyList = Object.keys(markerMap);
keyList.forEach((key, keyIndex) => {
if (keyIndex === 0) {
// First item
insertionOrder.push({
start: 0,
end: markerMap[key]!.DOCSTART.index,
keyToInsertAfter: key,
});
} else {
const previousKey = keyList[keyIndex - 1]!;
insertionOrder.push({
start: markerMap[previousKey]!.DOCEND.index,
end: markerMap[key]!.DOCSTART.index,
keyToInsertAfter: key,
});
}
// Last item, extra push
if (keyIndex === keyList.length - 1) {
insertionOrder.push({
start: markerMap[key]!.DOCEND.index,
end: lineList.length - 1,
keyToInsertAfter: null,
});
}
});
return insertionOrder;
}
function sortObject<V>(
input: { [key: string]: V },
fn: (a: { key: string; value: V }, b: { key: string; value: V }) => number
): { [key: string]: V } {
const result: { [key: string]: V } = {};
const sortedInputList: Array<{ key: string; value: V }> = Object.keys(input)
.map((key) => ({ key, value: input[key]! }))
.sort(fn);
for (const { key, value } of sortedInputList) {
result[key] = value;
}
return result;
}
function invariant(condition: any, errorMessage?: string) {
if (!condition) {
throw new Error(errorMessage ?? `Unexpected ${condition}`);
}
}
function fatalExec(command: string): void {
const result = shell.exec(command, {
silent: false,
fatal: true,
});
if (result.code !== 0) {
throw result;
}
}