diff --git a/apps/generator/cli.js b/apps/generator/cli.js new file mode 100644 index 000000000..0fd464b10 --- /dev/null +++ b/apps/generator/cli.js @@ -0,0 +1,198 @@ +#!/usr/bin/env node + +const path = require('path'); +const os = require('os'); +const program = require('commander'); +const xfs = require('fs.extra'); +const { DiagnosticSeverity } = require('@asyncapi/parser/cjs'); +const packageInfo = require('./package.json'); +const Generator = require('./lib/generator'); +const Watcher = require('./lib/watcher'); +const { isLocalTemplate, isFilePath } = require('./lib/utils'); + +const red = text => `\x1b[31m${text}\x1b[0m`; +const magenta = text => `\x1b[35m${text}\x1b[0m`; +const yellow = text => `\x1b[33m${text}\x1b[0m`; +const green = text => `\x1b[32m${text}\x1b[0m`; + +let asyncapiDocPath; +let template; +const params = {}; +const noOverwriteGlobs = []; +const disabledHooks = {}; +const mapBaseUrlToFolder = {}; + +const parseOutput = dir => path.resolve(dir); + +const paramParser = v => { + if (!v.includes('=')) throw new Error(`Invalid param ${v}. It must be in the format of --param name=value.`); + const [paramName, paramValue] = v.split(/=(.+)/, 2); + params[paramName] = paramValue; + return v; +}; + +const noOverwriteParser = v => noOverwriteGlobs.push(v); + +const disableHooksParser = v => { + const [hookType, hookNames] = v.split(/=/); + if (!hookType) throw new Error('Invalid --disable-hook flag. It must be in the format of: --disable-hook or --disable-hook =,,...'); + if (hookNames) { + disabledHooks[hookType] = hookNames.split(/,/); + } else { + disabledHooks[hookType] = true; + } +}; + +const mapBaseUrlParser = v => { + // Example value for regular expression: https://schema.example.com/crm/:./test/docs/ + // it splits on last occurrence of : into the groups all, url and folder + const re = /(.*):(.*)/g; + let mapping = []; + if ((mapping = re.exec(v))===null || mapping.length!==3) { + throw new Error('Invalid --map-base-url flag. A mapping : with delimiter : expected.'); + } + + // Folder is without trailing slash, so make sure that url has also no trailing slash: + mapBaseUrlToFolder.url = mapping[1].replace(/\/$/, ''); + mapBaseUrlToFolder.folder = path.resolve(mapping[2]); + + const isURL = /^https?:/; + if (!isURL.test(mapBaseUrlToFolder.url.toLowerCase())) { + throw new Error('Invalid --map-base-url flag. The mapping : requires a valid http/https url and valid folder with delimiter `:`.'); + } +}; + +const showError = err => { + console.error(red('Something went wrong:')); + console.error(red(err.stack || err.message)); + if (err.diagnostics) { + const errorDiagnostics = err.diagnostics.filter(diagnostic => diagnostic.severity === DiagnosticSeverity.Error); + console.error(red(`Errors:\n${JSON.stringify(errorDiagnostics, undefined, 2)}`)); + } +}; +const showErrorAndExit = err => { + showError(err); + process.exit(1); +}; + +program + .version(packageInfo.version) + .arguments('