|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Callable, Dict, Optional, Sequence, TypeVar, overload |
| 4 | + |
| 5 | +import tyro |
| 6 | + |
| 7 | +CallableT = TypeVar("CallableT", bound=Callable) |
| 8 | + |
| 9 | + |
| 10 | +class SubcommandApp: |
| 11 | + """This module provides a decorator-based API for subcommands in `tyro`, inspired by click. |
| 12 | +
|
| 13 | + Example: |
| 14 | +
|
| 15 | + ```python |
| 16 | + from tyro.extras import SubcommandApp |
| 17 | +
|
| 18 | + app = SubcommandApp() |
| 19 | +
|
| 20 | + @app.command |
| 21 | + def greet(name: str, loud: bool = False): |
| 22 | + '''Greet someone.''' |
| 23 | + greeting = f"Hello, {name}!" |
| 24 | + if loud: |
| 25 | + greeting = greeting.upper() |
| 26 | + print(greeting) |
| 27 | +
|
| 28 | + @app.command(name="addition") |
| 29 | + def add(a: int, b: int): |
| 30 | + '''Add two numbers.''' |
| 31 | + print(f"{a} + {b} = {a + b}") |
| 32 | +
|
| 33 | + if __name__ == "__main__": |
| 34 | + app.cli() |
| 35 | + ``` |
| 36 | +
|
| 37 | + Usage: |
| 38 | + `python my_script.py greet Alice` |
| 39 | + `python my_script.py greet Bob --loud` |
| 40 | + `python my_script.py addition 5 3` |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self) -> None: |
| 44 | + self._subcommands: Dict[str, Callable] = {} |
| 45 | + |
| 46 | + @overload |
| 47 | + def command(self, func: CallableT) -> CallableT: ... |
| 48 | + |
| 49 | + @overload |
| 50 | + def command( |
| 51 | + self, |
| 52 | + func: None = None, |
| 53 | + *, |
| 54 | + name: str | None = None, |
| 55 | + ) -> Callable[[CallableT], CallableT]: ... |
| 56 | + |
| 57 | + def command( |
| 58 | + self, |
| 59 | + func: CallableT | None = None, |
| 60 | + *, |
| 61 | + name: str | None = None, |
| 62 | + ) -> CallableT | Callable[[CallableT], CallableT]: |
| 63 | + """A decorator to register a function as a subcommand. |
| 64 | +
|
| 65 | + This method is inspired by Click's @cli.command() decorator. |
| 66 | + It adds the decorated function to the list of subcommands. |
| 67 | +
|
| 68 | + Args: |
| 69 | + func: The function to register as a subcommand. If None, returns a |
| 70 | + function to use as a decorator. |
| 71 | + name: The name of the subcommand. If None, the name of the function is used. |
| 72 | + """ |
| 73 | + |
| 74 | + def inner(func: CallableT) -> CallableT: |
| 75 | + nonlocal name |
| 76 | + if name is None: |
| 77 | + name = func.__name__ |
| 78 | + |
| 79 | + self._subcommands[name] = func |
| 80 | + return func |
| 81 | + |
| 82 | + if func is not None: |
| 83 | + return inner(func) |
| 84 | + else: |
| 85 | + return inner |
| 86 | + |
| 87 | + def cli( |
| 88 | + self, |
| 89 | + *, |
| 90 | + prog: Optional[str] = None, |
| 91 | + description: Optional[str] = None, |
| 92 | + args: Optional[Sequence[str]] = None, |
| 93 | + use_underscores: bool = False, |
| 94 | + sort_subcommands: bool = True, |
| 95 | + ) -> Any: |
| 96 | + """Run the command-line interface. |
| 97 | +
|
| 98 | + This method creates a CLI using tyro, with all subcommands registered using |
| 99 | + :func:`command()`. |
| 100 | +
|
| 101 | + Args: |
| 102 | + prog: The name of the program printed in helptext. Mirrors argument from |
| 103 | + `argparse.ArgumentParser()`. |
| 104 | + description: Description text for the parser, displayed when the --help flag is |
| 105 | + passed in. If not specified, the class docstring is used. Mirrors argument from |
| 106 | + `argparse.ArgumentParser()`. |
| 107 | + args: If set, parse arguments from a sequence of strings instead of the |
| 108 | + commandline. Mirrors argument from `argparse.ArgumentParser.parse_args()`. |
| 109 | + use_underscores: If True, use underscores as a word delimiter instead of hyphens. |
| 110 | + This primarily impacts helptext; underscores and hyphens are treated equivalently |
| 111 | + when parsing happens. We default helptext to hyphens to follow the GNU style guide. |
| 112 | + https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html |
| 113 | + sort_subcommands: If True, sort the subcommands alphabetically by name. |
| 114 | + """ |
| 115 | + assert self._subcommands is not None |
| 116 | + |
| 117 | + # Sort subcommands by name. |
| 118 | + if sort_subcommands: |
| 119 | + sorted_subcommands = dict( |
| 120 | + sorted(self._subcommands.items(), key=lambda x: x[0]) |
| 121 | + ) |
| 122 | + else: |
| 123 | + sorted_subcommands = self._subcommands |
| 124 | + |
| 125 | + if len(sorted_subcommands) == 1: |
| 126 | + return tyro.cli( |
| 127 | + next(iter(sorted_subcommands.values())), |
| 128 | + prog=prog, |
| 129 | + description=description, |
| 130 | + args=args, |
| 131 | + use_underscores=use_underscores, |
| 132 | + ) |
| 133 | + else: |
| 134 | + return tyro.extras.subcommand_cli_from_dict( |
| 135 | + sorted_subcommands, |
| 136 | + prog=prog, |
| 137 | + description=description, |
| 138 | + args=args, |
| 139 | + use_underscores=use_underscores, |
| 140 | + ) |
0 commit comments