src/index.ts (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
import type { ArgumentOptions, FlagOptions, Prettify } from "./types";
export class Command<TContext extends Record<string, any> = {}> {
public name?: string;
public description?: string;
private flags: Record<string, FlagOptions> = {};
private args: Record<string, ArgumentOptions<any>> = {};
private positionals: Array<{ name: string; options: any }> = [];
private subcommands: Record<string, Command<any>> = {};
private actionFn?: (ctx: TContext) => void | Promise<void>;
constructor(name?: string) {
this.name = name;
}
setName(name: string): this {
this.name = name;
return this;
}
setDescription(desc: string): this {
this.description = desc;
return this;
}
addFlag<TName extends string>(
name: TName,
options?: FlagOptions,
): Command<Prettify<TContext & { [K in TName]: boolean }>> {
this.flags[name] = options || {};
return this;
}
addStringArgument<TName extends string, TReq extends boolean = false>(
name: TName,
options?: Omit<ArgumentOptions<"string">, "type"> & { required?: TReq },
): Command<
Prettify<
TContext & {
[K in TName]: TReq extends true ? string : string | undefined;
}
>
> {
this.args[name] = { ...options, type: "string" };
return this;
}
addNumberArgument<TName extends string, TReq extends boolean = false>(
name: TName,
options?: Omit<ArgumentOptions<"number">, "type"> & { required?: TReq },
): Command<
Prettify<
TContext & {
[K in TName]: TReq extends true ? number : number | undefined;
}
>
> {
this.args[name] = { ...options, type: "number" };
return this;
}
addChoiceArgument<
TName extends string,
const TChoices extends readonly string[],
TReq extends boolean = false,
>(
name: TName,
options: {
choices: TChoices;
required?: TReq;
description?: string;
short?: string;
},
): Command<
Prettify<
TContext & {
[K in TName]: TReq extends true
? TChoices[number]
: TChoices[number] | undefined;
}
>
> {
this.args[name] = { ...options, type: "choice" };
return this;
}
addPositional<TName extends string, TReq extends boolean = false>(
name: TName,
options?: { description?: string; required?: TReq },
): Command<
Prettify<
TContext & {
[K in TName]: TReq extends true ? string : string | undefined;
}
>
> {
this.positionals = this.positionals || [];
this.positionals.push({ name, options });
return this;
}
addSubcommand(command: Command<any>): this {
if (!command.name) throw new Error("Subcommands must have a name");
this.subcommands[command.name] = command;
return this;
}
setAction(fn: (ctx: TContext) => void | Promise<void>): this {
this.actionFn = fn;
return this;
}
async parse(argv: string[]): Promise<void> {
const ctx: any = {};
const positionalsProvided: string[] = [];
// init boolean flags to their defaults, or false.
for (const [key, opts] of Object.entries(this.flags)) {
ctx[key] = opts.default ?? false;
}
let i = 0;
while (i < argv.length) {
const arg = argv[i] as string;
// check for subcommands before evaluating positionals/flags
if (!arg.startsWith("-") && this.subcommands[arg]) {
return this.subcommands[arg]?.parse(argv.slice(i + 1));
}
const isLong = arg.startsWith("--");
const isShort = arg.startsWith("-") && !isLong;
if (isLong) {
let name = arg.slice(2);
let value: string | undefined;
if (name.includes("=")) {
const splitIdx = name.indexOf("=");
value = name.slice(splitIdx + 1);
name = name.slice(0, splitIdx);
}
if (this.flags[name]) {
ctx[name] = true;
} else {
const argOpts = this.args[name];
if (argOpts) {
if (
value === undefined &&
i + 1 < argv.length &&
!(argv[i + 1] as string).startsWith("-")
) {
value = argv[i + 1];
i++;
}
ctx[name] = this.parseValue(name, value, argOpts);
} else {
throw new Error(`Unknown option: --${name}`);
}
}
}
if (isShort) {
const short = arg.slice(1);
const flagEntry = Object.entries(this.flags).find(
([_, o]) => o.short === short,
);
const argEntry = Object.entries(this.args).find(
([_, o]) => o.short === short,
);
if (flagEntry) {
ctx[flagEntry[0]] = true;
} else if (argEntry) {
const [name, opts] = argEntry;
let value: string | undefined;
if (i + 1 < argv.length && !(argv[i + 1] as string).startsWith("-")) {
value = argv[i + 1];
i++;
}
ctx[name] = this.parseValue(name, value, opts);
} else {
throw new Error(`Unknown short option: -${short}`);
}
}
if (!isLong && !isShort) positionalsProvided.push(arg);
i++;
}
for (let p = 0; p < this.positionals.length; p++) {
const pos = this.positionals[p]!;
const val = positionalsProvided[p];
if (val !== undefined) ctx[pos.name] = val;
else if (pos.options?.required)
throw new Error(`Missing required positional argument: <${pos.name}>`);
}
for (const [name, opts] of Object.entries(this.args)) {
if (opts.required && ctx[name] === undefined)
throw new Error(`Missing required argument: --${name}`);
}
if (this.actionFn) await this.actionFn(ctx);
}
private parseValue(
name: string,
value: string | undefined,
opts: ArgumentOptions<any>,
) {
if (value === undefined)
throw new Error(`Option --${name} requires a value`);
if (opts.type === "number") {
const num = Number(value);
if (isNaN(num))
throw new Error(`Option --${name} must be a valid number`);
return num;
}
if (opts.type === "choice") {
const choices = (opts as any).choices;
if (!choices.includes(value))
throw new Error(
`Option --${name} must be one of: ${choices.join(", ")}`,
);
}
return value;
}
}
|