GitHub

CLI

Commands with typed flags, arguments and subcommands, with help, errors and prompts built in.

A command's parameters are a Config class whose attributes are Flags and Arguments. The handler receives an instance with each attribute parsed to its type, so config.priority is an int and pyright knows it. command.make(name, Config, handler) builds a command, and command.run(app, version=...) parses the process's arguments and runs the handler that matches them, with --help, --version, --completions, --log-level and --wizard built in.

Flags and subcommands

Flag.string, integer, finite (a float; nan and inf are refused), boolean, literals, file, date, ... make flags, and methods refine them: with_alias, with_default, optional, with_description, with_fallback_config (read a config value when the flag is missing). Argument does the same for positional arguments. Pass literals its choices as a tuple, Flag.literals("format", ("text", "json")), to get a Flag[Literal["text", "json"]]: pyright widens a list's strings to str, and Python has no counterpart of the const type parameter that keeps Effect's array literal.

with_subcommands turns a command into a group. Flags every subcommand accepts go in the parent's config with with_shared_flags, and a handler reads them by yielding the parent command.

Add configList configtodo: shared --verboseadd: title, --prioritylist: --done, --formatadd handlerlist_items handler
Add configList configtodo: shared --verboseadd: title, --prioritylist: --done, --formatadd handlerlist_items handler
todo.py
import json

import pyfect as fx
from pyfect import console, platform
from pyfect.cli import Argument, Config, Flag, command


class Shared(Config):
    verbose = Flag.boolean("verbose").with_default(False).with_description("Explain each step")


class Add(Config):
    title = Argument.string("title").with_description("What to do")
    priority = (
        Flag.integer("priority").with_alias("p").with_default(1).with_description("1 (low) to 3")
    )


class List(Config):
    done = Flag.boolean("done").with_default(False).with_description("Include finished items")
    format = Flag.literals("format", ("text", "json")).with_default("text")


# The root command only holds the flags every subcommand shares.
todo = command.make("todo").with_shared_flags(Shared).with_description("Keep track of things")


@fx.fn
def add(config: Add):
    shared = yield from todo  # the parsed shared flags
    if shared.verbose:
        yield from console.log(f"priority {config.priority}")
    yield from console.log(f"added: {config.title}")


@fx.fn
def list_items(config: List):
    items = ["write docs", "ship it"] + (["plan release"] if config.done else [])
    text = json.dumps(items) if config.format == "json" else ", ".join(items)
    yield from console.log(text)


app = todo.with_subcommands(
    command.make("add", Add, add).with_description("Add an item"),
    command.make("list", List, list_items).with_description("List items"),
)

# `command.run(app, version=...)` reads sys.argv; `run_with` takes the arguments.
cli = command.run_with(app, version="1.0.0")
for args in (
    ["add", "write docs", "-p", "2", "--verbose"],
    ["list", "--done"],
    ["list", "--format", "json"],
):
    fx.run_main(cli(args).pipe(fx.provide(platform.layer)))

A program calls fx.run_main(command.run(app, version="1.0.0").pipe(fx.provide(platform.layer))); platform.layer gives the CLI the files, terminal and standard streams it reads.

Help output

Help is generated from the config: each flag's type, alias, choices and description, the command's description and examples. --help prints it for any command or subcommand, and a command line that doesn't parse prints the error and a suggestion (Did you mean this? --force) to standard error, then exits with status 1.

A subcommand's help lists its own flags under FLAGS and the shared flags of its ancestors under INHERITED FLAGS. In a deep tree, cli_output.default_formatter(inherited_flags= "summary", global_flags="summary") replaces both lists with a pointer such as Run 'app --help' for inherited flags, and "none" leaves them out; the command that declares global flags always lists them.

deploy_help.py
import pyfect as fx
from pyfect import console, platform
from pyfect.cli import Argument, Config, Flag, command
from pyfect.cli.help_doc import ExampleDoc


