|
| 1 | +import { parse } from "kdljs"; |
| 2 | +import type { Enum } from "./types"; |
| 3 | +import { readdir, readFile } from "fs/promises"; |
| 4 | +import { merge } from "./helpers.js"; |
| 5 | + |
| 6 | +/** |
| 7 | + * Converts patch files in KDL to match the [types](types.d.ts). |
| 8 | + */ |
| 9 | +function parseKDL(kdlText: string) { |
| 10 | + const { output, errors } = parse(kdlText); |
| 11 | + |
| 12 | + if (errors.length) { |
| 13 | + throw new Error("KDL parse errors", { cause: errors }); |
| 14 | + } |
| 15 | + |
| 16 | + const nodes = output!; |
| 17 | + const enums: Record<string, Enum> = {}; |
| 18 | + |
| 19 | + for (const node of nodes) { |
| 20 | + if (node.name === "enum") { |
| 21 | + handleEnum(node, enums); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return { enums: { enum: enums } }; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Handles an enum node by extracting its name and values. |
| 30 | + * Throws an error if the enum name is missing or if the values are not in the correct format. |
| 31 | + * @param node The enum node to handle. |
| 32 | + * @param enums The record of enums to update. |
| 33 | + */ |
| 34 | +function handleEnum(node: any, enums: Record<string, Enum>) { |
| 35 | + const name = node.values[0]; |
| 36 | + if (typeof name !== "string") { |
| 37 | + throw new Error("Missing enum name"); |
| 38 | + } |
| 39 | + const values: string[] = []; |
| 40 | + |
| 41 | + for (const child of node.children ?? []) { |
| 42 | + values.push(child.name); |
| 43 | + } |
| 44 | + |
| 45 | + enums[name] = { name, value: values }; |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Collect all file URLs in a directory. |
| 50 | + */ |
| 51 | +async function getAllFileURLs(folder: URL): Promise<URL[]> { |
| 52 | + const entries = await readdir(folder, { withFileTypes: true }); |
| 53 | + return entries.map((entry) => new URL(entry.name, folder)); |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Read and parse a single KDL file. |
| 58 | + */ |
| 59 | +export async function readPatch(fileUrl: URL): Promise<any> { |
| 60 | + const text = await readFile(fileUrl, "utf8"); |
| 61 | + return parseKDL(text); |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Read, parse, and merge all KDL files under the input folder. |
| 66 | + */ |
| 67 | +export default async function readPatches(): Promise<any> { |
| 68 | + const patchDirectory = new URL("../../inputfiles/patches/", import.meta.url); |
| 69 | + const fileUrls = await getAllFileURLs(patchDirectory); |
| 70 | + |
| 71 | + const parsedContents = await Promise.all(fileUrls.map(readPatch)); |
| 72 | + |
| 73 | + return parsedContents.reduce((acc, current) => merge(acc, current), {}); |
| 74 | +} |
0 commit comments