@anycli/command
Version:
anycli base command
101 lines (100 loc) • 3.32 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pjson = require('../package.json');
const Config = require("@anycli/config");
const Parser = require("@anycli/parser");
const cli_ux_1 = require("cli-ux");
const _ = require("lodash");
const flags = require("./flags");
const g = global;
g.anycli = g.anycli || {};
class Command {
constructor(argv, options) {
this.argv = argv;
this.config = Config.load(options || module.parent && module.parent.parent && module.parent.parent.filename || __dirname);
this.debug = require('debug')(this.ctor.id ? `${this.config.bin}:${this.ctor.id}` : this.config.bin);
this.debug('init version: %s argv: %o', this.ctor._base, argv);
cli_ux_1.default.config.context.command = _.compact([this.ctor.id, ...argv]).join(' ');
cli_ux_1.default.config.context.version = this.config.userAgent;
if (this.config.debug)
cli_ux_1.default.config.debug = true;
cli_ux_1.default.config.errlog = this.config.errlog;
g['http-call'] = g['http-call'] || {};
g['http-call'].userAgent = this.config.userAgent;
}
get ctor() {
return this.constructor;
}
get http() { return require('http-call').HTTP; }
async init() {
if (!this.ctor.parse)
return;
const o = Parser.parse(this.argv, Object.assign({ flags: this.ctor.flags, args: this.ctor.args, strict: this.ctor.strict || !this.ctor.variableArgs, context: this }, (this.ctor.parserOptions || {})));
this.flags = o.flags;
this.args = o.args;
this.argv = o.argv;
}
async catch(err) {
cli_ux_1.default.error(err);
}
async finally(_) {
try {
await cli_ux_1.default.done();
}
catch (err) {
cli_ux_1.default.warn(err);
}
}
}
Command._base = `${pjson.name}@${pjson.version}`;
Command.aliases = [];
Command.strict = true;
Command.parse = true;
Command.flags = {
version: flags.version(),
help: flags.help(),
};
Command.args = [];
Command.parserOptions = {};
/**
* instantiate and run the command
*/
Command.run = async function (argv = process.argv.slice(2), opts) {
let err;
let cmd;
try {
cmd = new this(argv, opts);
await cmd.init();
await cmd.run();
}
catch (e) {
err = e;
if (cmd)
await cmd.catch(e);
else
cli_ux_1.default.error(e);
}
finally {
if (cmd)
await cmd.finally(err);
}
// g.anycli.command = {}
// let cmd!: Command
// try {
// cmd = new this(argv, {...opts, config})
// if (g.anycli.command.showVersion) throw new VersionErr()
// if (g.anycli.command.showHelp) throw new HelpErr()
// return await cmd.run()
// } catch (err) {
// if (err instanceof VersionErr) {
// cli.info(config.userAgent)
// } else if (err instanceof HelpErr || err.message.match(/Unexpected argument: -h/)) {
// const Helper: typeof Help = require('@anycli/plugin-help').default
// const help = new Helper(config)
// help.showHelp(this, argv)
// } else cli.error(err)
// } finally {
// if (cmd) await cmd.finally()
// }
};
exports.default = Command;