koa-program/extend/generator.ts
Titor 42ba4cffe3 更改文件名
更改CLI文件为Generator文件名,突出当前文件的作用为生成器
2021-03-03 14:29:48 +08:00

72 lines
1.9 KiB
TypeScript

import prompts from "prompts";
import { file as fs } from "./file";
import ejs from "ejs";
import { join, resolve, sep } from "path";
abstract class Generator {
protected answers: {} | null = null;
protected RUN: string; // RUN: 项目初始化目录
private dir: string; // dir: 项目运行目录
protected PATH: string; // PATH: 项目根目录
protected TPL: string; // TPL: 模板目录
protected constructor() {
this.RUN = join(resolve(process.cwd()), sep);
let dir = this.dir = join(resolve(__dirname));
let path = this.PATH = this.dir.substring(0, dir.lastIndexOf("extend"));
this.TPL = join(path, "template/");
this.run().catch(err => console.log(err));
}
/*
* 自动指令中枢:
* @description 自动调用 CLI 过程中的5大阶段
*/
private async run() {
await this.Initialize();
await this.Prompting();
await this.Writing();
await this.Installing();
await this.Ending();
}
// ----------------------------------------------------------------------
// 5 大阶段
protected Initialize() {}
protected Prompting() {}
protected Writing() {}
protected Installing() {}
protected Ending() {}
// 5 大阶段
// ----------------------------------------------------------------------
protected easyCopy(file: string) {
// @ts-ignore
return fs.copy(join(this.TPL, file), join(this.RUN, this.answers.appName, file));
}
protected async easyTpl(file: string) {
// @ts-ignore
const [compileContent] = await Promise.all([ejs.renderFile(join(this.TPL, file), this.answers)]);
// @ts-ignore
return fs.write(join(this.RUN, this.answers.appName, file), compileContent);
}
// 提问题,并传回问题答案
protected async prompt(question: prompts.PromptObject<string> | prompts.PromptObject<string>[]) {
return this.answers = await prompts(question);
}
}
export { Generator };