commandzen
Version:
A command-line argument parsing library that allows for quick and easy parsing of command-line arguments.
77 lines (76 loc) • 2.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Command = void 0;
const events_1 = require("events");
const padding_1 = require("../utils/padding");
const option_1 = require("../option");
class Command extends events_1.EventEmitter {
name;
description;
aliases;
options;
subcommands;
constructor(name, description, aliases = [], options = [], subcommands = new Map()) {
super();
this.name = name;
this.description = description;
this.aliases = aliases;
this.options = options;
this.subcommands = subcommands;
}
static create(props) {
return new Command(props.name, props.description, props.aliases, props.options, props.subcommands);
}
addSubcommand(command) {
this.subcommands.set(command.name, command);
command.aliases.forEach((alias) => this.subcommands.set(alias, command));
return this;
}
addOption(...option) {
this.options.push(...option.map((o) => option_1.Option.create(o)));
return this;
}
addAlias(...aliases) {
this.aliases.push(...aliases);
return this;
}
findOption(flag) {
return this.options.find((o) => o.shortName === flag || o.longName === flag);
}
findSubcommand(name) {
return this.subcommands.get(name);
}
help(indentationLevel = 0, fullName = this.name, subcommandIndex = "") {
const indent = " ";
const prefix = indent.repeat(indentationLevel);
console.info(`${prefix}Usage: ${fullName} [options]`);
console.info(`\n${prefix}${this.description}`);
if (this.options.length > 0) {
const maxLength = this.options.reduce((max, option) => Math.max(max, option.flag.length), 0);
console.info(`\n${prefix}Options:`);
for (const option of this.options) {
const paddedFlag = (0, padding_1.paddingRight)(option.flag, maxLength);
console.info(`${prefix}${indent}${paddedFlag} ${option.description}`);
}
console.info();
}
if (this.subcommands.size > 0) {
console.info(`\n${prefix}Subcommands:`);
let index = 1;
for (const subcommand of this.subcommands.values()) {
const newIndex = `${subcommandIndex ? subcommandIndex + "." : ""}${index}`;
console.info(`${prefix}${indent}${newIndex}. ${subcommand.name}`);
subcommand.help(indentationLevel + 1, `${fullName} ${subcommand.name}`, newIndex);
index++;
}
}
if (indentationLevel === 0) {
console.info(`Run ${fullName} [command] --help for more information on a command.`);
}
}
registerAction(callback) {
this.on(this.name, callback);
return this;
}
}
exports.Command = Command;