@acot/cli
Version:
More accessible web, all over the world.
106 lines (105 loc) • 3.36 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CLI = void 0;
const stream_1 = require("stream");
const yargs_1 = __importDefault(require("yargs/yargs"));
const logger_1 = require("@acot/logger");
const global_options_1 = require("./global-options");
const command_1 = require("./command");
const debug = require('debug')('acot:cli');
process.on('uncaughtException', (e) => {
new logger_1.Logger().error('Uncaught exception:', e);
process.exit(1);
});
process.on('unhandledRejection', (e) => {
new logger_1.Logger().error('Unhandled rejection:', e);
process.exit(1);
});
class CLI {
constructor(pkg, logger, container) {
this._pkg = pkg;
this._logger = logger;
this._container = container;
}
async run(argv) {
const logger = this._logger;
const parser = (0, yargs_1.default)()
.help(false)
.version(false)
.detectLocale(false)
.parserConfiguration({
'set-placeholder-key': true,
'boolean-negation': false,
})
.fail((msg, err) => {
throw err != null ? err : new Error(msg);
})
.options(global_options_1.globalOptions)
.exitProcess(false);
let parsed = parser.parse(argv);
if (parsed.debug != null) {
const debug = require('debug');
debug.enable(`acot:${parsed.debug || '*'}`);
}
if (parsed.quiet) {
const stream = new stream_1.PassThrough();
logger.update({ stdout: stream, stderr: stream });
}
else if (parsed.verbose) {
logger.update({ level: 'verbose' });
}
parser.strict();
this._container.all().forEach((module) => {
(0, command_1.buildCommand)(parser, module);
});
try {
debug('receive argv: %O', argv);
parsed = parser.parse(argv);
debug('parsed argv: %O', parsed);
}
catch (e) {
logger.error(e);
debug('Parse error:', e);
return 1;
}
const context = {
cwd: process.cwd(),
pkg: this._pkg,
container: this._container,
logger,
};
try {
const { _, $0, ...args } = parsed;
if (parsed.version) {
return await this._container.mustGet('version').run({
...context,
args,
});
}
if (parsed.help) {
return await this._container.mustGet('help').run({
...context,
args: {
...args,
command: _,
},
});
}
const command = _.join('.') || 'help';
debug(`command "${command}"`);
debug('running command...');
return await this._container.mustGet(command).run({
...context,
args,
});
}
catch (e) {
logger.error(e);
return 1;
}
}
}
exports.CLI = CLI;