|
| 1 | +import { readFile } from "fs/promises"; |
| 2 | +import { Options as YargsOptions } from "yargs"; |
| 3 | + |
| 4 | +import checkDSL from "../validator"; |
| 5 | +import transformSyntax from "../transformer"; |
| 6 | +import { assertNever } from "assert-never"; |
| 7 | + |
| 8 | +type fromOption = "dsl" | "json"; |
| 9 | + |
| 10 | +interface CommandArgs { |
| 11 | + from: fromOption; |
| 12 | + inputFile: string; |
| 13 | +} |
| 14 | + |
| 15 | +exports.command = "transform"; |
| 16 | +exports.desc = "Transform "; |
| 17 | +exports.builder = { |
| 18 | + from: { |
| 19 | + describe: "whether we want to transform from dsl or json", |
| 20 | + choices: ["dsl", "json"], |
| 21 | + required: true, |
| 22 | + }, |
| 23 | + inputFile: { |
| 24 | + describe: "Configuration file. It must be in DSL syntax.", |
| 25 | + type: "string", |
| 26 | + required: true, |
| 27 | + }, |
| 28 | +} as Record<keyof CommandArgs, YargsOptions>; |
| 29 | + |
| 30 | +async function loadFile(inputFile: string) { |
| 31 | + return readFile(inputFile, "utf-8"); |
| 32 | +} |
| 33 | + |
| 34 | +exports.handler = async (argv: CommandArgs) => { |
| 35 | + try { |
| 36 | + const fileContents = await loadFile(argv.inputFile); |
| 37 | + switch (argv.from) { |
| 38 | + case "dsl": { |
| 39 | + const validateResult = checkDSL.checkDSL(fileContents); |
| 40 | + if (validateResult.length) { |
| 41 | + throw new Error(`Invalid DSL with error ${JSON.stringify(validateResult)}`); |
| 42 | + } |
| 43 | + const transformedResult = transformSyntax.friendlySyntaxToApiSyntax(fileContents); |
| 44 | + console.log(JSON.stringify(transformedResult, null, 4)); |
| 45 | + break; |
| 46 | + } |
| 47 | + case "json": { |
| 48 | + const transformedResult = transformSyntax.apiSyntaxToFriendlySyntax(JSON.parse(fileContents)); |
| 49 | + console.log(transformedResult); |
| 50 | + break; |
| 51 | + } |
| 52 | + default: |
| 53 | + assertNever(argv.from); |
| 54 | + } |
| 55 | + } catch (err) { |
| 56 | + console.error(err as Error); |
| 57 | + process.exitCode = 1; |
| 58 | + } |
| 59 | +}; |
0 commit comments