all repos — cmd @ 46c9141b19d060ead1c0be82a1cc815aa92f2987

Unnamed repository; edit this file 'description' to name the repository.

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
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
import type { ArgumentOptions, FlagOptions, Prettify } from "./types";

export class Command<TContext extends Record<string, unknown> = {}> {
	public name?: string;
	public description?: string;
	private flags: Record<string, FlagOptions> = {};
	private args: Record<string, ArgumentOptions<unknown, unknown>> = {};
	private positionals: Array<{
		name: string;
		options: { description?: string; required?: boolean } | undefined;
	}> = [];
	private subcommands: Record<string, Command<Record<string, unknown>>> = {};
	private actionFn?: (ctx: TContext) => void | Promise<void>;

	private shortToFlag: Record<string, string> = {};
	private shortToArg: Record<string, string> = {};

	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 || {};
		if (options?.short) this.shortToFlag[options.short] = name;
		return this as unknown as Command<Prettify<TContext & { [K in TName]: boolean }>>;
	}

	addStringArgument<
		TName extends string,
		TReq extends boolean = false,
		TDef extends string | undefined = undefined,
	>(
		name: TName,
		options?: Omit<ArgumentOptions<"string", TDef>, "type"> & {
			required?: TReq;
			default?: TDef;
		},
	): Command<
		Prettify<
			TContext & {
				[K in TName]: TDef extends string
					? string
					: TReq extends true
						? string
						: string | undefined;
			}
		>
	> {
		this.args[name] = { ...options, type: "string" };
		if (options?.short) this.shortToArg[options.short] = name;
		return this as unknown as Command<
			Prettify<
				TContext & {
					[K in TName]: TDef extends string
						? string
						: TReq extends true
							? string
							: string | undefined;
				}
			>
		>;
	}

	addNumberArgument<
		TName extends string,
		TReq extends boolean = false,
		TDef extends number | undefined = undefined,
	>(
		name: TName,
		options?: Omit<ArgumentOptions<"number", TDef>, "type"> & {
			required?: TReq;
			default?: TDef;
		},
	): Command<
		Prettify<
			TContext & {
				[K in TName]: TDef extends number
					? number
					: TReq extends true
						? number
						: number | undefined;
			}
		>
	> {
		this.args[name] = { ...options, type: "number" };
		if (options?.short) this.shortToArg[options.short] = name;
		return this as unknown as Command<
			Prettify<
				TContext & {
					[K in TName]: TDef extends number
						? number
						: TReq extends true
							? number
							: number | undefined;
				}
			>
		>;
	}

	addChoiceArgument<
		TName extends string,
		const TChoices extends readonly string[],
		TReq extends boolean = false,
		TDef extends TChoices[number] | undefined = undefined,
	>(
		name: TName,
		options: {
			choices: TChoices;
			required?: TReq;
			description?: string;
			short?: string;
			default?: TDef;
		},
	): Command<
		Prettify<
			TContext & {
				[K in TName]: TDef extends TChoices[number]
					? TChoices[number]
					: TReq extends true
						? TChoices[number]
						: TChoices[number] | undefined;
			}
		>
	> {
		this.args[name] = { ...options, type: "choice" };
		if (options?.short) this.shortToArg[options.short] = name;
		return this as unknown as Command<
			Prettify<
				TContext & {
					[K in TName]: TDef extends TChoices[number]
						? TChoices[number]
						: TReq extends true
							? TChoices[number]
							: TChoices[number] | undefined;
				}
			>
		>;
	}

	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 as unknown as Command<
			Prettify<
				TContext & {
					[K in TName]: TReq extends true ? string : string | undefined;
				}
			>
		>;
	}

	addSubcommand<T extends Record<string, unknown>>(command: Command<T>): this {
		if (!command.name) throw new Error("Subcommands must have a name");

		this.subcommands[command.name] = command as unknown as Command<Record<string, unknown>>;
		return this;
	}

	setAction(fn: (ctx: TContext) => void | Promise<void>): this {
		this.actionFn = fn;
		return this;
	}

	async parse(argv: string[]): Promise<void> {
		const ctx: Record<string, unknown> = {};
		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;
		}

		// init args to their defaults
		for (const [key, opts] of Object.entries(this.args)) {
			if (opts.default !== undefined) ctx[key] = opts.default;
		}

		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}`);
					}
				}
			} else if (isShort) {
				const shorts = arg.slice(1).split("");
				for (let j = 0; j < shorts.length; j++) {
					const short = shorts[j] as string;
					const flagName = this.shortToFlag[short];
					const argName = this.shortToArg[short];

					if (flagName) {
						ctx[flagName] = true;
					} else if (argName) {
						const opts = this.args[argName];
						let value: string | undefined;
						if (j === shorts.length - 1) {
							if (i + 1 < argv.length && !(argv[i + 1] as string).startsWith("-")) {
								value = argv[i + 1];
								i++;
							}
						}
						ctx[argName] = this.parseValue(argName, value, opts!);
					} else {
						throw new Error(`Unknown short option: -${short}`);
					}
				}
			} else {
				positionalsProvided.push(arg);
			}

			i++;
		}

		if (positionalsProvided.length > this.positionals.length)
			throw new Error(
				`Unknown positional argument: ${positionalsProvided[this.positionals.length]}`,
			);

		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 as unknown as TContext);
	}

	private parseValue(
		name: string,
		value: string | undefined,
		opts: ArgumentOptions<unknown, unknown>,
	) {
		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 unknown as { choices: string[] }).choices;
			if (!choices.includes(value))
				throw new Error(`Option --${name} must be one of: ${choices.join(", ")}`);
		}
		return value;
	}
}

export * from "./types";