diff --git a/index.ts b/index.ts index 0d505a1..0af83ee 100644 --- a/index.ts +++ b/index.ts @@ -1,4 +1,4 @@ import { generateCode } from "./src/main"; -export { generateCode, generateCodeByAST, generateCodeWithGenerator } from "./src/main"; +export { generateCode, generateCodeByAST, generateCodeWithGenerator, generateCodeFromData } from "./src/main"; export { CodeGenerator } from "./src/generators/generator"; export { TypescriptGenerator } from "./src/generators/typescript/generator"; \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index c7cc107..2973bf4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -9,7 +9,7 @@ import { fillConstructors } from "./astbuilder/fill_constructors"; import { CodeBuilder } from "./generators/CodeBuilder"; import { CodeGenerator, CommonGenDeclaration } from "./generators/generator"; import { TypescriptGenerator } from "./generators/typescript/generator"; -import fs from 'fs' +import fs from 'fs/promises' export function generateCodeByAST(tree: Program, input: string, getGenerator: (tlbCode: TLBCode) => CodeGenerator) { @@ -61,25 +61,33 @@ export function generateCodeByAST(tree: Program, input: string, getGenerator: (t return generatedCode; } -export function generateCodeWithGenerator(inputPath: string, outputPath: string, getGenerator: (tlbCode: TLBCode) => CodeGenerator) { - const input = fs.readFileSync( +function getGenerator(resultLanguage: string) { + return (tlbCode: TLBCode) => { + if (resultLanguage == 'typescript') { + return new TypescriptGenerator(tlbCode) + } else { + throw new Error(`Result language ${resultLanguage} is not supported`) + } + } +} + +export async function generateCodeFromData(input: string, resultLanguage: string): Promise { + const tree = ast(input) + return generateCodeByAST(tree, input, getGenerator(resultLanguage)); +} + +export async function generateCodeWithGenerator(inputPath: string, outputPath: string, getGenerator: (tlbCode: TLBCode) => CodeGenerator) { + const input = await fs.readFile( inputPath, 'utf-8', ) const tree = ast(input) - fs.writeFile(outputPath, generateCodeByAST(tree, input, getGenerator), () => { }); + await fs.writeFile(outputPath, generateCodeByAST(tree, input, getGenerator), {}); console.log(`Generated code is saved to ${outputPath}`); } -export function generateCode(inputPath: string, outputPath: string, resultLanguage: string) { - let getGenerator = (tlbCode: TLBCode) => { - if (resultLanguage == 'typescript') { - return new TypescriptGenerator(tlbCode) - } else { - throw new Error(`Result language ${resultLanguage} is not supported`) - } - } - generateCodeWithGenerator(inputPath, outputPath, getGenerator); +export async function generateCode(inputPath: string, outputPath: string, resultLanguage: string) { + return generateCodeWithGenerator(inputPath, outputPath, getGenerator(resultLanguage)); }