class Deploy(Config):
    service = Argument.string("service").with_description("The service to deploy")
    env = Flag.literals("env", ("staging", "prod")).with_default("staging")
    replicas = Flag.integer("replicas").with_alias("r").with_default(2).with_description("How many")
    force = Flag.boolean("force").with_default(False).with_description("Skip the checks")


deploy = (
    command.make("deploy", Deploy, lambda c: console.log(f"deploying {c.service} to {c.env}"))
    .with_description("Deploy a service")
    .with_examples([ExampleDoc("deploy api --env prod -r 3", "Three replicas in production")])
)

cli = command.run_with(deploy, version="1.0.0")
# `--help` prints the help and succeeds, as in Effect; a command line that doesn't parse
# fails with ShowHelp.
fx.run_main(cli(["--help"]).pipe(fx.provide(platform.layer)))

Prompts

prompt.string, integer, confirm, select, multi_select, date, file, password and the others ask the user in the terminal; a prompt is an effect, so a handler yields it. with_fallback_prompt(prompt) asks for a flag only when it was left out and the terminal can prompt; in a script or a pipe, the flag is required instead.

Prompts read key presses from the Terminal service, so a test provides a terminal whose user types a fixed string. terminal.decode turns the string, escape sequences included, into key presses.

test_init.py
import pyfect as fx
from pyfect import console, layer, platform, testing
from pyfect.cli import Config, Flag, ShowHelp, command, prompt
from pyfect.cli.terminal_capabilities import Capabilities, TerminalCapabilities
from pyfect.errors import Done
from pyfect.queue import Queue
from pyfect.terminal import Size, Terminal, TerminalService, UserInput, decode


class Init(Config):
    # Asked for when the flag is missing and the terminal can prompt.
    name = Flag.string("name").with_fallback_prompt(prompt.string("Project name"))


@fx.fn
def init(config: Init):
    template = yield from prompt.select(
        [prompt.Choice("Library", "lib"), prompt.Choice("Application", "app")],
        message="Template",
    )
    if (yield from prompt.confirm("Create it?", initial=True)):
        yield from console.log(f"created {config.name} from the {template} template")


cli = command.run_with(command.make("init", Init, init), version="1.0.0")


def user_types(keys: str):
    """A terminal whose user types `keys` (escape sequences for arrows)."""

    @fx.fn
    def make():
        queue = yield from Queue[UserInput, Done].unbounded()
        yield from queue.offer_all(decode(keys))
        sizes = yield from Queue[Size, Done].unbounded()
        yield from sizes.offer(Size(80, 24))
        return TerminalService(
            columns=fx.succeed(80),
            rows=fx.succeed(24),
            size=fx.succeed(sizes),
            read_input=fx.succeed(queue),
            read_line=fx.succeed(""),
            display=lambda _text: fx.void,
        )

    prompts = Capabilities(can_color=False, can_animate=False, can_prompt=True)
    return layer.merge(layer.effect(Terminal, make()), layer.succeed(TerminalCapabilities, prompts))


def run(args: list[str], keys: str = ""):
    return cli(args).pipe(fx.provide(user_types(keys))).pipe(fx.provide(platform.layer))


DOWN = "\x1b[B"


@testing.effect
def test_prompts_for_what_the_flags_left_out():
    yield from run([], keys=f"demo\r{DOWN}\r\r")
    assert (yield from testing.log_lines) == ["created demo from the app template"]


@testing.effect
def test_a_flag_skips_its_prompt():
    yield from run(["--name", "demo"], keys="\rn")
    assert (yield from testing.log_lines) == []


@testing.effect
def test_a_typo_suggests_the_flag():
    error = yield from run(["--nmae", "demo"]).flip()
    assert isinstance(error, ShowHelp)
    printed = "\n".join(map(str, (yield from testing.error_lines)))
    assert "Did you mean this?\n    --name" in printed

Reference: pyfect.cli, pyfect.cli.command, pyfect.cli.flag, pyfect.cli.prompt.