UNPKG

commandzen

Version:

A command-line argument parsing library that allows for quick and easy parsing of command-line arguments.

73 lines (72 loc) 2.75 kB
import { EventEmitter } from "events"; import { paddingRight } from "../utils/padding"; import { Option } from "../option"; export class Command extends 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.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 = 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; } }