commandzen
Version:
A command-line argument parsing library that allows for quick and easy parsing of command-line arguments.
53 lines (52 loc) • 1.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandParser = void 0;
class CommandParser {
constructor() {
}
static parse(command, argv) {
const initialState = {
command,
options: {},
};
const commandList = argv.reduce((acc, arg, index, arr) => {
if (!arg.startsWith("-")) {
return this.handleSubcommand(arg, acc);
}
else {
return this.handleOption(arg, acc, arr, index);
}
}, [initialState]);
return commandList[commandList.length - 1];
}
static handleSubcommand(arg, commandList) {
const currentCommandResult = commandList[commandList.length - 1];
const subcommand = currentCommandResult.command.findSubcommand(arg);
if (subcommand) {
commandList.push({
command: subcommand,
options: {},
});
}
return commandList;
}
static handleOption(arg, commandList, argv, index) {
const currentCommandResult = commandList[commandList.length - 1];
const option = currentCommandResult.command.findOption(arg);
if (option) {
const nextArg = argv[index + 1];
if (nextArg && !nextArg.startsWith("-")) {
currentCommandResult.options[option.key] = nextArg;
}
else {
if (option.required) {
console.error(`The option "${option.flag}" requires an argument, but it was not provided.`);
process.exit(1);
}
currentCommandResult.options[option.key] = true;
}
}
return commandList;
}
}
exports.CommandParser = CommandParser;