command

This is what we call "a combinator": command takes multiple parsers and combine them into one parser that can also take raw user input using its run function.

Config

  • name (required): A name for the command
  • version: A version for the command
  • handler (required): A function that takes all the arguments and do something with it
  • args (required): An object where the keys are the argument names (how they'll be treated in code) and the values are parsers
  • aliases: A list of other names this command can be called with. Useful with subcommands

Usage

#!/usr/bin/env YARN_SILENT=1 yarn ts-node

import {
	type Type,
	boolean,
	command,
	extendType,
	flag,
	option,
	run,
	string,
} from "../src";

const PrNumber = extendType(string, {
	async from(branchName) {
		const prNumber = branchName === "master" ? "10" : undefined;

		if (!prNumber) {
			throw new Error(`There is no PR associated with branch '${branchName}'`);
		}

		return prNumber;
	},
	defaultValue: () => "Hello",
});

const Repo: Type<string, string> = {
	...string,
	defaultValue: () => {
		throw new Error("Can't infer repo from git");
	},
	description: "repository uri",
	displayName: "uri",
};

const app = command({
	name: "build",
	args: {
		user: option({
			type: string,
			env: "APP_USER",
			long: "user",
			short: "u",
		}),
		password: option({
			type: string,
			env: "APP_PASS",
			long: "password",
			short: "p",
		}),
		repo: option({
			type: Repo,
			long: "repo",
			short: "r",
		}),
		prNumber: option({
			type: PrNumber,
			short: "b",
			long: "pr-number",
			env: "APP_BRANCH",
		}),
		dev: flag({
			type: boolean,
			long: "dev",
			short: "D",
		}),
	},
	handler: ({ repo, user, password, prNumber, dev }) => {
		console.log({ repo, user, password, prNumber, dev });
	},
});

run(app, process.argv.slice(2));