-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathgenerate_katas_content.js
More file actions
852 lines (758 loc) · 24.9 KB
/
Copy pathgenerate_katas_content.js
File metadata and controls
852 lines (758 loc) · 24.9 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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/// <reference lib="es2022"/>
// @ts-check
/**
* Katas Taxonomy
*
* A Kata is a top-level container of educational items which are used to explain a particular topic.
*
* This file builds the content for all the Katas. The katas ordering is conveyed by JSON file where each
* string in the array represents a folder that contains all the data to build the kata.
*
* Each Kata is organized in a directory where an index.md file provides a description on how the kata must be composed.
*/
import {
existsSync,
mkdirSync,
readFileSync,
writeFileSync,
readdirSync,
statSync,
} from "node:fs";
import { basename, dirname, join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import mdit from "markdown-it";
import { plugin } from "./markdown_latex_plugin.js";
const md = mdit("commonmark");
md.use(plugin);
// Set up the Markdown renderer with KaTeX support for validation
import mk from "@vscode/markdown-it-katex";
const mdValidator = mdit("commonmark");
const katexOpts = {
enableMathBlockInHtml: true,
enableMathInlineInHtml: true,
throwOnError: true,
};
// @ts-expect-error: This isn't typed correctly for some reason
mdValidator.use(mk.default, katexOpts);
const validate = true; // Consider making this a command-line option
let emitHtml = true;
const forceRegeneration =
process.argv.includes("--force") || process.argv.includes("-f");
const scriptDirPath = dirname(fileURLToPath(import.meta.url));
const katasContentPath = join(
scriptDirPath,
"..",
"..",
"..",
"katas",
"content",
);
const katasGeneratedContentPath = join(scriptDirPath, "src");
const contentFileNames = {
katasIndex: "index.json",
kataMarkdown: "index.md",
};
function tryGetTitleFromMarkdown(markdown, errorPrefix) {
const result = /^# (.*)/.exec(markdown);
if (result?.length !== 2)
throw new Error(`${errorPrefix}\nCould not get title from markdown`);
return result[1];
}
function tryGetTitleFromSegment(segment, errorPrefix) {
// The segment that represents the title can only be a markdown segment.
if (segment.type !== "markdown") {
throw new Error(
`${errorPrefix}\n` +
`segment is expected to be the title but found a segment of type '${segment.type}' instead`,
);
}
// Check that the segment has just one line.
const linesCount = segment.markdown.split(/\r?\n/).length;
if (linesCount !== 1) {
throw new Error(
`${errorPrefix}\n` +
`A title segment must be 1 line, but ${linesCount} lines are present\n` +
`Hint: is the markdown missing a @[section] macro?`,
);
}
const title = tryGetTitleFromMarkdown(segment.markdown, errorPrefix);
return title;
}
function tryParseJSON(json, errorPrefix) {
let parsed;
try {
parsed = JSON.parse(json);
} catch (e) {
throw new Error(`${errorPrefix}\n${e}`, { cause: e });
}
return parsed;
}
function tryReadFile(filePath, errorPrefix) {
let content;
try {
content = readFileSync(filePath, "utf8");
} catch (e) {
throw new Error(`${errorPrefix}\n${e}`, { cause: e });
}
return content;
}
function identifyMissingProperties(properties, required) {
return required.filter((property) => !Object.hasOwn(properties, property));
}
function getSourceId(sourcePath, basePath) {
return relative(basePath, sourcePath).replaceAll(sep, "__");
}
function aggregateSources(paths, globalCodeSources) {
const codeSources = [];
for (const path of paths) {
const id = getSourceId(path, globalCodeSources.basePath);
if (!(id in globalCodeSources.sources)) {
const code = tryReadFile(path, "Could not read code dependency");
globalCodeSources.sources[id] = code;
}
codeSources.push(id);
}
return codeSources;
}
function resolveSvgSegment(properties, baseFolderPath) {
const requiredProperties = ["path"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`SVG macro is missing the following properties: ${missingProperties}`,
);
}
const svgPath = join(baseFolderPath, properties.path);
const svg = tryReadFile(
svgPath,
`Could not read the contents of the SVG file at ${svgPath}`,
);
// An SVG file is basically an HTML file. If it includes blank lines, this will
// cause issues when including in Markdown, as blank lines indicate the end of
// HTML content. Check for blank lines within the document.
if (/\n\s*\r?\n/.test(svg)) {
throw new Error(
`SVG file ${svgPath} includes blank lines, which will break the Markdown`,
);
}
properties["svg"] = svg;
}
function resolveEmbeddedContent(segments, baseFolderPath) {
for (const segment of segments) {
if (segment.type === "svg") {
resolveSvgSegment(segment.properties, baseFolderPath);
}
}
}
function appendToMarkdownSegment(markdownSegment, segmentToAppend) {
if (segmentToAppend.type === "markdown") {
markdownSegment.markdown += "\n" + segmentToAppend.markdown;
} else if (segmentToAppend.type === "svg") {
markdownSegment.markdown += "\n" + segmentToAppend.properties.svg;
} else {
throw new Error(
`Cannot append segment of type "${segmentToAppend.type}" into markdown segment`,
);
}
}
function coalesceIntoSingleMarkdownSegment(startingSegment, segmentsStack) {
const markdownSegment = { type: "markdown", markdown: "" };
appendToMarkdownSegment(markdownSegment, startingSegment);
const isCoalesceSupportedForSegment = (segment) =>
segment.type === "markdown" || segment.type === "svg";
while (
segmentsStack.length > 0 &&
isCoalesceSupportedForSegment(segmentsStack.at(-1))
) {
const currentSegment = segmentsStack.pop();
appendToMarkdownSegment(markdownSegment, currentSegment);
}
return markdownSegment;
}
function coalesceSegments(segments) {
const coalescedSegments = [];
const segmentsStack = segments.reverse();
while (segmentsStack.length > 0) {
let currentSegment = segmentsStack.pop();
let coalescedSegment;
if (currentSegment.type === "markdown" || currentSegment.type === "svg") {
coalescedSegment = coalesceIntoSingleMarkdownSegment(
currentSegment,
segmentsStack,
);
} else {
coalescedSegment = currentSegment;
}
coalescedSegments.push(coalescedSegment);
}
return coalescedSegments;
}
function preProcessSegments(segments, baseFolderPath) {
resolveEmbeddedContent(segments, baseFolderPath);
const coalescedSegments = coalesceSegments(segments);
return coalescedSegments;
}
function parseMarkdown(markdown) {
const segments = [];
const macroRegex = /@\[(?<type>\w+)\]\((?<json>\{.*?\})\)((\r?\n)|$)/gs;
let latestProcessedIndex = 0;
while (latestProcessedIndex < markdown.length) {
const match = macroRegex.exec(markdown);
if (match !== null) {
// If there is something between the last processed index and the start of the match that is not just whitespace,
// it represents a text segment.
const delta = match.index - latestProcessedIndex;
if (delta > 0) {
const textSegment = tryCreateMarkdownSegment(
markdown.substring(latestProcessedIndex, match.index),
);
if (textSegment !== null) {
segments.push(textSegment);
}
}
// Create a segment that corresponds to the found macro.
const macroSegment = createMacroSegment(match);
segments.push(macroSegment);
latestProcessedIndex = macroRegex.lastIndex;
} else {
// No more matches were found, create a text segment with the remaining content.
const textSegment = tryCreateMarkdownSegment(
markdown.substring(latestProcessedIndex, markdown.length),
);
if (textSegment !== null) {
segments.push(textSegment);
}
latestProcessedIndex = markdown.length;
}
}
return segments;
}
function createExample(baseFolderPath, properties) {
// Validate that the data contains the required properties.
const requiredProperties = ["id", "codePath"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`Example macro is missing the following properties: ${missingProperties}`,
);
}
// Generate the object using the macro properties.
const codePath = join(baseFolderPath, properties.codePath);
const code = tryReadFile(
codePath,
`Could not read the contents of the example code file at ${codePath}`,
);
return {
type: "example",
id: properties.id,
code,
};
}
function createTextContent(markdown) {
if (validate) {
try {
mdValidator.render(markdown);
} catch (e) {
console.log("LaTeX validation error: ", e);
}
}
return {
type: "text-content",
content: emitHtml ? md.render(markdown) : markdown,
};
}
function createSolution(baseFolderPath, properties) {
// Validate that the data contains the required properties.
const requiredProperties = ["id", "codePath"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`Solution macro is missing the following properties: ${missingProperties}`,
);
}
// Generate the object using the macro properties.
const codePath = join(baseFolderPath, properties.codePath);
const code = tryReadFile(
codePath,
`Could not read the contents of the solution code file at ${codePath}`,
);
return {
type: "solution",
id: properties.id,
code,
};
}
function createExplainedSolution(markdownFilePath) {
const markdown = tryReadFile(
markdownFilePath,
`Could not read solution markdown file at ${markdownFilePath}`,
);
const solutionFolderPath = dirname(markdownFilePath);
const rawSegments = parseMarkdown(markdown);
const segments = preProcessSegments(rawSegments, solutionFolderPath);
const solutionItems = [];
for (const segment of segments) {
let solutionItem = null;
if (segment.type === "example") {
solutionItem = createExample(solutionFolderPath, segment.properties);
} else if (segment.type === "solution") {
solutionItem = createSolution(solutionFolderPath, segment.properties);
} else if (segment.type === "markdown") {
solutionItem = createTextContent(segment.markdown);
}
if (solutionItem !== null) {
solutionItems.push(solutionItem);
}
}
return {
type: "explained-solution",
items: solutionItems,
};
}
function createAnswer(markdownFilePath) {
const markdown = tryReadFile(
markdownFilePath,
`Could not read answer markdown file at ${markdownFilePath}`,
);
const answerFolderPath = dirname(markdownFilePath);
const rawSegments = parseMarkdown(markdown);
const segments = preProcessSegments(rawSegments, answerFolderPath);
const items = [];
for (const segment of segments) {
let answerItem = null;
if (segment.type === "example") {
answerItem = createExample(answerFolderPath, segment.properties);
} else if (segment.type === "markdown") {
answerItem = createTextContent(segment.markdown);
}
if (answerItem !== null) {
items.push(answerItem);
}
}
return { type: "answer", items };
}
function createQuestion(kataPath, properties) {
// Validate that the data contains the required properties.
const requiredProperties = ["descriptionPath", "answerPath"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`Question macro is missing the following properties\n` +
`${missingProperties}\n` +
`Macro properties:\n` +
`${JSON.stringify(properties, undefined, 2)}`,
);
}
// Generate the object using the macro properties.
const descriptionMarkdown = tryReadFile(
join(kataPath, properties.descriptionPath),
`Could not read description for question ${properties.id}`,
);
const description = createTextContent(descriptionMarkdown);
const answer = createAnswer(join(kataPath, properties.answerPath));
return {
type: "question",
description,
answer,
};
}
function createExerciseSection(kataPath, properties, globalCodeSources) {
// Validate that the data contains the required properties.
const requiredProperties = ["id", "title", "path"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`Exercise macro is missing the following properties\n` +
`${missingProperties}\n` +
`Macro properties:\n` +
`${JSON.stringify(properties, undefined, 2)}`,
);
}
const exercisePath = join(kataPath, properties.path);
// Generate the object using the macro properties.
// Get the description from the index.md file in the exercise folder.
let descriptionMarkdown = tryReadFile(
join(exercisePath, "index.md"),
`Could not read index.md file for exercise ${properties.id}`,
);
// Strip inline hint blocks from exercise descriptions when requested.
// The VS Code extension provides hints through a separate AI-powered
// button instead of the embedded <details> blocks.
const hintPattern =
/<details>\s*<summary>[\s\S]*?Need a hint[\s\S]*?<\/summary>([\s\S]*?)<\/details>/gi;
let extractedHints;
if (!emitHtml) {
// Capture the inner content of each hint block before stripping.
extractedHints = [...descriptionMarkdown.matchAll(hintPattern)].map((m) =>
m[1].trim(),
);
descriptionMarkdown = descriptionMarkdown.replace(hintPattern, "").trim();
}
const description = createTextContent(descriptionMarkdown);
// Aggregate the exercise sources. The verification source file is Verification.qs.
let resolvedVerificationFile = join(exercisePath, "Verification.qs");
// Implicit dependencies to simplify dependency handling:
// ../KatasLibrary.qs must be included
// ./Common.qs must be included if present in current kata
const implicitDependencies = ["../KatasLibrary.qs"];
if (existsSync(join(kataPath, "./Common.qs"))) {
implicitDependencies.push("./Common.qs");
}
const resolvedDependencies = implicitDependencies.map((path) =>
join(kataPath, path),
);
const resolvedSources = [resolvedVerificationFile].concat(
resolvedDependencies,
);
const sourceIds = aggregateSources(resolvedSources, globalCodeSources);
// Get the placeholder code from the Placeholder.qs file in the exercise folder.
const placeholderCode = tryReadFile(
join(exercisePath, "Placeholder.qs"),
`Could not read Placeholder.qs file for exercise '${properties.id}'`,
);
// Get the solution from the solution.md file in the exercise folder.
const explainedSolution = createExplainedSolution(
join(exercisePath, "solution.md"),
);
return {
type: "exercise",
id: properties.id,
title: properties.title,
description,
sourceIds,
placeholderCode,
explainedSolution,
...(extractedHints && extractedHints.length > 0
? { hints: extractedHints }
: {}),
};
}
function createLessonSection(kataPath, properties, segmentsStack) {
// Validate that the data contains the required properties.
const requiredProperties = ["id", "title"];
const missingProperties = identifyMissingProperties(
properties,
requiredProperties,
);
if (missingProperties.length > 0) {
throw new Error(
`Section macro is missing the following properties\n` +
`${missingProperties}\n` +
`Macro properties:\n` +
`${JSON.stringify(properties, undefined, 2)}`,
);
}
// Continue processing segments until another section-delimiting segment appears.
const lessonItems = [];
const isSectionDelimiterSegment = (segment) =>
segment.type === "exercise" || segment.type === "section";
while (
segmentsStack.length > 0 &&
!isSectionDelimiterSegment(segmentsStack.at(-1))
) {
const currentSegment = segmentsStack.pop();
let lessonItem = null;
if (currentSegment.type === "example") {
lessonItem = createExample(kataPath, currentSegment.properties);
} else if (currentSegment.type === "markdown") {
lessonItem = createTextContent(currentSegment.markdown);
} else if (currentSegment.type === "question") {
lessonItem = createQuestion(kataPath, currentSegment.properties);
}
// Check that a valid lesson item was created.
if (lessonItem === null) {
throw new Error(
`Lesson item could not be generated for segment of type '${currentSegment.type}'\n` +
`segment:\n` +
`${JSON.stringify(currentSegment, undefined, 2)}`,
);
}
lessonItems.push(lessonItem);
}
return {
type: "lesson",
id: properties.id,
title: properties.title,
items: lessonItems,
};
}
function createMacroSegment(match) {
const type = match.groups.type;
const propertiesJson = match.groups.json;
const properties = tryParseJSON(
propertiesJson,
`Invalid JSON for macro of type ${type}.\n` + `JSON: ${propertiesJson}`,
);
return {
type,
properties,
};
}
function tryCreateMarkdownSegment(text) {
const trimmedText = text.trim();
if (trimmedText.length > 0) {
return { type: "markdown", markdown: trimmedText };
}
return null;
}
function createKata(
kataPath,
id,
title,
segments,
globalCodeSources,
published,
) {
// Validate that the kata has at least one segment.
if (segments.length === 0) {
throw new Error(`Kata '${id}' does not have any segments`);
}
// Create sections from the segments in the stack.
// Use the array of segments as a stack to keep track of the segments that have not been processed.
const segmentsStack = segments.reverse();
const sections = [];
while (segmentsStack.length > 0) {
const currentSegment = segmentsStack.pop();
let section = null;
if (currentSegment.type === "exercise") {
section = createExerciseSection(
kataPath,
currentSegment.properties,
globalCodeSources,
);
} else if (currentSegment.type === "section") {
section = createLessonSection(
kataPath,
currentSegment.properties,
segmentsStack,
);
}
// Check if a valid section was created.
if (section === null) {
throw new Error(
`Unexpected segment of type '${currentSegment.type}'\n` +
`segment:\n` +
`${JSON.stringify(currentSegment, undefined, 2)}\n` +
`Hint: is the markdown missing a @[section] macro?`,
);
}
sections.push(section);
}
return {
id,
title,
sections,
published,
};
}
function generateKataContent(path, globalCodeSources, published) {
console.log(`- Creating content for kata at: ${path}`);
const markdownPath = join(path, contentFileNames.kataMarkdown);
const markdown = tryReadFile(
markdownPath,
"Could not read the contents of the kata markdown file",
);
const kataId = basename(path);
const rawSegments = parseMarkdown(markdown);
// The first segment in the kata must be the title.
const firstSegment = rawSegments.at(0);
const title = tryGetTitleFromSegment(
firstSegment,
`Could not get title for kata '${kataId}'`,
);
// Do not use the first segment since it was already processed to get the kata's title.
const segments = preProcessSegments(rawSegments.slice(1), path);
const kata = createKata(
path,
kataId,
title,
segments,
globalCodeSources,
published,
);
console.log(
`-- '${kata.id}' kata ${kata.published ? "" : "(unpublished)"} was successfully created`,
);
return kata;
}
function validateIdsUniqueness(katas) {
console.log("Validating IDs uniqueness across all katas");
const allIds = new Set();
const assertUniqueness = (id) => {
const idAlreadyExists = allIds.has(id);
if (idAlreadyExists) {
throw new Error(`"${id}" is not unique`);
}
allIds.add(id);
};
for (const kata of katas) {
// Check kata IDs are unique.
assertUniqueness(kata.id);
for (const section of kata.sections) {
// Check section IDs are unique.
assertUniqueness(section.id);
if (section.type === "exercise") {
// Check IDs for examples and solutions within exercises are unique.
section.explainedSolution.items.forEach((item) => {
if (item.type === "example" || item.type === "solution") {
assertUniqueness(item.id);
}
});
} else if (section.type === "lesson") {
// Check IDs for examples within lessons are unique.
section.items.forEach((item) => {
if (item.type === "example") {
assertUniqueness(item.id);
}
});
}
}
}
}
function generateKatasContent(katasPath, outputPath) {
console.log("Generating katas content");
const indexPath = join(katasPath, contentFileNames.katasIndex);
const indexJson = tryReadFile(
indexPath,
"Could not read the contents of the katas index file",
);
const publishedKatasDirs = tryParseJSON(
indexJson,
`Invalid katas index at ${indexPath}`,
);
const unpublishedKatasDirs = readdirSync(katasPath, { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name)
.filter((dir) => !publishedKatasDirs.includes(dir));
// Unpublished katas are listed after published in alphabetical order
const allKatasDirs = publishedKatasDirs.concat(unpublishedKatasDirs);
// Initialize an object where all the global code sources will be aggregated.
const globalCodeSourcesContainer = {
basePath: katasPath,
sources: {},
};
// Generate an object for each kata and update the global code sources with the code they reference.
var katas = [];
for (const kataDir of allKatasDirs) {
const kataPath = join(katasPath, kataDir);
const published = publishedKatasDirs.includes(kataDir);
const kata = generateKataContent(
kataPath,
globalCodeSourcesContainer,
published,
);
katas.push(kata);
}
// Create the objects that will be written to a file.
const globalCodeSources = [];
for (let id in globalCodeSourcesContainer.sources) {
globalCodeSources.push({
id: id,
code: globalCodeSourcesContainer.sources[id],
});
}
// Validate the uniqueness of IDs.
validateIdsUniqueness(katas);
// Save the JS object to a file.
const katasContent = {
katas: katas,
globalCodeSources: globalCodeSources,
};
if (!existsSync(outputPath)) {
mkdirSync(outputPath);
}
const contentJsPath = join(
outputPath,
emitHtml ? "katas-content.generated.ts" : "katas-content.generated.md.ts",
);
writeFileSync(
contentJsPath,
`export default ${JSON.stringify(katasContent, undefined, 2)}`,
"utf-8",
);
}
function needsRegeneration(katasPath, outputPath) {
if (forceRegeneration) {
return true;
}
const outputFiles = [
join(outputPath, "katas-content.generated.ts"),
join(outputPath, "katas-content.generated.md.ts"),
];
// Check if any output file is missing
for (const outputFile of outputFiles) {
if (!existsSync(outputFile)) {
console.log(`Output file ${outputFile} missing`);
return true;
}
}
// Get the oldest output file timestamp
let oldestOutputTime = Infinity;
for (const outputFile of outputFiles) {
try {
const stat = statSync(outputFile);
oldestOutputTime = Math.min(oldestOutputTime, stat.mtime.getTime());
} catch {
console.log(`Could not stat output file ${outputFile}`);
return true; // If we can't stat the file, regenerate
}
}
// Check if any input file is newer than the oldest output
function checkDirectory(dirPath) {
try {
const entries = readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
if (checkDirectory(fullPath)) return true;
} else {
try {
const stat = statSync(fullPath);
if (stat.mtime.getTime() > oldestOutputTime) {
console.log(
`Input file newer than output: ${relative(process.cwd(), fullPath)}`,
);
return true;
}
} catch {
// If we can't stat an input file, be safe and regenerate
console.log(`Could not stat input file ${fullPath}`);
return true;
}
}
}
} catch {
// If we can't read the directory, be safe and regenerate
console.log(`Could not read directory ${dirPath}`);
return true;
}
return false;
}
return checkDirectory(katasPath);
}
if (needsRegeneration(katasContentPath, katasGeneratedContentPath)) {
// Generate HTML and Markdown versions of the katas bundle
emitHtml = true;
generateKatasContent(katasContentPath, katasGeneratedContentPath);
emitHtml = false;
generateKatasContent(katasContentPath, katasGeneratedContentPath);
} else {
console.log("Content is up to date, skipping generation");
}