Wrapper function to allow creating a command in one shot #400
Replies: 3 comments 2 replies
-
It grows! import type {
ArgumentOptions,
Command,
HandlerFn,
OptionOptions
} from "bandersnatch";
import { command as _origCommand } from "bandersnatch";
type OptionMap = Record<string, OptionOptions>;
type OptionFn<T extends OptionMap> = (optionMap: T) => T;
type ArgMap = Record<string, ArgumentOptions>;
type ArgFn<T extends ArgMap> = (optionMap: T) => T;
interface BuildCommandArgs<T> {
command: string;
description: string;
hidden?: boolean;
subCommands?: Command[];
action?: HandlerFn<T>;
args?: ArgMap | ArgFn<ArgMap>;
opts?: OptionMap | OptionFn<OptionMap>;
}
/**
* @todo get the given `T` to match up options to params
*/
export function buildCommand<T>({
command,
description,
action,
args,
opts,
subCommands,
hidden = false
}: BuildCommandArgs<T>): Command {
const cmd = _origCommand<T>(command, { description, hidden });
if (opts) {
const actualOpts: OptionMap = typeof opts === "function" ? opts({}) : opts;
Object.entries(actualOpts).forEach(([optName, config]) => {
cmd.option(optName, config);
});
}
if (args) {
const actualArgs: ArgMap = typeof args === "function" ? args({}) : args;
Object.entries(actualArgs).forEach(([argName, config]) => {
cmd.argument(argName, config);
});
}
if (action) {
cmd.action(action);
}
if (subCommands) {
for (const subCommand of subCommands) {
cmd.add(subCommand);
}
}
return cmd;
} |
Beta Was this translation helpful? Give feedback.
-
This looks very good. One of the influences for this library is vorpal, which uses the fluent interface. I'm hesitant to add your suggestion to the library, as I don't want to offer multiple ways of doing the same thing. This adds complexity and makes (imo) e.g. yargs harder to use than it could be. I do have some doubts about the fluent interface myself, maybe I will look into changing the API for a next major release. |
Beta Was this translation helpful? Give feedback.
-
Love the library, it is making my life easy, so thank you 🙂 |
Beta Was this translation helpful? Give feedback.
-
I do like the fluent interface, but I was having issues with prettier formatting my method chains oddly...
This is what I have done to remedy this issue, plus, I am tossing around ideas of a file based command autoloader with the commands being modules..........
Anyways... what do you think about something like this?
Beta Was this translation helpful? Give feedback.
All reactions