nope/lib/helpers/generateTemplate.ts

104 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-08-24 21:16:09 +00:00
import { copyFile, readFile } from "fs/promises";
import * as handlebars from 'handlebars';
import { join } from 'path';
2020-08-24 21:16:09 +00:00
import { Project } from "ts-morph";
import { Logger } from 'winston';
2020-08-24 21:16:09 +00:00
import { analyzeFiles } from "./analyzeTypescriptFiles";
import { createFile, createPath } from "./fileHelpers";
/**
* Generate the Client Templates.
* @param options
*/
export async function generateClientTemplate(options: {
pathToTemplate: string,
outputDir: string,
inputDir: string,
tsConfigFilePath: string,
// A Logger.
logger?: Logger
}) {
// Create the Output dir (if it doenst exists)
await createPath(options.outputDir);
if (options.logger) {
options.logger.info('Templates will be stored in ' + options.outputDir);
}
// Firstly copy the nopeDispatcher
await copyFile(
2020-08-24 21:16:09 +00:00
join(__dirname, '..', '..', '..', 'lib', 'dispatcher', 'nopeDispatcher.ts'),
join(options.outputDir, 'nopeDispatcher.ts')
);
// Function to Determine new project files.
const project = new Project({
tsConfigFilePath: options.tsConfigFilePath,
addFilesFromTsConfig: false,
});
project.addSourceFilesAtPaths(options.inputDir);
// Readin the Source-Files.
const sourceFiles = project.getSourceFiles();
// Generate the Files
const result = analyzeFiles(sourceFiles);
// load the File.
const template = await readFile(options.pathToTemplate, {
encoding: 'utf-8'
})
// Renderfuncting
const render = handlebars.compile(template);
// Generate the Files.
const files: {
name: string,
content: string,
}[] = result.map(item => {
item.className = item.className + 'ClientInterface'
return {
name: item.className + '.ts',
content: render(item)
}
});
2020-08-24 21:16:09 +00:00
for (const file of files) {
// Define the File Name:
2020-08-24 21:16:09 +00:00
const fileName = join(options.outputDir, 'clients', file.name);
await createFile(
// Generate the Path.
2020-08-24 21:16:09 +00:00
join(options.outputDir, 'clients', file.name),
file.content
2020-08-24 21:16:09 +00:00
);
if (options.logger) {
options.logger.info('Generated -> ' + fileName);
}
2020-08-24 21:16:09 +00:00
// Function to Determine new project files.
const project = new Project({
tsConfigFilePath: options.tsConfigFilePath,
addFilesFromTsConfig: false,
});
project.addSourceFileAtPath(fileName);
// Readin the Source-Files.
const sourceFiles = project.getSourceFiles();
for (const file of sourceFiles) {
file.formatText();
await file.save();
}
}
// Compile the Template and parse the Code.
2020-08-24 21:16:09 +00:00
return true;
}