hoppa-cli
Version:
Powerful task for developers
72 lines (60 loc) • 2.41 kB
JavaScript
const argv = process.argv;
const cli = {
command: argv[2] ? (argv[2].startsWith('-') ? '' : argv[2]) : '',
args: argv.filter((v, i) => i > 2 && !v.startsWith('-')),
options: argv.filter((v, i) => i > 1 && v.startsWith('-'))
};
const entries = [];
function Command(name, description) {
this.name = name;
this.options = {};
entries.push({ name, description, options: [] });
}
Command.prototype.option = function (name, description) {
var names = name.split(',').map(x => x.trim());
entries.forEach((task, index) => {
if (task.name == this.name) {
entries[index].options.push({ name, description });
}
});
var ok = cli.options.some(v => names.indexOf(v) >= 0);
names.forEach(name => this.options[name.replace('--', '').replace('-', '')] = ok);
return this;
}
/**
* @param action {((args: string[], options: any) => void)}
*/
Command.prototype.action = function (action) {
if (cli.command == this.name && !command.RAN) {
action.call(this, cli.args, this.options);
command.RAN = true;
}
}
const command = (name, description) => new Command(name, description);
command.log = (...args) => console.log(args.join(' '));
command.chalk = require('chalk').default;
command.command = (...args) => new command(...args);
command.rl = require('readline-sync');
command.help = (app) => command('help', 'Show this help')
.action(() => {
var commandLen = entries.reduce((p, curr) => Math.max(curr.name.length, p), 0);
var optionLen = entries.reduce((p, curr) => Math.max(
p,
curr.options.reduce((p, curr) => Math.max(
p,
curr.name.length
), 0)
), 0);
entries.forEach(entry => {
var { name, description, options } = entry;
name = name + ' '.repeat(commandLen - name.length);
command.log(command.chalk.blue(app), command.chalk.green(name), '-', description);
options.forEach(option => {
var { name, description } = option;
name = name + ' '.repeat(optionLen - name.length);
command.log(command.chalk.gray(` ${name} ${description}`));
});
if (options.length) command.log();
});
});
module.exports = command;