jmms
Version:
Jmms cli tools, Jmms is a java meta-micro-service framework
100 lines (88 loc) • 3.44 kB
JavaScript
const _ = require('lodash');
const log = require('../../log');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const shelljs = require('shelljs');
const mkdirp = require('mkdirp');
const swagger = require('swagger-parser');
var BaseGenerator = require('../../base');
module.exports = class extends BaseGenerator {
constructor(args, opts) {
super(args, opts, false);
}
initializing() {
this.inFile = this.options['file'];
if(!this.inFile) {
this.inFile = this.destinationPath("swagger.json");
if(!fs.existsSync(this.inFile)) {
log.error("The swagger spec file must specified!!!");
process.exit(0);
}
}
this.outDir = this.options['out'];
if(!this.outDir) {
if(fs.existsSync(this.destinationPath("book.json"))) {
this.outDir = this.destinationRoot();
}else {
this.outDir = this.destinationPath("./api-doc/");
}
}else {
this.outDir = path.resolve(this.outDir);
}
this.outSwagger = path.join(this.outDir, "swagger.json");
const docGenerated = fs.existsSync(path.join(this.outDir, "book.json"));
const force = this.options['force'] == true;
if(docGenerated) {
if(!force) {
log.error("Doc already generated at '" + this.outDir + "', please use --force option if you wan't to update");
process.exit(0);
}
}else {
if(!force && fs.existsSync(this.outDir)) {
log.error("The output dir '" + this.outDir + "' already exists, please use --force option if you wan't to generate");
process.exit(0);
}
}
}
writing() {
log.info("Reading '" + this.inFile + "'...\n");
const outDir = this.outDir;
//create doc dir if not exists
if(!fs.existsSync(outDir)) {
fs.mkdirSync(outDir);
}
//create pom.xml if not exists.
const pom = path.join(outDir, "pom.xml");
if(!fs.existsSync(pom)) {
const vars = {};
_.merge(vars, require("../../vars"))
vars.name = "api-doc";
vars.groupId = 'swagger';
vars.artifactId = vars.name;
vars.version = '1.0.0-SNAPSHOT';
this.fs.copyTpl(this.templatePath('pom.xml'), pom, vars);
}
swagger.parse(this.inFile, (err, api) => {
if(err) {
log.error("Swagger spec err : " + err);
fs.unlinkSync(pom);
process.exit(0);
}
//write swagger.json
fs.writeFileSync(this.outSwagger, JSON.stringify(api, 4));
process.chdir(outDir);
this._runJavaCli((cli) => {
cli.exec('swagger.docGen', {dir: outDir}, (err) => {
if(err) {
log.error("Error generating doc, " + err);
}else {
log.info(`\n${chalk.green.bold("Doc generated at '" + outDir + "' successfully!")}\n`);
}
fs.unlinkSync(pom);
process.exit(0);
});
});
});
}
};