diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/INSTALLER b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..5c69047b2eb8235994febeeae1da4a82365a240a --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +uv \ No newline at end of file diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/METADATA b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..adb3f97dc86b6a6f78c5aa6c8d68456859a98c60 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/METADATA @@ -0,0 +1,158 @@ +Metadata-Version: 2.4 +Name: brotli +Version: 1.2.0 +Summary: Python bindings for the Brotli compression library +Home-page: https://github.com/google/brotli +Author: The Brotli Authors +License: MIT +Platform: Posix +Platform: MacOS X +Platform: Windows +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Classifier: Programming Language :: C +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.3 +Classifier: Programming Language :: Python :: 3.4 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Unix Shell +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: System :: Archiving +Classifier: Topic :: System :: Archiving :: Compression +Classifier: Topic :: Text Processing :: Fonts +Classifier: Topic :: Utilities +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: author +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: platform +Dynamic: summary + +

+ GitHub Actions Build Status + Fuzzing Status +

+

Brotli

+ +### Introduction + +Brotli is a generic-purpose lossless compression algorithm that compresses data +using a combination of a modern variant of the LZ77 algorithm, Huffman coding +and 2nd order context modeling, with a compression ratio comparable to the best +currently available general-purpose compression methods. It is similar in speed +with deflate but offers more dense compression. + +The specification of the Brotli Compressed Data Format is defined in +[RFC 7932](https://datatracker.ietf.org/doc/html/rfc7932). + +Brotli is open-sourced under the MIT License, see the LICENSE file. + +> **Please note:** brotli is a "stream" format; it does not contain +> meta-information, like checksums or uncompressed data length. It is possible +> to modify "raw" ranges of the compressed stream and the decoder will not +> notice that. + +### Installation + +In most Linux distributions, installing `brotli` is just a matter of using +the package management system. For example in Debian-based distributions: +`apt install brotli` will install `brotli`. On MacOS, you can use +[Homebrew](https://brew.sh/): `brew install brotli`. + +[![brotli packaging status](https://repology.org/badge/vertical-allrepos/brotli.svg?exclude_unsupported=1&columns=3&exclude_sources=modules,site&header=brotli%20packaging%20status)](https://repology.org/project/brotli/versions) + +Of course you can also build brotli from sources. + +### Build instructions + +#### Vcpkg + +You can download and install brotli using the +[vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager: + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + ./vcpkg install brotli + +The brotli port in vcpkg is kept up to date by Microsoft team members and +community contributors. If the version is out of date, please [create an issue +or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + +#### Bazel + +See [Bazel](https://www.bazel.build/) + +#### CMake + +The basic commands to build and install brotli are: + + $ mkdir out && cd out + $ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./installed .. + $ cmake --build . --config Release --target install + +You can use other [CMake](https://cmake.org/) configuration. + +#### Python + +To install the latest release of the Python module, run the following: + + $ pip install brotli + +To install the tip-of-the-tree version, run: + + $ pip install --upgrade git+https://github.com/google/brotli + +See the [Python readme](python/README.md) for more details on installing +from source, development, and testing. + +### Contributing + +We glad to answer/library related questions in +[brotli mailing list](https://groups.google.com/g/brotli). + +Regular issues / feature requests should be reported in +[issue tracker](https://github.com/google/brotli/issues). + +For reporting vulnerability please read [SECURITY](SECURITY.md). + +For contributing changes please read [CONTRIBUTING](CONTRIBUTING.md). + +### Benchmarks +* [Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/) / [Unstable Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/unstable/) +* [Large Text Compression Benchmark](https://mattmahoney.net/dc/text.html) +* [Lzturbo Benchmark](https://sites.google.com/site/powturbo/home/benchmark) + +### Related projects +> **Disclaimer:** Brotli authors take no responsibility for the third party projects mentioned in this section. + +Independent [decoder](https://github.com/madler/brotli) implementation +by Mark Adler, based entirely on format specification. + +JavaScript port of brotli [decoder](https://github.com/devongovett/brotli.js). +Could be used directly via `npm install brotli` + +Hand ported [decoder / encoder](https://github.com/dominikhlbg/BrotliHaxe) +in haxe by Dominik Homberger. +Output source code: JavaScript, PHP, Python, Java and C# + +7Zip [plugin](https://github.com/mcmilk/7-Zip-Zstd) + +Dart compression framework with +[fast FFI-based Brotli implementation](https://pub.dev/documentation/es_compression/latest/brotli/) +with ready-to-use prebuilt binaries for Win/Linux/Mac diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/RECORD b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7b5c8e891de9b6097a802eab86de81c718edfec8 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/RECORD @@ -0,0 +1,9 @@ +_brotli.cpython-310-x86_64-linux-gnu.so,sha256=Rx-Ml4X8kqv4Zeyh-9KvI8XLKBBHOBqs29aTzajqizk,5170080 +brotli-1.2.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2 +brotli-1.2.0.dist-info/METADATA,sha256=-dEtUYS1CQsUay5fDWKTFSGysUNepGZDOiObt8QfyWI,6116 +brotli-1.2.0.dist-info/RECORD,, +brotli-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +brotli-1.2.0.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151 +brotli-1.2.0.dist-info/licenses/LICENSE,sha256=PRgACONpIqTo2uwRw0x68mT-1ZYtB5JK6pKMOOhmPJQ,1084 +brotli-1.2.0.dist-info/top_level.txt,sha256=gsS54HrhO3ZveFxeMrKo_7qH4Sm4TbQ7jGLVBEqJ4NI,15 +brotli.py,sha256=gTYQvw10ppmNe0fZEuiJLDiW5urBnLeyJXXgT8KUtj8,1970 diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/REQUESTED b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/WHEEL b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d170d6d9582d145f12244c4135d9446d597e1029 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..33b7cdd2dbaeddce1e35aa1a13f63d71154dc42f --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/top_level.txt b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a111e9cca6fb4d3696239f5bb98bee20cb2914e7 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_brotli +brotli diff --git a/.venv/lib/python3.10/site-packages/cyclopts/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57d19bc2973a6a307f3309af7765215e79b96533 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/__init__.py @@ -0,0 +1,112 @@ +__version__: str +try: + # _version.py is auto-generated by hatch-vcs during build from git tags + from cyclopts._version import __version__ # type: ignore[import-not-found] +except ImportError: + __version__ = "0.0.0.dev0" + +__all__ = [ + "__version__", + "App", + "Argument", + "ArgumentCollection", + "ArgumentOrderError", + "Token", + "CoercionError", + "CombinedShortOptionError", + "CommandCollisionError", + "CycloptsError", + "CycloptsPanel", + "Dispatcher", + "DocstringError", + "EditorError", + "EditorNotFoundError", + "EditorDidNotSaveError", + "EditorDidNotChangeError", + "Group", + "UnknownCommandError", + "MissingArgumentError", + "ConsumeMultipleError", + "MixedArgumentError", + "RepeatArgumentError", + "RequiresEqualsError", + "Parameter", + "ResultAction", + "UnknownOptionError", + "UnusedCliTokensError", + "UNSET", + "ValidationError", + "config", + "convert", + "default_name_transform", + "edit", + "env_var_split", + "types", + "validators", + "run", +] + +from cyclopts._convert import convert +from cyclopts._env_var import env_var_split +from cyclopts._result_action import ResultAction +from cyclopts._run import run +from cyclopts.argument import Argument, ArgumentCollection +from cyclopts.core import App +from cyclopts.exceptions import ( + ArgumentOrderError, + CoercionError, + CombinedShortOptionError, + CommandCollisionError, + ConsumeMultipleError, + CycloptsError, + DocstringError, + MissingArgumentError, + MixedArgumentError, + RepeatArgumentError, + RequiresEqualsError, + UnknownCommandError, + UnknownOptionError, + UnusedCliTokensError, + ValidationError, +) +from cyclopts.group import Group +from cyclopts.panel import CycloptsPanel +from cyclopts.parameter import Parameter +from cyclopts.protocols import Dispatcher +from cyclopts.token import Token +from cyclopts.utils import UNSET, default_name_transform + +# Lazy imports for opt-in features (saves ~6ms on import) +# These modules are only loaded when explicitly accessed by user code +_LAZY_IMPORTS = { + # Submodules - opt-in features not needed for basic CLI parsing + "config": "cyclopts.config", # Configuration file parsing (JSON, TOML, YAML, env) + "types": "cyclopts.types", # ~3ms - special types like ResolvedExistingPath + "validators": "cyclopts.validators", # ~2ms - validators like Number, Path + # Editor functionality - rarely used + "edit": "cyclopts._edit", # ~4ms + "EditorError": "cyclopts._edit", + "EditorNotFoundError": "cyclopts._edit", + "EditorDidNotSaveError": "cyclopts._edit", + "EditorDidNotChangeError": "cyclopts._edit", +} + + +def __getattr__(name: str): + """Lazy-load opt-in features and rarely-used functionality.""" + if name in _LAZY_IMPORTS: + import importlib + + module_path = _LAZY_IMPORTS[name] + if name in ("config", "types", "validators"): + # These are submodules, import the module itself + module = importlib.import_module(module_path) + globals()[name] = module + return module + else: + # These are attributes from modules (e.g., edit, EditorError) + module = importlib.import_module(module_path) + value = getattr(module, name) + globals()[name] = value + return value + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/__init__.pyi b/.venv/lib/python3.10/site-packages/cyclopts/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7a5f2b6d3b72235698043780fbfd4ad4beaf0daf --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/__init__.pyi @@ -0,0 +1,37 @@ +from cyclopts import config as config +from cyclopts import types as types +from cyclopts import validators as validators +from cyclopts._convert import convert as convert +from cyclopts._edit import EditorDidNotChangeError as EditorDidNotChangeError +from cyclopts._edit import EditorDidNotSaveError as EditorDidNotSaveError +from cyclopts._edit import EditorError as EditorError +from cyclopts._edit import EditorNotFoundError as EditorNotFoundError +from cyclopts._edit import edit as edit +from cyclopts._env_var import env_var_split as env_var_split +from cyclopts._result_action import ResultAction as ResultAction +from cyclopts._run import run as run +from cyclopts.argument import Argument as Argument +from cyclopts.argument import ArgumentCollection as ArgumentCollection +from cyclopts.core import App as App +from cyclopts.exceptions import ArgumentOrderError as ArgumentOrderError +from cyclopts.exceptions import CoercionError as CoercionError +from cyclopts.exceptions import CombinedShortOptionError as CombinedShortOptionError +from cyclopts.exceptions import CommandCollisionError as CommandCollisionError +from cyclopts.exceptions import CycloptsError as CycloptsError +from cyclopts.exceptions import DocstringError as DocstringError +from cyclopts.exceptions import MissingArgumentError as MissingArgumentError +from cyclopts.exceptions import MixedArgumentError as MixedArgumentError +from cyclopts.exceptions import RepeatArgumentError as RepeatArgumentError +from cyclopts.exceptions import UnknownCommandError as UnknownCommandError +from cyclopts.exceptions import UnknownOptionError as UnknownOptionError +from cyclopts.exceptions import UnusedCliTokensError as UnusedCliTokensError +from cyclopts.exceptions import ValidationError as ValidationError +from cyclopts.group import Group as Group +from cyclopts.panel import CycloptsPanel as CycloptsPanel +from cyclopts.parameter import Parameter as Parameter +from cyclopts.protocols import Dispatcher as Dispatcher +from cyclopts.token import Token as Token +from cyclopts.utils import UNSET as UNSET +from cyclopts.utils import default_name_transform as default_name_transform + +__version__: str diff --git a/.venv/lib/python3.10/site-packages/cyclopts/__main__.py b/.venv/lib/python3.10/site-packages/cyclopts/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..63a7d3e8236893ffdd582a25207e9825f8c5bdcc --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/__main__.py @@ -0,0 +1,6 @@ +"""Cyclopts CLI entry point.""" + +from cyclopts.cli import app + +if __name__ == "__main__": + app() diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_convert.py b/.venv/lib/python3.10/site-packages/cyclopts/_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..70390473f568933218f5ecc74f916a1945b343cd --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_convert.py @@ -0,0 +1,978 @@ +import collections.abc +import inspect +import json +import operator +import re +import sys +import typing +from collections.abc import Callable, Iterable, Sequence +from datetime import date, datetime, timedelta +from enum import Enum, Flag +from functools import partial, reduce +from typing import ( + TYPE_CHECKING, + Any, + Literal, + TypeVar, + Union, + get_args, + get_origin, +) + +if sys.version_info >= (3, 12): + from typing import TypeAliasType +else: + TypeAliasType = None + +from cyclopts.annotations import ( + ITERABLE_TYPES, + get_annotated_discriminator, + is_annotated, + is_enum_flag, + is_nonetype, + is_union, + resolve, + resolve_optional, +) +from cyclopts.exceptions import CoercionError, ValidationError +from cyclopts.field_info import FieldInfo, get_field_infos +from cyclopts.utils import UNSET, default_name_transform, grouper, is_builtin, is_class_and_subclass + +if sys.version_info >= (3, 12): # pragma: no cover + from typing import TypeAliasType +else: # pragma: no cover + TypeAliasType = None + +if TYPE_CHECKING: + from cyclopts.argument import Token + + +T = TypeVar("T") +E = TypeVar("E", bound=Enum) +F = TypeVar("F", bound=Flag) + +# Mapping from bare concrete types to their default parameterized versions. +# Used when type parameters are not specified (e.g., bare `list` becomes `list[str]`). +_implicit_iterable_type_mapping: dict[type, type] = { + frozenset: frozenset[str], + list: list[str], + set: set[str], + tuple: tuple[str, ...], + dict: dict[str, str], +} + +# Mapping from abstract collection types to their concrete implementations. +# Used to convert abstract types like collections.abc.Set to concrete types like set. +_abstract_to_concrete_type_mapping: dict[type, type] = { + Iterable: list, + typing.Sequence: list, + Sequence: list, + collections.abc.Set: set, + collections.abc.MutableSet: set, + collections.abc.MutableSequence: list, + collections.abc.Mapping: dict, + collections.abc.MutableMapping: dict, +} + +NestedCliArgs = dict[str, Union[Sequence[str], "NestedCliArgs"]] + + +def _bool(s: str) -> bool: + s = s.lower() + if s in {"no", "n", "0", "false", "f"}: + return False + elif s in {"yes", "y", "1", "true", "t"}: + return True + else: + # Cyclopts is a little bit conservative when coercing strings into boolean. + raise CoercionError(target_type=bool) + + +def _int(s: str) -> int: + s = s.lower() + if s.startswith("0x"): + return int(s, 16) + elif s.startswith("0o"): + return int(s, 8) + elif s.startswith("0b"): + return int(s, 2) + elif "." in s: + # Casting to a float first allows for things like "30.0" + # We handle this conditionally because very large integers can lose + # meaningful precision when cast to a float. + return int(round(float(s))) + else: + return int(s) + + +def _bytes(s: str) -> bytes: + return bytes(s, encoding="utf8") + + +def _bytearray(s: str) -> bytearray: + return bytearray(_bytes(s)) + + +def _date(s: str) -> date: + """Parse a date string. + + Returns + ------- + datetime.date + """ + return date.fromisoformat(s) + + +def _datetime(s: str) -> datetime: + """Parse a datetime string. + + Returns + ------- + datetime.datetime + """ + try: + return datetime.fromisoformat(s) + except ValueError: + # Fallback for space-separated format (not ISO 8601 compliant) + # Python 3.11+ fromisoformat() accepts spaces, but 3.10 doesn't + # Convert space to 'T' to make it ISO-compliant + return datetime.fromisoformat(s.strip().replace(" ", "T", 1)) + + +def _timedelta(s: str) -> timedelta: + """Parse a timedelta string.""" + negative = False + if s.startswith("-"): + negative = True + s = s[1:] + + matches = re.findall(r"((\d+\.\d+|\d+)([smhdwMy]))", s) + + if not matches: + raise ValueError(f"Could not parse duration string: {s}") + + seconds = 0 + for _, value, unit in matches: + value = float(value) + if unit == "s": + seconds += value + elif unit == "m": + seconds += value * 60 + elif unit == "h": + seconds += value * 3600 + elif unit == "d": + seconds += value * 86400 + elif unit == "w": + seconds += value * 604800 + elif unit == "M": + # Approximation: 1 month = 30 days + seconds += value * 2592000 + elif unit == "y": + # Approximation: 1 year = 365 days + seconds += value * 31536000 + + if negative: + seconds = -seconds + return timedelta(seconds=seconds) + + +def get_enum_member( + type_: type[E], + token: Union["Token", str], + name_transform: Callable[[str], str], +) -> E: + """Match a token's value to an enum's member. + + Applies ``name_transform`` to both the value and the member. + """ + from cyclopts.argument import Token + + is_token = isinstance(token, Token) + value = token.value if is_token else token + value_transformed = name_transform(value) + for name, member in type_.__members__.items(): + if name_transform(name) == value_transformed: + return member + raise CoercionError( + token=token if is_token else None, + target_type=type_, + ) + + +def convert_enum_flag( + enum_type: type[F], + tokens: Iterable[str] | Iterable["Token"], + name_transform: Callable[[str], str], +) -> F: + """Convert tokens to a Flag enum value. + + Parameters + ---------- + enum_type : type[F] + The Flag enum type to convert to. + tokens : Iterable[str] | Iterable[Token] + The tokens to convert. Can be member names or :class:`Token` objects. + name_transform : Callable[[str], str] | None + Function to transform names for comparison. + + Returns + ------- + F + The combined flag value. + + Raises + ------ + CoercionError + If a token is not a valid flag member. + """ + return reduce( + operator.or_, + (get_enum_member(enum_type, token, name_transform) for token in tokens), + enum_type(0), + ) + + +# For types that need more logic than just invoking their type +_converters: dict[Any, Callable] = { + bool: _bool, + int: _int, + bytes: _bytes, + bytearray: _bytearray, + date: _date, + datetime: _datetime, + timedelta: _timedelta, +} + + +def _convert_tuple( + type_: type[Any], + *tokens: "Token", + converter: Callable[[type, str], Any] | None, + name_transform: Callable[[str], str], +) -> tuple: + convert = partial(_convert, converter=converter, name_transform=name_transform) + inner_types = tuple(x for x in get_args(type_) if x is not ...) + inner_token_count, consume_all = token_count(type_) + # Elements like boolean-flags will have an inner_token_count of 0. + inner_token_count = max(inner_token_count, 1) + if consume_all: + # variable-length tuple (list-like) + remainder = len(tokens) % inner_token_count + if remainder: + raise CoercionError( + msg=f"Incorrect number of arguments: expected multiple of {inner_token_count} but got {len(tokens)}." + ) + if len(inner_types) == 1: + inner_type = inner_types[0] + elif len(inner_types) == 0: + inner_type = str + else: + raise ValueError("A tuple must have 0 or 1 inner-types.") + + return tuple( + convert(inner_type, chunk[0] if inner_token_count == 1 else chunk) + for chunk in grouper(tokens, inner_token_count) + ) + else: + # Fixed-length tuple + if inner_token_count != len(tokens): + raise CoercionError( + msg=f"Incorrect number of arguments: expected {inner_token_count} but got {len(tokens)}." + ) + args_per_convert = [token_count(x)[0] for x in inner_types] + it = iter(tokens) + batched = [[next(it) for _ in range(size)] for size in args_per_convert] + batched = [elem[0] if len(elem) == 1 else elem for elem in batched] + out = tuple(convert(inner_type, arg) for inner_type, arg in zip(inner_types, batched, strict=False)) + return out + + +def _validate_json_extra_keys( + data: dict, + type_: type, + token: "Token | None" = None, +) -> None: + """Validate that JSON data doesn't contain extra keys not in the type's fields. + + Parameters + ---------- + data : dict + The JSON dictionary to validate. + type_ : type + The target type (dataclass, etc.) to validate against. + token : Token | None + Optional token for error context. + + Raises + ------ + CoercionError + If the data contains keys not present in the type's fields. + """ + field_infos = get_field_infos(type_) + # Collect all valid names including aliases (e.g., Pydantic camelCase aliases) + valid_names: set[str] = set() + for field_name, field_info in field_infos.items(): + valid_names.add(field_name) + valid_names.update(field_info.names) + extra_keys = set(data.keys()) - valid_names + if extra_keys: + extra_key = sorted(extra_keys)[0] # Report first extra key alphabetically for determinism + valid_fields = ", ".join(sorted(field_infos.keys())) + raise CoercionError( + msg=f'Unknown field "{extra_key}" in JSON for {type_.__name__}. Valid fields: {valid_fields}', + target_type=type_, + token=token, + ) + + +def _convert_json( + type_: Any, + data: dict, + field_infos: dict, + converter: Callable | None, + name_transform: Callable[[str], str], +): + """Convert JSON dict to dataclass with proper type conversion for fields. + + Parameters + ---------- + type_ : Type + The dataclass type to create. + data : dict + The JSON dictionary containing field values. + field_infos : dict + Field information from the dataclass. + converter : Callable | None + Optional converter function. + name_transform : Callable[[str], str] + Function to transform field names. + + Returns + ------- + Instance of type_ with properly converted field values. + """ + from cyclopts.token import Token + + # Validate no extra keys in JSON data + _validate_json_extra_keys(data, type_) + + converted_data = {} + for field_name, field_info in field_infos.items(): + if field_name in data: + value = data[field_name] + # Convert the value to the proper type + if value is not None and not is_class_and_subclass(field_info.hint, str): + # Create a token for the value and convert it + token = Token(value=json.dumps(value) if isinstance(value, dict | list) else str(value)) + # Always attempt conversion, let errors propagate for consistency + converted_value = convert(field_info.hint, [token], converter, name_transform) + else: + converted_value = value + converted_data[field_name] = converted_value + + # Create the dataclass with converted values + return type_(**converted_data) + + +def _create_json_decode_error_message( + token: "Token", + type_: Any, + error: json.JSONDecodeError, +) -> str: + """Create a helpful error message for JSON decode errors. + + Parameters + ---------- + token : Token + The token containing the invalid JSON. + type_ : Type + The target type we were trying to convert to. + error : json.JSONDecodeError + The JSON decode error that occurred. + + Returns + ------- + str + A formatted error message with context and hints. + """ + value_str = token.value.strip() + + # Try to provide context around the error + error_pos = error.pos if hasattr(error, "pos") else error.colno - 1 if hasattr(error, "colno") else 0 + + # Create a snippet showing the error location + snippet_start = max(0, error_pos - 20) + snippet_end = min(len(value_str), error_pos + 20) + snippet = value_str[snippet_start:snippet_end] + + # Add markers if we truncated + if snippet_start > 0: + snippet = "..." + snippet + if snippet_end < len(value_str): + snippet = snippet + "..." + + # Calculate where the error marker should point + marker_pos = error_pos - snippet_start + if snippet_start > 0: + marker_pos += 3 # Account for "..." + + # Common error patterns with helpful hints + hint = "" + if re.search(r"\bTrue\b", value_str): + hint = "\n Hint: Use lowercase 'true' instead of Python's True" + elif re.search(r"\bFalse\b", value_str): + hint = "\n Hint: Use lowercase 'false' instead of Python's False" + elif re.search(r"\bNone\b", value_str): + hint = "\n Hint: Use 'null' instead of Python's None" + elif "'" in value_str: + hint = "\n Hint: JSON requires double quotes, not single quotes" + + return f"Invalid JSON for {type_.__name__}:\n {snippet}\n {' ' * marker_pos}^ {error.msg}{hint}" + + +def instantiate_from_dict(type_: type[T], data: dict[str, Any]) -> T: + """Instantiate a type with proper handling of parameter kinds. + + Respects POSITIONAL_ONLY, KEYWORD_ONLY, and POSITIONAL_OR_KEYWORD parameter kinds + when constructing the object. + + This function is necessary because `inspect.signature().bind(**data)` has the same + limitation we're solving: it cannot accept positional-only parameters as keyword + arguments. For example, `def __init__(self, a, /, b)` requires `a` to be passed + positionally, but when we have a dict `{"a": 1, "b": 2}`, we need to transform + this into the call `type_(1, b=2)`. + + Parameters + ---------- + type_ : type[T] + The type to instantiate. + data : dict[str, Any] + Dictionary mapping field names to values. + + Returns + ------- + T + Instance of type_ constructed from data. + """ + field_infos = get_field_infos(type_) + if not field_infos: + return type_(**data) + + pos_args = [] + kwargs = {} + + for field_name, value in data.items(): + field_info = field_infos.get(field_name) + if field_info and field_info.kind == FieldInfo.POSITIONAL_ONLY: + pos_args.append((field_name, value)) + else: + kwargs[field_name] = value + + # Sort positional args by their order in field_infos + field_names_order = list(field_infos.keys()) + pos_args.sort(key=lambda x: field_names_order.index(x[0])) + + return type_(*(v for _, v in pos_args), **kwargs) + + +def _convert_structured_type( + type_: type[T], + token: Sequence["Token"], + field_infos: dict[str, "FieldInfo"], + convert: Callable, +) -> T: + """Convert tokens to a structured type with proper positional/keyword argument handling. + + Respects the parameter kind of each field: + - POSITIONAL_ONLY: passed as positional argument + - KEYWORD_ONLY or POSITIONAL_OR_KEYWORD: passed as keyword argument + + This correctly handles types with keyword-only fields (e.g., dataclasses with kw_only=True). + + Parameters + ---------- + type_ : type[T] + The target structured type to instantiate. + token : Sequence[Token] + The tokens to convert. + field_infos : dict[str, FieldInfo] + Field information for the structured type. + convert : Callable + Conversion function for nested types. + + Returns + ------- + T + Instance of type_ constructed from the tokens. + """ + i = 0 + data = {} + hint = type_ + + for field_name, field_info in field_infos.items(): + hint = field_info.hint + + # Convert the token(s) for this field + if is_class_and_subclass(hint, str): # Avoids infinite recursion + value = token[i].value + i += 1 + should_break = False + else: + tokens_per_element, consume_all = token_count(hint) + if tokens_per_element == 1: + value = convert(hint, token[i]) + i += 1 + else: + value = convert(hint, token[i : i + tokens_per_element]) + i += tokens_per_element + should_break = consume_all + + data[field_name] = value + + # Handle consume_all or end of tokens + if should_break: + break + if i == len(token): + break + + assert i == len(token) + return instantiate_from_dict(type_, data) + + +def _convert( + type_, + token: Union["Token", Sequence["Token"]], + *, + converter: Callable[[Any, str], Any] | None, + name_transform: Callable[[str], str], +): + """Inner recursive conversion function for public ``convert``. + + Parameters + ---------- + converter: Callable + name_transform: Callable + """ + from cyclopts.argument import Token + from cyclopts.parameter import Parameter + + converter_needs_token = False + if is_annotated(type_): + from cyclopts.parameter import Parameter + + type_, cparam = Parameter.from_annotation(type_) + if cparam.converter: + converter_needs_token = True + + def converter_with_token(t_, value): + assert cparam.converter + + # Resolve string converters to methods on the type + resolved_converter = cparam.converter + if isinstance(resolved_converter, str): + resolved_converter = getattr(t_, resolved_converter) + + # Detect bound methods (classmethods/instance methods) + # Bound methods already have their first parameter bound + if inspect.ismethod(resolved_converter): + # Call with just tokens - cls/self already bound + return resolved_converter((value,)) + else: + # Regular function - pass type and tokens + return resolved_converter(t_, (value,)) + + converter = converter_with_token + + if cparam.name_transform: + name_transform = cparam.name_transform + else: + cparam = None + + convert = partial(_convert, converter=converter, name_transform=name_transform) + convert_tuple = partial(_convert_tuple, converter=converter, name_transform=name_transform) + + origin_type = get_origin(type_) + # Normalize abstract origin types to concrete types early + # (e.g., collections.abc.Set -> set) so we only check ITERABLE_TYPES later + if origin_type in _abstract_to_concrete_type_mapping: + origin_type = _abstract_to_concrete_type_mapping[origin_type] + # Inner types **may** be ``Annotated`` + inner_types = get_args(type_) + + if type_ is dict: + out = convert(dict[str, str], token) + elif type_ in _implicit_iterable_type_mapping: + out = convert(_implicit_iterable_type_mapping[type_], token) + elif type_ in _abstract_to_concrete_type_mapping: + # Bare abstract type (e.g., collections.abc.Set with no [T]) + # Convert to default parameterized concrete type + concrete_type = _abstract_to_concrete_type_mapping[type_] + default_param = _implicit_iterable_type_mapping.get(concrete_type, concrete_type) + out = convert(default_param, token) + elif TypeAliasType is not None and isinstance(type_, TypeAliasType): + out = convert(type_.__value__, token) + elif is_union(origin_type): + for t in inner_types: + if is_nonetype(t): + continue + try: + out = convert(t, token) + break + except Exception: + pass + else: + if isinstance(token, Sequence): + raise ValueError # noqa: TRY004 + raise CoercionError(token=token, target_type=type_) + elif origin_type is Literal: + # Try coercing the token into each allowed Literal value (left-to-right). + last_coercion_error = None + for choice in get_args(type_): + try: + res = convert(type(choice), token) + except CoercionError as e: + last_coercion_error = e + continue + if res == choice: + out = res + break + else: + if last_coercion_error: + last_coercion_error.target_type = type_ + raise last_coercion_error + else: + raise CoercionError(token=token[0] if isinstance(token, Sequence) else token, target_type=type_) + elif origin_type is tuple: + if isinstance(token, Token): + # E.g. Tuple[str] (Annotation: tuple containing a single string) + out = convert_tuple(type_, token, converter=converter) + else: + out = convert_tuple(type_, *token, converter=converter) + elif origin_type in ITERABLE_TYPES: + # NOT including tuple; handled in ``origin_type is tuple`` body above. + # Note: origin_type has already been normalized from abstract to concrete + count, _ = token_count(inner_types[0]) + if not isinstance(token, Sequence): + raise ValueError + + # Check if tokens are JSON strings + inner_type = inner_types[0] + if ( + count > 1 + and any(isinstance(t, Token) and t.value.strip().startswith("{") for t in token) + and inner_type is not str + ): + # Each token is a complete JSON representation of the dataclass + gen = token + elif count > 1: + gen = zip(*[iter(token)] * count, strict=False) + else: + gen = token + out = origin_type(convert(inner_types[0], e) for e in gen) + elif is_class_and_subclass(type_, Flag): + # TODO: this might never execute since enum.Flag is now handled in ``convert``. + out = convert_enum_flag(type_, token if isinstance(token, Sequence) else [token], name_transform) + elif is_class_and_subclass(type_, Enum): + if isinstance(token, Sequence): + raise ValueError + + if converter is None: + out = get_enum_member(type_, token, name_transform) + else: + out = converter(type_, token.value) + else: + field_infos = get_field_infos(type_) + # Hope that if there is no field_info, that it takes `*args` and would be happy with a single ``str`` input. + # This is common for many types, such as libraries that try to mimic pathlib.Path interface. + # TODO: This doesn't respect the type-annotation of ``*args``. + if is_builtin(type_) or not field_infos: + assert isinstance(token, Token) + try: + if token.implicit_value is not UNSET: + out = token.implicit_value + elif converter is None: + out = _converters.get(type_, type_)(token.value) # pyright: ignore[reportOptionalCall] + elif converter_needs_token: + out = converter(type_, token) # pyright: ignore[reportArgumentType] + else: + out = converter(type_, token.value) + except CoercionError as e: + if e.target_type is None: + e.target_type = type_ + if e.token is None: + e.token = token + raise + except ValueError: + raise CoercionError(token=token, target_type=type_) from None + else: + # Convert it into a user-supplied class. + # First check if we have a single token that's a JSON string + if isinstance(token, Token) and token.value.strip().startswith("{") and type_ is not str: + try: + data = json.loads(token.value) + if not isinstance(data, dict): + # JSON was valid but didn't produce a dict (e.g., it was an array or scalar) + raise TypeError # noqa: TRY301 + # Convert dict to dataclass with proper type conversion + out = _convert_json(type_, data, field_infos, converter, name_transform) + except json.JSONDecodeError as e: + # Create helpful error message for invalid JSON + msg = _create_json_decode_error_message(token, type_, e) + raise CoercionError(msg=msg, token=token, target_type=type_) from e + except TypeError: + # Fall back to positional argument parsing + if not isinstance(token, Sequence): + token = [token] + out = _convert_structured_type(type_, token, field_infos, convert) + else: + # Standard positional argument parsing + if not isinstance(token, Sequence): + token = [token] + out = _convert_structured_type(type_, token, field_infos, convert) + + if cparam: + # An inner type may have an independent Parameter annotation; + # e.g.: + # Uint8 = Annotated[int, ...] + # rgb: tuple[Uint8, Uint8, Uint8] + try: + for validator in cparam.validator: # pyright: ignore + validator(type_, out) + except (AssertionError, ValueError, TypeError) as e: + raise ValidationError(exception_message=e.args[0] if e.args else "", value=out) from e + + return out + + +def convert( + type_: Any, + tokens: Sequence[str] | Sequence["Token"] | NestedCliArgs, + converter: Callable[[type, str], Any] | None = None, + name_transform: Callable[[str], str] | None = None, +): + """Coerce variables into a specified type. + + Internally used to coercing string CLI tokens into python builtin types. + Externally, may be useful in a custom converter. + See Cyclopt's automatic coercion rules :doc:`/rules`. + + If ``type_`` **is not** iterable, then each element of ``tokens`` will be converted independently. + If there is more than one element, then the return type will be a ``Tuple[type_, ...]``. + If there is a single element, then the return type will be ``type_``. + + If ``type_`` **is** iterable, then all elements of ``tokens`` will be collated. + + Parameters + ---------- + type_: Type + A type hint/annotation to coerce ``*args`` into. + tokens: Union[Sequence[str], NestedCliArgs] + String tokens to coerce. + Generally, either a list of strings, or a dictionary of list of strings (recursive). + Each leaf in the dictionary tree should be a list of strings. + converter: Optional[Callable[[Type, str], Any]] + An optional function to convert tokens to the inner-most types. + The converter should have signature: + + .. code-block:: python + + def converter(type_: type, value: str) -> Any: + "Perform conversion of string token." + + This allows to use the :func:`convert` function to handle the the difficult task + of traversing lists/tuples/unions/etc, while leaving the final conversion logic to + the caller. + name_transform: Optional[Callable[[str], str]] + Currently only used for ``Enum`` type hints. + A function that transforms enum names and CLI values into a normalized format. + + The function should have signature: + + .. code-block:: python + + def name_transform(s: str) -> str: + "Perform name transform." + + where the returned value is the name to be used on the CLI. + + If ``None``, defaults to ``cyclopts.default_name_transform``. + + Returns + ------- + Any + Coerced version of input ``*args``. + """ + from cyclopts.argument import Token + + if not tokens: + raise ValueError + + if not isinstance(tokens, dict) and isinstance(tokens[0], str): + tokens = tuple(Token(value=str(x)) for x in tokens) + + if name_transform is None: + name_transform = default_name_transform + + convert_priv = partial(_convert, converter=converter, name_transform=name_transform) + convert_tuple = partial(_convert_tuple, converter=converter, name_transform=name_transform) + type_ = resolve(type_) + + if type_ is Any: + type_ = str + + type_ = _implicit_iterable_type_mapping.get(type_, type_) + + # Handle bare abstract types (e.g., collections.abc.Set without [T]) + # Convert to their default parameterized concrete versions + if type_ in _abstract_to_concrete_type_mapping: + concrete_type = _abstract_to_concrete_type_mapping[type_] + type_ = _implicit_iterable_type_mapping.get(concrete_type, concrete_type) + + origin_type = get_origin(type_) + # Normalize abstract origin types to concrete types early + if origin_type in _abstract_to_concrete_type_mapping: + origin_type = _abstract_to_concrete_type_mapping[origin_type] + maybe_origin_type = origin_type or type_ + + if origin_type is tuple: + return convert_tuple(type_, *tokens) # pyright: ignore + elif maybe_origin_type in ITERABLE_TYPES: + return convert_priv(type_, tokens) # pyright: ignore + elif maybe_origin_type is dict: + if not isinstance(tokens, dict): + raise ValueError # Programming error + try: + value_type = get_args(type_)[1] + except IndexError: + value_type = str + dict_converted = { + k: convert(value_type, v, converter=converter, name_transform=name_transform) for k, v in tokens.items() + } + return _converters.get(maybe_origin_type, maybe_origin_type)(**dict_converted) + elif isinstance(tokens, dict): + raise ValueError(f"Dictionary of tokens provided for unknown {type_!r}.") # Programming error + elif is_enum_flag(maybe_origin_type): + # Unlike other types that can accept multiple tokens, the result is not a sequence, it's a single + # enum.Flag object. + return convert_enum_flag(maybe_origin_type, tokens, name_transform) + else: + tokens_per_element, consume_all = token_count(type_) + if consume_all: + return convert_priv(type_, tokens) # pyright: ignore + elif len(tokens) == 1: + return convert_priv(type_, tokens[0]) # pyright: ignore + elif tokens_per_element == 1: + return [convert_priv(type_, item) for item in tokens] # pyright: ignore + elif len(tokens) == tokens_per_element: + return convert_priv(type_, tokens) # pyright: ignore + else: + raise NotImplementedError("Unreachable?") + + +def token_count(type_: Any, skip_converter_params: bool = False) -> tuple[int, bool]: + """The number of tokens after a keyword the parameter should consume. + + Parameters + ---------- + type_: Type + A type hint/annotation to infer token_count from if not explicitly specified. + skip_converter_params: bool + If True, don't extract converter parameters from __cyclopts__. + Used to prevent infinite recursion when determining consume_all behavior. + + Returns + ------- + int + Number of tokens to consume. + bool + If this is ``True`` and positional, consume all remaining tokens. + The returned number of tokens constitutes a single element of the iterable-to-be-parsed. + """ + # Discriminated unions (e.g. Annotated[Cat | Dog, pydantic.Field(discriminator="type")]) + # consume a single JSON string token regardless of member field counts. + # Check before get_parameters strips the Annotated metadata. + if get_annotated_discriminator(resolve_optional(type_)) is not None: + return 1, False + + # Check for explicit n_tokens in Parameter annotation before resolving + # This handles nested cases like tuple[Annotated[str, Parameter(n_tokens=2)], int] + from cyclopts.parameter import get_parameters + + resolved_type, parameters = get_parameters(type_, skip_converter_params=skip_converter_params) + for param in parameters: + if param.n_tokens is not None: + if param.n_tokens == -1: + return 1, True + else: + # Recursively determine consume_all from the type's natural structure. + # Only recurse if the type has changed (e.g., Annotated wrapper was removed). + # If resolved_type is the same as type_, recursing would cause infinite loop. + if resolved_type is not type_: + # Skip converter params to avoid infinite recursion when converter is decorated + # with @Parameter(n_tokens=...) and attached to a class via @Parameter(converter=...). + _, consume_all_from_type = token_count(resolved_type, skip_converter_params=True) + else: + # Type didn't change (e.g., class decorated with @Parameter(n_tokens=...)) + # Can't determine natural consume_all by recursing on same type + consume_all_from_type = False + return param.n_tokens, consume_all_from_type + + type_ = resolved_type + origin_type = get_origin(type_) + # Normalize abstract origin types to concrete types early + if origin_type in _abstract_to_concrete_type_mapping: + origin_type = _abstract_to_concrete_type_mapping[origin_type] + + # Handle bare abstract types like bare concrete types + if type_ in _abstract_to_concrete_type_mapping: + concrete_type = _abstract_to_concrete_type_mapping[type_] + type_ = _implicit_iterable_type_mapping.get(concrete_type, concrete_type) + origin_type = get_origin(type_) + + if (origin_type or type_) is tuple: + args = get_args(type_) + if args: + return sum(token_count(x)[0] for x in args if x is not ...), ... in args + else: + return 1, True + elif (origin_type or type_) is bool: + return 0, False + elif type_ in ITERABLE_TYPES or (origin_type in ITERABLE_TYPES and len(get_args(type_)) == 0): + return 1, True + elif is_enum_flag(type_): + return 1, True + elif origin_type in ITERABLE_TYPES and len(get_args(type_)): + return token_count(get_args(type_)[0])[0], True + elif TypeAliasType is not None and isinstance(type_, TypeAliasType): + return token_count(type_.__value__) + elif is_union(type_): + sub_args = get_args(type_) + token_count_target = token_count(sub_args[0]) + for sub_type_ in sub_args[1:]: + this = token_count(sub_type_) + if this != token_count_target: + raise ValueError( + f"Cannot Union types that consume different numbers of tokens: {sub_args[0]} {sub_type_}" + ) + return token_count_target + elif is_builtin(type_): + # Many builtins actually take in VAR_POSITIONAL when we really just want 1 argument. + return 1, False + else: + # This is usually/always a custom user-defined class. + field_infos = get_field_infos(type_) + count, consume_all = 0, False + for value in field_infos.values(): + if value.kind is value.VAR_POSITIONAL: + consume_all = True + elif not value.required: + continue + elem_count, elem_consume_all = token_count(value.hint) + count += elem_count + consume_all |= elem_consume_all + + # classes like ``enum.Enum`` can slip through here with a 0 count. + if not count: + return 1, False + + return count, consume_all diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_edit.py b/.venv/lib/python3.10/site-packages/cyclopts/_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..a32637ebd83a274d64b4965d1ee01bededdfb37b --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_edit.py @@ -0,0 +1,108 @@ +import os +import tempfile +import time +from collections.abc import Sequence +from pathlib import Path + + +class EditorError(Exception): + """Root editor-related error. + + Root exception raised by all exceptions in :func:`.edit`. + """ + + +class EditorDidNotSaveError(EditorError): + """User did not save upon exiting :func:`.edit`.""" + + +class EditorDidNotChangeError(EditorError): + """User did not edit file contents in :func:`.edit`.""" + + +class EditorNotFoundError(EditorError): + """Could not find a valid text editor for :func`.edit`.""" + + +def edit( + initial_text: str = "", + *, + fallback_editors: Sequence[str] = ("nano", "vim", "notepad", "gedit"), + editor_args: Sequence[str] = (), + path: str | Path = "", + encoding: str = "utf-8", + save: bool = True, + required: bool = True, +) -> str: + """Get text input from a user by launching their default text editor. + + Parameters + ---------- + initial_text: str + Initial text to populate the text file with. + fallback_editors: Sequence[str] + If the text editor cannot be determined from the environment variable ``EDITOR``, attempt to use these text editors in the order provided. + editor_args: Sequence[str] + Additional CLI arguments that are passed along to the editor-launch command. + path: Union[str, Path] + If specified, the path to the file that should be opened. + Text editors typically display this, so a custom path may result in a better user-interface. + Defaults to a temporary text file. + encoding: str + File encoding to use. + save: bool + **Require** the user to save before exiting the editor. Otherwise raises :exc:`EditorDidNotSaveError`. + required: bool + **Require** for the saved text to be different from ``initial_text``. Otherwise raises :exc:`EditorDidNotChangeError`. + + Raises + ------ + EditorError + Base editor error exception. Explicitly raised if editor subcommand + returned a non-zero exit code. + EditorNotFoundError + A suitable text editor could not be found. + EditorDidNotSaveError + The user exited the text-editor without saving and ``save=True``. + EditorDidNotChangeError + The user did not change the file contents and ``required=True``. + + Returns + ------- + str + The resulting text that was saved by the text editor. + """ + import shutil + import subprocess + + for editor in (os.environ.get("EDITOR"), *fallback_editors): + if editor and shutil.which(editor): + break + else: + raise EditorNotFoundError + + if path: + path = Path(path) + path.parent.mkdir(exist_ok=True, parents=True) + else: + path = Path(tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False).name) + path.write_text(initial_text, encoding=encoding) + past_time = time.time() - 5 # arbitrarily set time to 5 seconds ago; some systems only have 1 second precision. + os.utime(path, (past_time, past_time)) # Set access and modification time + start_stat = path.stat() + + try: + subprocess.check_call([editor, path, *editor_args]) + end_stat = path.stat() + if save and end_stat.st_mtime <= start_stat.st_mtime: + raise EditorDidNotSaveError + edited_text = path.read_text(encoding=encoding) + except subprocess.CalledProcessError as e: + raise EditorError(f"{editor} exited with status {e.returncode}") from e + finally: + path.unlink(missing_ok=True) + + if required and edited_text == initial_text: + raise EditorDidNotChangeError + + return edited_text diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_env_var.py b/.venv/lib/python3.10/site-packages/cyclopts/_env_var.py new file mode 100644 index 0000000000000000000000000000000000000000..0b170a256a6c48719fd4011c21613cc36ed90f0c --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_env_var.py @@ -0,0 +1,59 @@ +import os +from pathlib import Path +from typing import Any, get_args + +from cyclopts._convert import resolve, token_count + + +def _is_path(type_) -> bool: + if type_ is Path: + return True + + for inner_type in get_args(type_): + inner_type = resolve(inner_type) + if _is_path(inner_type): + return True + + return False + + +def env_var_split( + type_: Any, + val: str, + *, + delimiter: str | None = None, +) -> list[str]: + """Type-dependent environment variable value splitting. + + Converts a single string into a list of strings. Splits when: + + * The ``type_`` is some variant of ``Iterable[pathlib.Path]`` objects. + If Windows, split on ``;``, otherwise split on ``:``. + + * Otherwise, if the ``type_`` is an ``Iterable``, split on whitespace. + Leading/trailing whitespace of each output element will be stripped. + + This function is the default value for :attr:`cyclopts.App.env_var_split`. + + Parameters + ---------- + type_: type + Type hint that we will eventually coerce into. + val: str + String to split. + delimiter: str | None + Delimiter to split ``val`` on. + If None, defaults to whitespace. + + Returns + ------- + list[str] + List of individual string tokens. + """ + type_ = resolve(type_) + count, consume_all = token_count(type_) + + if count > 1 or consume_all: + return val.split(os.pathsep) if _is_path(type_) else val.split(delimiter) + else: + return [val] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_markup.py b/.venv/lib/python3.10/site-packages/cyclopts/_markup.py new file mode 100644 index 0000000000000000000000000000000000000000..65426a4db1c1d1b029be5c52c0e1509e19198244 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_markup.py @@ -0,0 +1,132 @@ +"""Markup and format conversion utilities. + +Pure utility layer for text processing across help and docs systems. +""" + +import io +from typing import TYPE_CHECKING, Any, Optional + +if TYPE_CHECKING: + from rich.console import Console + + +def extract_text(obj: Any, console: Optional["Console"] = None, preserve_markup: bool = False) -> str: + """Extract text from Rich renderables or any object. + + Parameters + ---------- + obj : Any + Object to convert to text. + console : Console | None + Console for rendering Rich objects. + preserve_markup : bool + If True, preserve original markdown/RST markup when available. + When False, always render to plain text. + + Returns + ------- + str + Text representation (plain or with markup preserved). + """ + if obj is None: + return "" + + if hasattr(obj, "primary_renderable"): + primary = getattr(obj, "primary_renderable", None) + if primary is not None: + if preserve_markup and hasattr(primary, "markup"): + return primary.markup.rstrip() + return extract_text(primary, console, preserve_markup=preserve_markup) + + if hasattr(obj, "plain"): + return obj.plain.rstrip() + + if preserve_markup and hasattr(obj, "markup"): + return obj.markup.rstrip() + + if hasattr(obj, "__rich_console__"): + from rich.console import Console + + plain_console = Console( + file=io.StringIO(), + width=console.width if console else 120, + force_terminal=False, + no_color=True, + highlight=False, + markup=False, + emoji=False, + ) + with plain_console.capture() as capture: + plain_console.print(obj, end="") + return capture.get().rstrip() + + return str(obj).rstrip() + + +def escape_rst(text: str | None) -> str: + """Escape special reStructuredText characters in text. + + Parameters + ---------- + text : str | None + Text to escape. Can be None. + + Returns + ------- + str + Escaped text safe for RST. + """ + if not text: + return "" + return text.replace("\\", "\\\\") + + +def escape_markdown(text: str | None) -> str | None: + """Escape special markdown characters in text. + + If the text appears to already contain markdown formatting (bold, italic, + code, links, or headings), it is returned unchanged. Otherwise, pipe + characters are escaped for table compatibility. + + Parameters + ---------- + text : str | None + Text to escape. Can be None. + + Returns + ------- + str | None + Escaped text safe for markdown, or None if input was None. + """ + if not text: + return text + + if any(pattern in text for pattern in ["**", "``", "`", "](", "#"]): + return text + + text = text.replace("|", "\\|") + return text + + +def escape_html(text: str | None) -> str: + """Escape special HTML characters in text. + + Parameters + ---------- + text : str | None + Text to escape. Can be None. + + Returns + ------- + str + Escaped text safe for HTML. + """ + if not text: + return "" + + text = text.replace("&", "&") + text = text.replace("<", "<") + text = text.replace(">", ">") + text = text.replace('"', """) + text = text.replace("'", "'") + return text diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_path_type.py b/.venv/lib/python3.10/site-packages/cyclopts/_path_type.py new file mode 100644 index 0000000000000000000000000000000000000000..1491cf7ad44c1568a39b2135f4b3620ac6f55d40 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_path_type.py @@ -0,0 +1,155 @@ +""":class:`StdioPath` - A Path subclass that treats ``-`` as stdin/stdout. + +Requires Python 3.12+ for proper Path subclassing support. +""" + +import io +import sys +from pathlib import Path +from typing import IO, TYPE_CHECKING + +from cyclopts.parameter import Parameter + +if TYPE_CHECKING: + from collections.abc import Buffer + + +class _NonClosingIOWrapper: + """Wrapper around an IO stream that doesn't close on context exit. + + This is used to wrap stdin/stdout so they can be used as context managers + without being closed when the context exits. + """ + + def __init__(self, stream: IO, detach_on_exit: bool = False): + self._stream = stream + self._detach_on_exit = detach_on_exit + + def __enter__(self): + return self._stream + + def __exit__(self, *args): + # Flush any buffered data (important for TextIOWrapper) + self._stream.flush() + if self._detach_on_exit: + self._stream.detach() # Detach TextIOWrapper without closing underlying buffer + + def __getattr__(self, name): + return getattr(self._stream, name) + + +@Parameter(allow_leading_hyphen=True) +class StdioPath(Path): + """A :class:`~pathlib.Path` subclass that treats ``-`` as stdin/stdout.""" + + STDIO_STRING: str = "-" + """The string that represents stdin/stdout. Override in subclasses for custom behavior.""" + + @property + def is_stdio(self) -> bool: + """Return True if this represents stdin/stdout. + + Override this property in subclasses for custom matching logic + (e.g., matching multiple strings or using pattern matching). + """ + return str(self) == self.STDIO_STRING + + def __repr__(self): + return f"{type(self).__name__}({str(self)!r})" + + def exists(self, *, follow_symlinks: bool = True) -> bool: + """Return True if path exists. Always True for stdio.""" + return True if self.is_stdio else super().exists(follow_symlinks=follow_symlinks) + + def open( # pyright: ignore[reportIncompatibleMethodOverride] + self, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ): + """Open the file or return stdin/stdout. + + For stdio paths, returns a wrapper around the appropriate stream + (stdin for reading, stdout for writing) that doesn't close on context exit. + For regular paths, behaves like the standard Path.open(). + """ + if self.is_stdio: + is_binary = "b" in mode + is_write = "w" in mode or "a" in mode + # Always get the buffer stream + buffer_stream = sys.stdout.buffer if is_write else sys.stdin.buffer + if is_binary: + stream = _NonClosingIOWrapper(buffer_stream) + else: + # For text mode, wrap the binary stream with TextIOWrapper + text_stream = io.TextIOWrapper( + buffer_stream, + encoding=encoding or "utf-8", + errors=errors or "strict", + newline=newline, + ) + stream = _NonClosingIOWrapper(text_stream, detach_on_exit=True) + return stream + return super().open(mode, buffering, encoding, errors, newline) + + def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: + """Read entire contents as text.""" + if self.is_stdio: + wrapper = io.TextIOWrapper( + sys.stdin.buffer, + encoding=encoding or "utf-8", + errors=errors or "strict", + newline=newline, + ) + try: + return wrapper.read() + finally: + wrapper.detach() # Detach without closing stdin.buffer + # newline parameter added in Python 3.13 + if sys.version_info >= (3, 13): + return super().read_text(encoding=encoding, errors=errors, newline=newline) + else: + return super().read_text(encoding=encoding, errors=errors) + + def read_bytes(self) -> bytes: + """Read entire contents as bytes.""" + if self.is_stdio: + return sys.stdin.buffer.read() + return super().read_bytes() + + def write_text( + self, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + """Write text data.""" + if self.is_stdio: + wrapper = io.TextIOWrapper( + sys.stdout.buffer, + encoding=encoding or "utf-8", + errors=errors or "strict", + newline=newline, + ) + try: + wrapper.write(data) + wrapper.flush() + # TextIOWrapper doesn't return bytes written, so calculate from encoded data + # Apply same newline translation that TextIOWrapper does + if newline is None or newline == "": + encoded_data = data + else: + encoded_data = data.replace("\n", newline) + return len(encoded_data.encode(encoding or "utf-8", errors or "strict")) + finally: + wrapper.detach() # Detach without closing stdout.buffer + return super().write_text(data, encoding=encoding, errors=errors, newline=newline) + + def write_bytes(self, data: "Buffer") -> int: + """Write binary data.""" + if self.is_stdio: + return sys.stdout.buffer.write(data) + return super().write_bytes(data) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_result_action.py b/.venv/lib/python3.10/site-packages/cyclopts/_result_action.py new file mode 100644 index 0000000000000000000000000000000000000000..c2570c0032da4224a99fcef6f3c8019ae24ee02d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_result_action.py @@ -0,0 +1,147 @@ +import sys +from collections.abc import Callable, Iterable +from typing import Any, Literal, cast + +from cyclopts.utils import is_iterable + +ResultActionSingle = ( + Literal[ + "return_value", + "call_if_callable", + "print_non_int_return_int_as_exit_code", + "print_str_return_int_as_exit_code", + "print_str_return_zero", + "print_non_none_return_int_as_exit_code", + "print_non_none_return_zero", + "return_int_as_exit_code_else_zero", + "print_non_int_sys_exit", + "sys_exit", + "return_none", + "return_zero", + "print_return_zero", + "sys_exit_zero", + "print_sys_exit_zero", + ] + | Callable[[Any], Any] +) + +ResultAction = ResultActionSingle | Iterable[ResultActionSingle] + + +def handle_result_action( + result: Any, + action: ResultAction, + print_fn: Callable[[Any], None], +) -> Any: + """Handle command result based on result_action. + + When ``action`` is a sequence, actions are applied left-to-right in a pipeline, + where each action receives the result of the previous action. For example, + with ``result_action=[uppercase, add_greeting]``: + + result → uppercase(result) → add_greeting(uppercase(result)) + + Parameters + ---------- + result : Any + The command's return value. + action : ResultAction + The action (or sequence of actions) to take with the result. + If a sequence, actions are chained left-to-right. + print_fn : Callable[[Any], None] + Function to call to print output (e.g., console.print). + + Returns + ------- + Any + Processed result based on action (may call sys.exit() and not return). + """ + if is_iterable(action): + for single_action in cast(Iterable[ResultActionSingle], action): + result = handle_result_action(result, single_action, print_fn) + return result + + if callable(action): + return action(result) + + match action: + case "print_non_int_sys_exit": + if isinstance(result, bool): + sys.exit(0 if result else 1) + elif isinstance(result, int): + sys.exit(result) + elif result is not None: + print_fn(result) + sys.exit(0) + else: + sys.exit(0) + case "return_value": + return result + case "call_if_callable": + if callable(result): + return result() + return result + case "sys_exit": + if isinstance(result, bool): + sys.exit(0 if result else 1) + elif isinstance(result, int): + sys.exit(result) + else: + sys.exit(0) + case "print_non_int_return_int_as_exit_code": + if isinstance(result, bool): + return 0 if result else 1 + elif isinstance(result, int): + return result + elif result is not None: + print_fn(result) + return 0 + else: + return 0 + case "print_str_return_int_as_exit_code": + if isinstance(result, str): + print_fn(result) + return 0 + elif isinstance(result, bool): + return 0 if result else 1 + elif isinstance(result, int): + return result + else: + return 0 + case "print_str_return_zero": + if isinstance(result, str): + print_fn(result) + return 0 + case "print_non_none_return_int_as_exit_code": + if result is not None: + print_fn(result) + if isinstance(result, bool): + return 0 if result else 1 + elif isinstance(result, int): + return result + return 0 + case "print_non_none_return_zero": + if result is not None: + print_fn(result) + return 0 + case "return_int_as_exit_code_else_zero": + if isinstance(result, bool): + return 0 if result else 1 + elif isinstance(result, int): + return result + else: + return 0 + case "return_none": + return None + case "return_zero": + return 0 + case "print_return_zero": + print_fn(result) + return 0 + case "sys_exit_zero": + sys.exit(0) + case "print_sys_exit_zero": + print_fn(result) + sys.exit(0) + case _: + raise ValueError diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_run.py b/.venv/lib/python3.10/site-packages/cyclopts/_run.py new file mode 100644 index 0000000000000000000000000000000000000000..2473f2053ab52ae4ef27e2b81f8162c506e6e5e1 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_run.py @@ -0,0 +1,132 @@ +import inspect +import sys +from collections.abc import Callable, Coroutine +from functools import partial +from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload + +from cyclopts._result_action import ResultAction + +if sys.version_info < (3, 11): # pragma: no cover + from typing_extensions import assert_never +else: # pragma: no cover + from typing import assert_never + +if TYPE_CHECKING: + from cyclopts.core import App + +V = TypeVar("V") + +# App will be lazily imported to avoid circular imports +App = None # type: ignore[assignment] + + +def _run_maybe_async_command( + command: Callable, + bound: inspect.BoundArguments | None = None, + backend: Literal["asyncio", "trio"] = "asyncio", +): + """Run a command, handling both sync and async cases. + + If the command is async, an async context will be created to run it. + + Parameters + ---------- + command : Callable + The command to execute. + bound : inspect.BoundArguments | None + Bound arguments for the command. If None, command is called with no arguments. + backend : Literal["asyncio", "trio"] + The async backend to use if the command is async. + + Returns + ------- + return_value: Any + The value the command function returns. + """ + if not inspect.iscoroutinefunction(command): + if bound is None: + return command() + else: + return command(*bound.args, **bound.kwargs) + + if backend == "asyncio": + import asyncio + + if bound is None: + return asyncio.run(command()) + else: + return asyncio.run(command(*bound.args, **bound.kwargs)) + elif backend == "trio": + import trio + + if bound is None: + return trio.run(command) + else: + return trio.run(partial(command, *bound.args, **bound.kwargs)) + else: # pragma: no cover + assert_never(backend) + + +@overload +def run(callable: Callable[..., Coroutine[None, None, V]], /, *, result_action: Literal["return_value"]) -> V: ... + + +@overload +def run(callable: Callable[..., V], /, *, result_action: Literal["return_value"]) -> V: ... + + +@overload +def run( + callable: Callable[..., Coroutine[None, None, Any]], /, *, result_action: ResultAction | None = None +) -> Any: ... + + +@overload +def run(callable: Callable[..., Any], /, *, result_action: ResultAction | None = None) -> Any: ... + + +def run(callable, /, *, result_action: ResultAction | None = None): + """Run the given callable as a CLI command. + + The callable may also be a coroutine function. + This function is syntax sugar for very simple use cases, and is roughly equivalent to: + + .. code-block:: python + + from cyclopts import App + + app = App() + app.default(callable) + app() + + Parameters + ---------- + callable + The function to execute as a CLI command. + result_action + How to handle the command's return value. If not specified, uses the default + ``"print_non_int_sys_exit"`` which calls :func:`sys.exit` with the appropriate code. + Can be set to ``"return_value"`` to return the result directly for testing/embedding. + + Example usage: + + .. code-block:: python + + import cyclopts + + + def main(name: str, age: int): + print(f"Hello {name}, you are {age} years old.") + + + cyclopts.run(main) + """ + global App + if App is None: + from cyclopts.core import App as _App + + App = _App + + app = App(result_action=result_action) + app.default(callable) + return app() diff --git a/.venv/lib/python3.10/site-packages/cyclopts/_version.py b/.venv/lib/python3.10/site-packages/cyclopts/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..bf9057822eda1ea383f31e9e047cc2f6b731436c --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/_version.py @@ -0,0 +1,24 @@ +# file generated by vcs-versioning +# don't change, don't track in version control +from __future__ import annotations + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +version: str +__version__: str +__version_tuple__: tuple[int | str, ...] +version_tuple: tuple[int | str, ...] +commit_id: str | None +__commit_id__: str | None + +__version__ = version = '4.11.0' +__version_tuple__ = version_tuple = (4, 11, 0) + +__commit_id__ = commit_id = None diff --git a/.venv/lib/python3.10/site-packages/cyclopts/annotations.py b/.venv/lib/python3.10/site-packages/cyclopts/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ad87c7d41c426f0aaad90fcdf86e616128ba46 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/annotations.py @@ -0,0 +1,238 @@ +import inspect +import sys +import typing +from collections.abc import Iterable, Sequence +from enum import Flag +from types import UnionType +from typing import Annotated, Any, Union, get_args, get_origin + +import attrs + +from cyclopts.utils import is_class_and_subclass + +if sys.version_info < (3, 11): # pragma: no cover + from typing_extensions import NotRequired, Required +else: # pragma: no cover + from typing import NotRequired, Required + +if sys.version_info >= (3, 12): # pragma: no cover + from typing import TypeAliasType +else: # pragma: no cover + TypeAliasType = None + +# from types import NoneType is available >=3.10 +NoneType = type(None) +AnnotatedType = type(Annotated[int, 0]) + +ITERABLE_TYPES = { + Iterable, + typing.Sequence, + Sequence, + frozenset, + list, + set, + tuple, +} + + +def is_nonetype(hint): + return hint is NoneType + + +def is_union(type_: type | None) -> bool: + """Checks if a type is a union.""" + # Direct checks are faster than checking if the type is in a set that contains the union-types. + if type_ is Union or type_ is UnionType: + return True + + # The ``get_origin`` call is relatively expensive, so we'll check common types + # that are passed in here to see if we can avoid calling ``get_origin``. + if type_ is str or type_ is int or type_ is float or type_ is bool or is_annotated(type_): + return False + origin = get_origin(type_) + return origin is Union or origin is UnionType + + +def is_pydantic(hint) -> bool: + return hasattr(hint, "__pydantic_core_schema__") + + +def is_pydantic_secret(hint) -> bool: + """Check if a type is a Pydantic secret type (SecretStr, SecretBytes, Secret, etc.).""" + return ( + hasattr(hint, "__module__") + and hint.__module__ == "pydantic.types" + and hasattr(hint, "get_secret_value") + and callable(getattr(hint, "get_secret_value", None)) + ) + + +def is_dataclass(hint) -> bool: + return hasattr(hint, "__dataclass_fields__") + + +def is_namedtuple(hint) -> bool: + return is_class_and_subclass(hint, tuple) and hasattr(hint, "_fields") + + +def is_attrs(hint) -> bool: + return attrs.has(hint) + + +def is_enum_flag(hint) -> bool: + """Check if a type hint is an enum.Flag subclass.""" + return is_class_and_subclass(hint, Flag) + + +def is_annotated(hint) -> bool: + return type(hint) is AnnotatedType + + +def is_iterable_type(hint) -> bool: + """Check if a type hint is a collection/iterable type (list, set, tuple, etc.). + + Handles Annotated, Optional, TypeAlias, and NewType wrappers. + """ + hint = resolve(hint) + origin = get_origin(hint) + return is_class_and_subclass(origin, tuple(ITERABLE_TYPES)) + + +def contains_hint(hint, target_type) -> bool: + """Indicates if ``target_type`` is in a possibly annotated/unioned ``hint``. + + E.g. ``contains_hint(Union[int, str], str) == True`` + """ + hint = resolve(hint) + if is_union(hint): + return any(contains_hint(x, target_type) for x in get_args(hint)) + else: + return is_class_and_subclass(hint, target_type) + + +def is_typeddict(hint) -> bool: + """Determine if a type annotation is a TypedDict. + + This is surprisingly hard! Modified from Beartype's implementation: + + https://github.com/beartype/beartype/blob/main/beartype/_util/hint/pep/proposal/utilpep589.py + """ + hint = resolve(hint) + if is_union(hint): + return any(is_typeddict(x) for x in get_args(hint)) + + if not is_class_and_subclass(hint, dict): + return False + + return ( + hasattr(hint, "__annotations__") + and hasattr(hint, "__total__") + and hasattr(hint, "__required_keys__") + and hasattr(hint, "__optional_keys__") + ) + + +def resolve( + type_: Any, +) -> type: + """Perform all simplifying resolutions.""" + if type_ is inspect.Parameter.empty: + return str + + type_prev = None + while type_ != type_prev: + type_prev = type_ + type_ = resolve_type_alias(type_) + type_ = resolve_annotated(type_) + type_ = resolve_optional(type_) + type_ = resolve_required(type_) + type_ = resolve_new_type(type_) + return type_ + + +def resolve_optional(type_: Any) -> Any: + """Only resolves Union's of None + one other type (i.e. Optional).""" + type_ = resolve_type_alias(type_) + # Python will automatically flatten out nested unions when possible. + # So we don't need to loop over resolution. + if not is_union(type_): + return type_ + + non_none_types = [t for t in get_args(type_) if t is not NoneType] + if not non_none_types: # pragma: no cover + # This should never happen; python simplifies: + # ``Union[None, None] -> NoneType`` + raise ValueError("Union type cannot be all NoneType") + elif len(non_none_types) == 1: + type_ = non_none_types[0] + elif len(non_none_types) > 1: + return Union[tuple(resolve_optional(x) for x in non_none_types)] # pyright: ignore # noqa: UP007 + else: + raise NotImplementedError + + return type_ + + +def resolve_annotated(type_: Any) -> type: + type_ = resolve_type_alias(type_) + if is_annotated(type_): + type_ = get_args(type_)[0] + return type_ + + +def get_annotated_discriminator(annotation) -> Any: + """Return the ``discriminator`` metadata from an ``Annotated[...]`` hint, else ``None``. + + Only inspects ``Annotated`` hints — for other parameterized types (``list[X]``, + ``dict[K, V]``, etc.) this returns ``None`` so that an incidental + ``.discriminator`` attribute on a type parameter cannot spuriously match. + """ + if not is_annotated(annotation): + return None + for meta in get_args(annotation)[1:]: + try: + return meta.discriminator + except AttributeError: + pass + return None + + +def resolve_required(type_: Any) -> type: + if get_origin(type_) in (Required, NotRequired): + type_ = get_args(type_)[0] + return type_ + + +def resolve_new_type(type_: Any) -> type: + try: + return resolve_new_type(type_.__supertype__) + except AttributeError: + return type_ + + +def resolve_type_alias(type_: Any) -> Any: + """Resolve TypeAliasType (Python 3.12+ 'type' statement) to its underlying type.""" + if TypeAliasType is not None and isinstance(type_, TypeAliasType): + return type_.__value__ + return type_ + + +def get_hint_name(hint) -> str: + if isinstance(hint, str): + return hint + if is_nonetype(hint): + return "None" + if hint is Any: + return "Any" + if is_union(hint): + return "|".join(get_hint_name(arg) for arg in get_args(hint)) + if origin := get_origin(hint): + out = get_hint_name(origin) + if args := get_args(hint): + out += "[" + ", ".join(get_hint_name(arg) for arg in args) + "]" + return out + if hasattr(hint, "__name__"): + return hint.__name__ + if getattr(hint, "_name", None) is not None: + return hint._name + return str(hint) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/app_stack.py b/.venv/lib/python3.10/site-packages/cyclopts/app_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..cabccd4a4c87f2cc4b628ff91846177c7fe18d7a --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/app_stack.py @@ -0,0 +1,173 @@ +from collections.abc import Sequence +from contextlib import contextmanager +from itertools import chain +from typing import TYPE_CHECKING, Any, TypeVar, cast, overload + +from cyclopts.group_extractors import inverse_groups_from_app +from cyclopts.parameter import Parameter + +if TYPE_CHECKING: + from cyclopts.core import App + + +V = TypeVar("V") + + +class AppStack: + def __init__(self, app): + # the ``stack`` is guaranteed to have the self-referencing app at the top of the stack. + self.stack: list[list[App]] = [[app]] + # Stack of overrides passed to parse_args/call that should be propagated + self.overrides_stack: list[dict[str, Any]] = [{}] + + @contextmanager + def __call__(self, apps: Sequence["App"] | Sequence[str], overrides: dict[str, Any] | None = None): + # set `overrides` default-values with current overrides so that they properly propagate down the call-stack. + overrides = self.overrides | (overrides or {}) + + self.overrides_stack.append(overrides or {}) + + if not apps: + try: + yield + finally: + self.overrides_stack.pop() + return + + # Convert strings to Apps if needed + if isinstance(apps[0], str): + str_apps = cast(Sequence[str], apps) + _, apps_tuple, _ = self.stack[0][0].parse_commands(str_apps, include_parent_meta=True) + resolved_apps: list[App] = list(apps_tuple) + else: + resolved_apps = cast(list["App"], list(apps)) + del apps + + if not resolved_apps: + try: + yield + finally: + self.overrides_stack.pop() + return + + so_far = [] + app_ids = {id(app) for app in resolved_apps} + for app in resolved_apps: + if app._meta_parent is None: + # Do not include the prior meta-app. + while so_far and so_far[-1]._meta_parent is not None: + so_far.pop() + + so_far.append(app) + app.app_stack.stack.append(so_far.copy()) + # Also push the overrides onto this app's stack + app.app_stack.overrides_stack.append(overrides or {}) + + # Also traverse the app's meta app + meta_app = app + while (meta_app := meta_app._meta) is not None: + if id(meta_app) in app_ids: + # It will be handled conventionally + continue + meta_subapps = so_far.copy() + meta_subapps.append(meta_app) + meta_app.app_stack.stack.append(meta_subapps) + # Also push the overrides onto the meta app's stack + meta_app.app_stack.overrides_stack.append(overrides or {}) + try: + yield + finally: + for app in resolved_apps: + app.app_stack.stack.pop() + app.app_stack.overrides_stack.pop() + # Also pop from meta apps + meta_app = app + while (meta_app := meta_app._meta) is not None: + if id(meta_app) in app_ids: + continue + meta_app.app_stack.stack.pop() + meta_app.app_stack.overrides_stack.pop() + # Pop overrides from stack + self.overrides_stack.pop() + + @property + def overrides(self) -> dict: + out = {} + for overrides_frame in reversed(self.overrides_stack): + for key, value in overrides_frame.items(): + if value is not None: + out.setdefault(key, value) + return out + + @property + def default_parameter(self) -> Parameter: + """default_parameter has special resolution since it needs to include the command groups in the derivation.""" + cparams = [] + for child_app in chain.from_iterable(self.stack): + if child_app._meta_parent: + continue + cparams.extend([group.default_parameter for group in child_app.app_stack.command_groups]) + cparams.append(child_app.default_parameter) + + return Parameter.combine(*cparams) + + @property + def current_frame(self) -> list["App"]: + if not self.stack: + raise ValueError + + return self.stack[-1] + + @overload + def resolve(self, attribute: str) -> Any: ... + + @overload + def resolve(self, attribute: str, override: V) -> V: ... + + @overload + def resolve(self, attribute: str, override: V | None, fallback: V) -> V: ... + + @overload + def resolve(self, attribute: str, override: V | None = None, *, fallback: V) -> V: ... + + def resolve(self, attribute: str, override: V | None = None, fallback: V | None = None) -> V | None: + """Resolve an attribute from the App hierarchy.""" + if override is not None: + return override + + # Check if we have a stored override from parent invocations (most recent first) + for overrides_frame in reversed(self.overrides_stack): + if attribute in overrides_frame: + value = overrides_frame[attribute] + if value is not None: + return value + + # `reversed` so that "closer" apps have higher priority. + for app in reversed(list(chain.from_iterable(self.stack))): + result = getattr(app, attribute) + if result is not None: + return result + + # Check parenting meta app(s) + meta_app = app + while (meta_app := meta_app._meta_parent) is not None: + result = getattr(meta_app, attribute) + if result is not None: + return result + + return fallback + + @property + def command_groups(self) -> list: + command_app = self.current_frame[-1] + try: + current_app: App | None = self.current_frame[-2] + except IndexError: + current_app = None + + while current_app is not None: + try: + return next(x for x in inverse_groups_from_app(current_app) if x[0] is command_app)[1] + except StopIteration: + current_app = current_app._meta_parent + return [] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/argument/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/argument/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d9b6a7cdfc37ab7b89adcb25edcbd7bded63e84b --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/argument/__init__.py @@ -0,0 +1,21 @@ +"""Argument and ArgumentCollection classes for CLI parsing.""" + +from cyclopts.token import Token + +from ._argument import Argument +from ._collection import ( + ArgumentCollection, + _resolve_groups_from_callable, + update_argument_collection, +) +from .utils import get_choices_from_hint, resolve_parameter_name + +__all__ = [ + "Argument", + "ArgumentCollection", + "Token", + "_resolve_groups_from_callable", + "get_choices_from_hint", + "resolve_parameter_name", + "update_argument_collection", +] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/argument/_argument.py b/.venv/lib/python3.10/site-packages/cyclopts/argument/_argument.py new file mode 100644 index 0000000000000000000000000000000000000000..587ffe0f3c8b2f6bb0c942651af94ecf149c6059 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/argument/_argument.py @@ -0,0 +1,1178 @@ +"""Argument class and related functionality.""" + +import inspect +import json +import operator +import re +import sys +from collections.abc import Callable, Sequence +from contextlib import suppress +from functools import partial, reduce +from typing import TYPE_CHECKING, Any, get_args, get_origin + +from attrs import define, field + +from cyclopts._convert import ( + _validate_json_extra_keys, + convert, + instantiate_from_dict, + token_count, +) +from cyclopts.annotations import ( + ITERABLE_TYPES, + contains_hint, + get_annotated_discriminator, + is_attrs, + is_dataclass, + is_enum_flag, + is_namedtuple, + is_nonetype, + is_pydantic, + is_typeddict, + is_union, + resolve, + resolve_annotated, + resolve_optional, +) +from cyclopts.exceptions import ( + CoercionError, + CycloptsError, + MissingArgumentError, + MixedArgumentError, + RepeatArgumentError, + ValidationError, +) +from cyclopts.field_info import ( + FieldInfo, + _attrs_field_infos, + _generic_class_field_infos, + _pydantic_field_infos, + _typed_dict_field_infos, + get_field_infos, + signature_parameters, +) +from cyclopts.parameter import ITERATIVE_BOOL_IMPLICIT_VALUE, Parameter +from cyclopts.token import Token +from cyclopts.utils import UNSET, grouper, is_builtin, parse_version + +from .utils import ( + enum_flag_from_dict, + get_choices_from_hint, + missing_keys_factory, + startswith, +) + +if TYPE_CHECKING: + from cyclopts.argument._collection import ArgumentCollection + + +@define(kw_only=True) +class Argument: + """Encapsulates functionality and additional contextual information for parsing a parameter. + + An argument is defined as anything that would have its own entry in the help page. + """ + + tokens: list[Token] = field(factory=list) + """ + List of :class:`.Token` parsed from various sources. + Do not directly mutate; see :meth:`append`. + """ + + field_info: FieldInfo = field(factory=FieldInfo) + """ + Additional information about the parameter from surrounding python syntax. + """ + + parameter: Parameter = field(factory=Parameter) + """ + Fully resolved user-provided :class:`.Parameter`. + """ + + hint: Any = field(default=str, converter=resolve) + """ + The type hint for this argument; may be different from :attr:`.FieldInfo.annotation`. + """ + + index: int | None = field(default=None) + """ + Associated python positional index for argument. + If ``None``, then cannot be assigned positionally. + """ + + keys: tuple[str, ...] = field(default=()) + """ + **Python** keys that lead to this leaf. + + ``self.parameter.name`` and ``self.keys`` can naively disagree! + For example, a ``self.parameter.name="--foo.bar.baz"`` could be aliased to "--fizz". + The resulting ``self.keys`` would be ``("bar", "baz")``. + + This is populated based on type-hints and class-structure, not ``Parameter.name``. + + .. code-block:: python + + from cyclopts import App, Parameter + from dataclasses import dataclass + from typing import Annotated + + app = App() + + + @dataclass + class User: + id: int + name: Annotated[str, Parameter(name="--fullname")] + + + @app.default + def main(user: User): + pass + + + for argument in app.assemble_argument_collection(): + print(f"name: {argument.name:16} hint: {str(argument.hint):16} keys: {str(argument.keys)}") + + .. code-block:: bash + + $ my-script + name: --user.id hint: keys: ('id',) + name: --fullname hint: keys: ('name',) + """ + + _value: Any = field(alias="value", default=UNSET) + """ + Converted value from last :meth:`convert` call. + This value may be stale if fields have changed since last :meth:`convert` call. + :class:`.UNSET` if :meth:`convert` has not yet been called with tokens. + """ + + _accepts_keywords: bool = field(default=False, init=False, repr=False) + + _default: Any = field(default=None, init=False, repr=False) + _lookup: dict[str, FieldInfo] = field(factory=dict, init=False, repr=False) + + children: "ArgumentCollection" = field(init=False, repr=False) + """ + Collection of other :class:`Argument` that eventually culminate into the python variable represented by :attr:`field_info`. + """ + + _marked_converted: bool = field(default=False, init=False, repr=False) + _mark_converted_override: bool = field(default=False, init=False, repr=False) + + _missing_keys_checker: Callable | None = field(default=None, init=False, repr=False) + + _internal_converter: Callable | None = field(default=None, init=False, repr=False) + + _enum_flag_type: Any | None = field(default=None, init=False, repr=False) + + def __attrs_post_init__(self): + from cyclopts.argument._collection import ArgumentCollection + + self.children = ArgumentCollection() + + hint = resolve(self.hint) + hints = get_args(hint) if is_union(hint) else (hint,) + + if self.parameter.count: + # Perform type-annotation validation. + resolved_hint = resolve_optional(hint) + # Technically, bool is a subclass of int, so we need to explicitly check. + if resolved_hint is bool or not ( + resolved_hint is int or (isinstance(resolved_hint, type) and issubclass(resolved_hint, int)) + ): + raise ValueError( + f"Parameter(count=True) requires an int type hint, got {self.hint}. " + f"Use 'Annotated[int, Parameter(count=True)]' for counting flags." + ) + + if self.parameter.requires_equals and self.parameter.consume_multiple: + raise ValueError( + "Parameter(requires_equals=True) and Parameter(consume_multiple=...) cannot be used together. " + "requires_equals enforces '--option=value' syntax, which is incompatible with " + "consume_multiple's space-separated value consumption." + ) + + if not self.parse: + # Validate that non-parsed parameters are keyword-only or have defaults + is_keyword_only = self.field_info.kind is self.field_info.KEYWORD_ONLY + has_default = self.field_info.default is not self.field_info.empty + if not (is_keyword_only or has_default): + raise ValueError( + f"Non-parsed parameter '{self.field_info.name}' must be a KEYWORD_ONLY function parameter " + "or have a default value." + ) + return + + if self.parameter.accepts_keys is False: + return + + for hint in hints: + origin = get_origin(hint) + hint_origin = {hint, origin} + + field_infos = get_field_infos(hint) + if dict in hint_origin: + self._accepts_keywords = True + key_type, val_type = str, str + args = get_args(hint) + with suppress(IndexError): + key_type = args[0] + val_type = args[1] + if key_type is not str: + raise TypeError('Dictionary type annotations must have "str" keys.') + self._default = val_type + elif is_typeddict(hint): + self._missing_keys_checker = missing_keys_factory(_typed_dict_field_infos) + self._accepts_keywords = True + self._update_lookup(field_infos) + elif is_dataclass(hint): + self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos) + self._accepts_keywords = True + self._update_lookup(field_infos) + elif is_namedtuple(hint): + self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos) + self._accepts_keywords = True + if not hasattr(hint, "__annotations__"): + raise ValueError("Cyclopts cannot handle collections.namedtuple without type annotations.") + self._update_lookup(field_infos) + elif is_attrs(hint): + self._missing_keys_checker = missing_keys_factory(_attrs_field_infos) + self._accepts_keywords = True + self._update_lookup(field_infos) + elif is_pydantic(hint): + self._missing_keys_checker = missing_keys_factory(_pydantic_field_infos) + self._accepts_keywords = True + self._update_lookup(field_infos) + elif is_enum_flag(hint): + self._enum_flag_type = hint + self._accepts_keywords = True + self._update_lookup(field_infos) + elif not is_builtin(hint) and field_infos: + self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos) + self._accepts_keywords = True + self._update_lookup(field_infos) + elif self.parameter.accepts_keys is None: + continue + + if self.parameter.accepts_keys is None: + continue + + self._accepts_keywords = True + self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos) + for i, field_info in enumerate(signature_parameters(hint.__init__).values()): + if i == 0 and field_info.name == "self": + continue + if field_info.kind is field_info.VAR_KEYWORD: + self._default = field_info.annotation + else: + self._update_lookup({field_info.name: field_info}) + + def _update_lookup(self, field_infos: dict[str, FieldInfo]): + from typing import Literal + + discriminator = get_annotated_discriminator(self.field_info.annotation) + + for key, field_info in field_infos.items(): + if existing_field_info := self._lookup.get(key): + if existing_field_info == field_info: + pass + elif discriminator and discriminator in field_info.names and discriminator in existing_field_info.names: + existing_field_info.annotation = Literal[existing_field_info.annotation, field_info.annotation] + existing_field_info.default = FieldInfo.empty + else: + raise NotImplementedError + else: + self._lookup[key] = field_info + + @property + def value(self): + """Converted value from last :meth:`convert` call. + + This value may be stale if fields have changed since last :meth:`convert` call. + :class:`.UNSET` if :meth:`convert` has not yet been called with tokens. + """ + return self._value + + @value.setter + def value(self, val): + if self._marked: + self._mark_converted_override = True + self._marked = True + self._value = val + + @property + def _marked(self): + """If ``True``, then this node in the tree has already been converted and ``value`` has been populated.""" + return self._marked_converted | self._mark_converted_override + + @_marked.setter + def _marked(self, value: bool): + self._marked_converted = value + + @property + def _accepts_arbitrary_keywords(self) -> bool: + args = get_args(self.hint) if is_union(self.hint) else (self.hint,) + return any(dict in (arg, get_origin(arg)) for arg in args) + + @property + def show_default(self) -> bool | Callable[[Any], str]: + """Show the default value on the help page.""" + if self.required: + return False + elif self.parameter.show_default is None: + return self.field_info.default not in (None, self.field_info.empty) + elif (self.field_info.default is self.field_info.empty) or not self.parameter.show_default: + return False + else: + return self.parameter.show_default + + @property + def _use_pydantic_type_adapter(self) -> bool: + return bool( + is_pydantic(self.hint) + or ( + is_union(self.hint) + and ( + any(is_pydantic(x) for x in get_args(self.hint)) + or get_annotated_discriminator(self.field_info.annotation) + ) + ) + ) + + def _type_hint_for_key(self, key: str): + try: + return self._lookup[key].annotation + except KeyError: + if self._default is None: + raise + return self._default + + def _should_attempt_json_dict(self, tokens: Sequence[Token | str] | None = None) -> bool: + """When parsing, should attempt to parse the token(s) as json dict data.""" + if tokens is None: + tokens = self.tokens + if not tokens: + return False + value = tokens[0].value if isinstance(tokens[0], Token) else tokens[0] + if not value.strip().startswith("{"): + return False + + if self._accepts_keywords: + if self.parameter.json_dict is not None: + return self.parameter.json_dict + if contains_hint(self.field_info.annotation, str): + return False + return True + + hint = resolve(self.hint) + origin = get_origin(hint) + if origin in ITERABLE_TYPES: + args = get_args(hint) + if args and args[0] is not str: + return True + + return False + + def _should_attempt_json_list( + self, tokens: Sequence[Token | str] | Token | str | None = None, keys: tuple[str, ...] = () + ) -> bool: + """When parsing, should attempt to parse the token(s) as json list data.""" + if tokens is None: + tokens = self.tokens + if not tokens: + return False + _, consume_all = self.token_count(keys) + if not consume_all: + return False + if isinstance(tokens, Token): + value = tokens.value + elif isinstance(tokens, str): + value = tokens + else: + value = tokens[0].value if isinstance(tokens[0], Token) else tokens[0] + if not value.strip().startswith("["): + return False + if self.parameter.json_list is not None: + return self.parameter.json_list + for arg in get_args(self.field_info.annotation) or (str,): + if contains_hint(arg, str): + return False + return True + + def match( + self, + term: str | int, + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> tuple[tuple[str, ...], Any]: + """Match a name search-term, or a positional integer index. + + Raises + ------ + ValueError + If no match is found. + + Returns + ------- + tuple[str, ...] + Leftover keys after matching to this argument. + Used if this argument accepts_arbitrary_keywords. + Any + Implicit value. + :obj:`~.UNSET` if no implicit value is applicable. + """ + if not self.parse: + raise ValueError + return ( + self._match_index(term) + if isinstance(term, int) + else self._match_name(term, transform=transform, delimiter=delimiter) + ) + + def _normalize_trailing_keys(self, trailing: tuple[str, ...]) -> tuple[str, ...]: + """Map kebab-case segments back to their canonical Python field names. + + Walks the type hint segment-by-segment: + + * Dynamic ``dict`` keys pass through unchanged (advance to the value type). + * Segments addressing a structured type (pydantic / dataclass / attrs / + TypedDict / NamedTuple) are looked up in a ``{name_transform(name): name}`` + map built from the type's field_infos; on hit, the segment is replaced + with the canonical name and the walk advances to that field's annotation. + * On miss or when the hint is unwalkable (plain scalar, unresolved forward + ref, etc.) remaining segments pass through unchanged — this preserves the + existing raw-snake_case behavior as a backward-compat fallback. + """ + name_transform = self.parameter.name_transform + if name_transform is None or not trailing: + return trailing + + # Seed from ``self.hint`` (not ``field_info.annotation``): for + # ``**kwargs: SubConfig``, the annotation is ``SubConfig`` but the hint + # is ``dict[str, SubConfig]`` — we need the wrapped form so the first + # trailing segment is routed as a dict key rather than a field name. + hint = resolve(self.hint) + out: list[str] = [] + i = 0 + while i < len(trailing): + segment = trailing[i] + hint = resolve_optional(hint) + + if get_origin(hint) is dict: + out.append(segment) + args = get_args(hint) + hint = args[1] if len(args) > 1 else str + i += 1 + continue + + field_infos = {} + try: + field_infos = get_field_infos(hint) + except Exception: + pass + if not field_infos: + out.extend(trailing[i:]) + break + + # Build a kebab→canonical map from ``fi.names`` only. Cyclopts's + # field_info extractors populate ``names`` with exactly the names + # the underlying library accepts (e.g. pydantic omits the python + # name when ``populate_by_name=False``); trust that. + name_map: dict[str, tuple[str, Any]] = {} + for canonical_name, fi in field_infos.items(): + for alias in fi.names: + name_map.setdefault(name_transform(alias), (canonical_name, fi.annotation)) + + match = name_map.get(segment) + if match is None: + out.extend(trailing[i:]) + break + canonical_name, next_hint = match + out.append(canonical_name) + hint = resolve(next_hint) + i += 1 + + return tuple(out) + + def _match_name( + self, + term: str, + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> tuple[tuple[str, ...], Any]: + """Check how well this argument matches a token keyword identifier. + + Parameters + ---------- + term: str + Something like "--foo" + transform: Callable + Function that converts the cyclopts Parameter name(s) into + something that should be compared against ``term``. + + Raises + ------ + ValueError + If no match found. + + Returns + ------- + tuple[str, ...] + Leftover keys after matching to this argument. + Used if this argument accepts_arbitrary_keywords. + Any + Implicit value. + """ + if self.field_info.kind is self.field_info.VAR_KEYWORD: + return self._normalize_trailing_keys(tuple(term.lstrip("-").split(delimiter))), UNSET + + trailing = term + implicit_value = UNSET + + assert self.parameter.name + for name in self.parameter.name: + if transform: + name = transform(name) + if startswith(term, name): + trailing = term[len(name) :] + implicit_value = True if self.hint is bool or self.hint in ITERATIVE_BOOL_IMPLICIT_VALUE else UNSET + if trailing: + if trailing[0] == delimiter: + trailing = trailing[1:] + break + else: + return (), implicit_value + else: + hint = resolve_annotated(self.field_info.annotation) + if is_union(hint): + hints = get_args(hint) + else: + hints = (hint,) + for hint in hints: + hint = resolve_annotated(hint) + double_break = False + for name in self.parameter.get_negatives(hint): + if transform: + name = transform(name) + if startswith(term, name): + trailing = term[len(name) :] + if hint in ITERATIVE_BOOL_IMPLICIT_VALUE: + implicit_value = False + elif is_nonetype(hint) or hint is None: + implicit_value = None + else: + hint = resolve_optional(hint) + implicit_value = (get_origin(hint) or hint)() + if trailing: + if trailing[0] == delimiter: + trailing = trailing[1:] + double_break = True + break + else: + return (), implicit_value + if double_break: + break + else: + raise ValueError + + if not self._accepts_arbitrary_keywords: + raise ValueError + + return self._normalize_trailing_keys(tuple(trailing.split(delimiter))), implicit_value + + def _match_index(self, index: int) -> tuple[tuple[str, ...], Any]: + if self.index is None: + raise ValueError + elif self.field_info.kind is self.field_info.VAR_POSITIONAL: + if index < self.index: + raise ValueError + elif index != self.index: + raise ValueError + return (), UNSET + + def append(self, token: Token): + """Safely add a :class:`Token`.""" + if not self.parse: + raise ValueError + + if any(x.address == token.address for x in self.tokens): + if self.parameter.allow_repeating is False: + raise RepeatArgumentError(token=token) + _, consume_all = self.token_count(token.keys) + if self.parameter.allow_repeating is True: + if not consume_all: + # "last wins" for scalar types — remove old tokens with same address + self.tokens = [x for x in self.tokens if x.address != token.address] + elif not consume_all and not self.parameter.count: + raise RepeatArgumentError(token=token) + + if self.tokens: + if bool(token.keys) ^ any(x.keys for x in self.tokens): + raise MixedArgumentError(argument=self) + self.tokens.append(token) + + @property + def has_tokens(self) -> bool: + """This argument, or a child argument, has at least 1 parsed token.""" # noqa: D404 + return bool(self.tokens) or any(x.has_tokens for x in self.children) + + @property + def children_recursive(self) -> "ArgumentCollection": + from cyclopts.argument._collection import ArgumentCollection + + out = ArgumentCollection() + for child in self.children: + out.append(child) + out.extend(child.children_recursive) + return out + + def _convert_pydantic(self): + if self.has_tokens: + import pydantic + + unstructured_data = self._json() + try: + return pydantic.TypeAdapter(self.field_info.annotation).validate_python(unstructured_data) + except pydantic.ValidationError as e: + self._handle_pydantic_validation_error(e) + else: + return UNSET + + def _convert(self, converter: Callable | None = None): + from cyclopts.argument._collection import update_argument_collection + + if self.parameter.converter: + # Resolve string converters to methods on the type + if isinstance(self.parameter.converter, str): + converter = getattr(self.hint, self.parameter.converter) + else: + converter = self.parameter.converter + elif converter is None: + converter = partial(convert, name_transform=self.parameter.name_transform) + + assert converter is not None # Ensure converter is set at this point + + def safe_converter(hint, tokens): + if isinstance(tokens, dict): + try: + return converter(hint, tokens) # pyright: ignore + except (AssertionError, ValueError, TypeError) as e: + raise CoercionError(msg=e.args[0] if e.args else None, argument=self, target_type=hint) from e + else: + try: + # Detect bound methods (classmethods/instance methods) + if inspect.ismethod(converter): + # Call with just tokens - cls/self already bound + return converter(tokens) # pyright: ignore[reportCallIssue] + else: + # Regular function - pass type and tokens + return converter(hint, tokens) # pyright: ignore[reportCallIssue] + except (AssertionError, ValueError, TypeError) as e: + token = tokens[0] if len(tokens) == 1 else None + raise CoercionError( + msg=e.args[0] if e.args else None, argument=self, target_type=hint, token=token + ) from e + + if not self.parse: + out = UNSET + elif self.parameter.count: + out = sum(token.implicit_value for token in self.tokens if token.implicit_value is not UNSET) + elif not self.children: + positional: list[Token] = [] + keyword = {} + + def expand_tokens(tokens): + for token in tokens: + if self._should_attempt_json_list(token): + try: + parsed_json = json.loads(token.value) + except json.JSONDecodeError as e: + raise CoercionError(token=token, target_type=self.hint) from e + + if not isinstance(parsed_json, list): + raise CoercionError(token=token, target_type=self.hint) + + if not parsed_json: + yield token.evolve(value="", implicit_value=[]) + else: + for element in parsed_json: + if element is None: + yield token.evolve(value="", implicit_value=element) + elif isinstance(element, dict): + yield token.evolve(value=json.dumps(element)) + else: + yield token.evolve(value=str(element)) + else: + yield token + + expanded_tokens = list(expand_tokens(self.tokens)) + for token in expanded_tokens: + resolved_hint = resolve_optional(self.hint) + if token.implicit_value is not UNSET and isinstance( + token.implicit_value, get_origin(resolved_hint) or resolved_hint + ): + assert len(expanded_tokens) == 1 + return token.implicit_value + + if token.keys: + lookup = keyword + for key in token.keys[:-1]: + lookup = lookup.setdefault(key, {}) + lookup.setdefault(token.keys[-1], []).append(token) + else: + positional.append(token) + + if positional and keyword: # pragma: no cover + raise MixedArgumentError(argument=self) + + if positional: + if self.field_info and self.field_info.kind is self.field_info.VAR_POSITIONAL: + hint = get_args(self.hint)[0] + tokens_per_element, _ = self.token_count() + out = tuple(safe_converter(hint, values) for values in grouper(positional, tokens_per_element)) + else: + out = safe_converter(self.hint, tuple(positional)) + elif keyword: + if self.field_info and self.field_info.kind is self.field_info.VAR_KEYWORD and not self.keys: + out = {key: safe_converter(get_args(self.hint)[1], value) for key, value in keyword.items()} + else: + out = safe_converter(self.hint, keyword) + elif self.required: + raise MissingArgumentError(argument=self) + else: + return UNSET + else: + data = {} + out = UNSET + + if self._enum_flag_type: + out = self._enum_flag_type(0) + + if self._enum_flag_type and self.tokens: + converted_flags = safe_converter(self._enum_flag_type, self.tokens) + out |= reduce(operator.or_, converted_flags) if isinstance(converted_flags, list) else converted_flags + + if self._should_attempt_json_dict(): + while self.tokens: + token = self.tokens.pop(0) + try: + parsed_json = json.loads(token.value) + except json.JSONDecodeError as e: + raise CoercionError(token=token, target_type=self.hint) from e + _validate_json_extra_keys(parsed_json, self.hint, token) + update_argument_collection( + {self.name.lstrip("-"): parsed_json}, + token.source, + self.children_recursive, + root_keys=(), + allow_unknown=False, + ) + + if self._use_pydantic_type_adapter: + return self._convert_pydantic() + + if self.tokens and not self._enum_flag_type: + positional_tokens = [token for token in self.tokens if not token.keys] + if positional_tokens: + return safe_converter(self.hint, tuple(positional_tokens)) + + for child in self.children: + assert len(child.keys) == (len(self.keys) + 1) + if child.has_tokens: + data[child.keys[-1]] = child.convert_and_validate(converter=converter) + elif child.required: + obj = data + for k in child.keys: + try: + obj = obj[k] + except Exception: + raise MissingArgumentError(argument=child) from None + child._marked = True + + self._run_missing_keys_checker(data) + + if self._enum_flag_type: + out |= enum_flag_from_dict(self._enum_flag_type, data, self.parameter.name_transform) + if not out: + out = UNSET + elif data: + out = instantiate_from_dict(self.hint, data) + elif self.required: + raise MissingArgumentError(argument=self) # pragma: no cover + else: + out = UNSET + + return out + + def convert(self, converter: Callable | None = None): + """Converts :attr:`tokens` into :attr:`value`. + + Parameters + ---------- + converter: Callable | None + Converter function to use. Overrides ``self.parameter.converter`` + + Returns + ------- + Any + The converted data. Same as :attr:`value`. + """ + if not self._marked: + try: + self.value = self._convert(converter=converter) + except CoercionError as e: + if e.argument is None: + e.argument = self + if e.target_type is None: + e.target_type = self.hint + raise + except CycloptsError as e: + if e.argument is None: + e.argument = self + raise + + return self.value + + def validate(self, value): + """Validates provided value. + + Parameters + ---------- + value: + Value to validate. + + Returns + ------- + Any + The converted data. Same as :attr:`value`. + """ + assert isinstance(self.parameter.validator, tuple) + + # Only use pydantic validation if pydantic v2+ is available. + # Pydantic v1 has an incompatible API (e.g. no TypeAdapter). + if "pydantic" in sys.modules: + import pydantic + + pydantic_version = parse_version(pydantic.__version__) + if pydantic_version < (2,): + pydantic = None + else: + pydantic = None + + def validate_pydantic(hint, val): + if not pydantic: + return + if self._use_pydantic_type_adapter: + return + + try: + pydantic.TypeAdapter(hint).validate_python(val) + except pydantic.ValidationError as e: + self._handle_pydantic_validation_error(e) + except pydantic.PydanticUserError: + pass + + try: + if not self.keys and self.field_info and self.field_info.kind is self.field_info.VAR_KEYWORD: + hint = get_args(self.hint)[1] + for validator in self.parameter.validator: + for val in value.values(): + validator(hint, val) + validate_pydantic(dict[str, self.field_info.annotation], value) + elif self.field_info and self.field_info.kind is self.field_info.VAR_POSITIONAL: + hint = get_args(self.hint)[0] + for validator in self.parameter.validator: + for val in value: + validator(hint, val) + validate_pydantic(tuple[self.field_info.annotation, ...], value) + else: + for validator in self.parameter.validator: + validator(self.hint, value) + validate_pydantic(self.field_info.annotation, value) + except (AssertionError, ValueError, TypeError) as e: + raise ValidationError(exception_message=e.args[0] if e.args else "", argument=self) from e + + def convert_and_validate(self, converter: Callable | None = None): + """Converts and validates :attr:`tokens` into :attr:`value`. + + Parameters + ---------- + converter: Callable | None + Converter function to use. Overrides ``self.parameter.converter`` + + Returns + ------- + Any + The converted data. Same as :attr:`value`. + """ + val = self.convert(converter=converter) + if val is not UNSET: + self.validate(val) + elif self.field_info.default is not FieldInfo.empty: + self.validate(self.field_info.default) + return val + + def token_count(self, keys: tuple[str, ...] = ()): + """The number of string tokens this argument consumes. + + Parameters + ---------- + keys: tuple[str, ...] + The **python** keys into this argument. + If provided, returns the number of string tokens that specific + data type within the argument consumes. + + Returns + ------- + int + Number of string tokens to create 1 element. + consume_all: bool + :obj:`True` if this data type is iterable. + """ + if self.parameter.count: + return 0, False + + # Check for explicit n_tokens override + # This applies to values at any level: root values (keys=()) or nested values (keys=(...)) + # For example, **kwargs: Annotated[str, Parameter(n_tokens=2)] means each kwarg value needs 2 tokens + if self.parameter.n_tokens is not None: + if self.parameter.n_tokens == -1: + return 1, True + else: + # Determine consume_all based on the hint at the requested level + # by recursively calling token_count on the hint + if len(keys) > 1: + hint = self._default + elif len(keys) == 1: + hint = self._type_hint_for_key(keys[0]) + else: + hint = self.hint + + # Recursively call token_count to get the consume_all behavior + # We ignore the token count from the recursive call and use our explicit n_tokens + _, consume_all_from_type = token_count(hint) + return self.parameter.n_tokens, consume_all_from_type + + if len(keys) > 1: + hint = self._default + elif len(keys) == 1: + hint = self._type_hint_for_key(keys[0]) + else: + hint = self.hint + if self._enum_flag_type and not keys: + return 1, True + tokens_per_element, consume_all = token_count(hint) + return tokens_per_element, consume_all + + @property + def negatives(self): + """Negative flags from :meth:`.Parameter.get_negatives`.""" + return self.parameter.get_negatives(resolve_annotated(self.field_info.annotation)) + + @property + def name(self) -> str: + """The **first** provided name this argument goes by.""" + return self.names[0] + + @property + def names(self) -> tuple[str, ...]: + """Names the argument goes by (both positive and negative).""" + import itertools + + assert isinstance(self.parameter.name, tuple) + return tuple(itertools.chain(self.parameter.name, self.negatives)) + + def env_var_split(self, value: str, delimiter: str | None = None) -> list[str]: + """Split a given value with :meth:`.Parameter.env_var_split`.""" + return self.parameter.env_var_split(self.hint, value, delimiter=delimiter) + + @property + def show(self) -> bool: + """Show this argument on the help page. + + If an argument has child arguments, don't show it on the help-page. + Returns False for arguments that won't be parsed (including underscore-prefixed params). + """ + if self.children: + return False + if self.parameter.show is not None: + # User explicitly set show + return self.parameter.show + # Default to whether this argument is parsed + return self.parse + + @property + def parse(self) -> bool: + """Whether this argument should be parsed from CLI tokens. + + If ``Parameter.parse`` is a regex pattern, parse if the pattern matches + the field name; otherwise don't parse. + """ + if self.parameter.parse is None: + return True + if isinstance(self.parameter.parse, re.Pattern): + return bool(self.parameter.parse.search(self.field_info.name)) + return bool(self.parameter.parse) + + @property + def required(self) -> bool: + """Whether or not this argument requires a user-provided value.""" + if self.parameter.required is None: + return self.field_info.required + else: + return self.parameter.required + + def is_positional_only(self) -> bool: + return self.field_info.is_positional_only + + def is_var_positional(self) -> bool: + return self.field_info.kind == self.field_info.VAR_POSITIONAL + + def is_flag(self) -> bool: + """Check if this argument is a flag (consumes no CLI tokens). + + Flags are arguments that don't consume command-line tokens after the option name. + They typically have implicit values (e.g., `--verbose` for bool, `--no-items` for list). + + Returns + ------- + bool + True if the argument consumes zero tokens from the command line. + + Examples + -------- + >>> from cyclopts import Parameter + >>> bool_arg = Argument(hint=bool, parameter=Parameter(name="--verbose")) + >>> bool_arg.is_flag() + True + >>> str_arg = Argument(hint=str, parameter=Parameter(name="--name")) + >>> str_arg.is_flag() + False + """ + return self.token_count() == (0, False) + + def get_choices(self, force: bool = False) -> tuple[str, ...] | None: + """Extract completion choices from type hint. + + Extracts choices from Literal types, Enum types, and Union types containing them. + Respects the Parameter.show_choices setting unless force=True. + + Parameters + ---------- + force : bool + If True, return choices even when show_choices=False. + Used by shell completion to always provide choices. + + Returns + ------- + tuple[str, ...] | None + Tuple of choice strings if choices exist and should be shown, None otherwise. + + Examples + -------- + >>> argument = Argument(hint=Literal["dev", "staging", "prod"], parameter=Parameter(show_choices=True)) + >>> argument.get_choices() + ('dev', 'staging', 'prod') + >>> argument = Argument(hint=Literal["dev", "staging", "prod"], parameter=Parameter(show_choices=False)) + >>> argument.get_choices() # Returns None for help text + >>> argument.get_choices(force=True) # Returns choices for completion + ('dev', 'staging', 'prod') + """ + if not force and not self.parameter.show_choices: + return None + choices = get_choices_from_hint(self.hint, self.parameter.name_transform) + return tuple(choices) if choices else None + + def _json(self) -> dict: + """Convert argument to be json-like for pydantic. + + All values will be str/list/dict. JSON-serialized strings (from sources + like config files or environment variables) are deserialized back to their + original dict/list structure. + """ + out = {} + if self._accepts_keywords: + for token in self.tokens: + node = out + for key in token.keys[:-1]: + node = node.setdefault(key, {}) + node[token.keys[-1]] = token.value if token.implicit_value is UNSET else token.implicit_value + for child in self.children: + child._marked = True + if not child.has_tokens: + continue + keys = child.keys[len(self.keys) :] + if child._accepts_keywords: + result = child._json() + if result: + out[keys[0]] = result + elif (get_origin(child.hint) or child.hint) in ITERABLE_TYPES: + for token in child.tokens: + if token.implicit_value is not UNSET: + out.setdefault(keys[-1], []).extend(token.implicit_value) + else: + value = token.value + # Deserialize JSON strings (from update_argument_collection) back to dict/list + if isinstance(value, str) and value.strip() and value.strip()[0] in ("{", "["): + try: + value = json.loads(value) + except json.JSONDecodeError: + pass + out.setdefault(keys[-1], []).append(value) + else: + token = child.tokens[0] + out[keys[0]] = token.value if token.implicit_value is UNSET else token.implicit_value + return out + + def _run_missing_keys_checker(self, data): + if not self._missing_keys_checker or (not self.required and not data): + return + if not (missing_keys := self._missing_keys_checker(self, data)): + return + missing_key = missing_keys[0] + keys = self.keys + (missing_key,) + missing_arguments = self.children.filter_by(keys_prefix=keys) + if missing_arguments: + raise MissingArgumentError(argument=missing_arguments[0]) + else: + missing_description = self.field_info.names[0] + "->" + "->".join(keys) + raise ValueError( + f'Required field "{missing_description}" is not accessible by Cyclopts; possibly due to conflicting POSITIONAL/KEYWORD requirements.' + ) + + def _handle_pydantic_validation_error(self, exc): + import pydantic + + error = exc.errors()[0] + if error["type"] == "missing": + loc = error["loc"] + + # Pydantic includes list indices in loc for list-element errors + # (e.g. ("animals", 0, "dog", "name")). Cyclopts doesn't model list + # items as individual Arguments, so no prefix-match can correctly + # map — fall through to the native pydantic error, which shows the + # full nested path. + if not any(isinstance(part, int) for part in loc): + candidate = tuple(loc) + while candidate: + missing_arguments = self.children_recursive.filter_by(keys_prefix=self.keys + candidate) + # An Argument that already has tokens cannot be "missing"; + # the stripping heuristic has wandered into a populated sibling. + missing_arguments = [a for a in missing_arguments if not a.tokens] + if missing_arguments: + raise MissingArgumentError(argument=missing_arguments[0]) from exc + if len(candidate) == 1: + break + # For discriminated unions pydantic prepends the discriminator + # value (e.g. loc=("cat", "rainbow")). Strip leading elements + # until we find a real child Argument. + candidate = candidate[1:] + # Fall through to ValidationError. + + if isinstance(exc, pydantic.ValidationError): + raise ValidationError(exception_message=str(exc), argument=self) from exc + else: + raise exc diff --git a/.venv/lib/python3.10/site-packages/cyclopts/argument/_collection.py b/.venv/lib/python3.10/site-packages/cyclopts/argument/_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..8255053a667f05914f73e46fbde0c14982112eeb --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/argument/_collection.py @@ -0,0 +1,767 @@ +"""ArgumentCollection class and related functionality.""" + +import inspect +import itertools +import json +from collections.abc import Callable, Iterable, Sequence +from typing import TYPE_CHECKING, Any, SupportsIndex, TypeVar, overload + +if TYPE_CHECKING: + from cyclopts.core import App + +from cyclopts.exceptions import ( + UnknownOptionError, +) +from cyclopts.field_info import ( + signature_parameters, +) +from cyclopts.group import Group +from cyclopts.parameter import Parameter +from cyclopts.token import Token +from cyclopts.utils import UNSET, is_iterable + +from ._argument import Argument +from .utils import ( + KIND_PARENT_CHILD_REASSIGNMENT, + PARAMETER_SUBKEY_BLOCKER, + extract_docstring_help, + resolve_parameter_name, + to_cli_option_name, + walk_leaves, +) + +T = TypeVar("T") + + +class ArgumentCollection(list[Argument]): + """A list-like container for :class:`Argument`.""" + + def __init__(self, *args): + super().__init__(*args) + + def copy(self) -> "ArgumentCollection": + """Returns a shallow copy of the :class:`ArgumentCollection`.""" + return type(self)(self) + + @overload + def __getitem__(self, term: SupportsIndex, /) -> Argument: ... + @overload + def __getitem__(self, term: slice, /) -> list[Argument]: ... + @overload + def __getitem__(self, term: str, /) -> Argument: ... + def __getitem__( + self, + term: str | SupportsIndex | slice, + ) -> Argument | list[Argument]: + if isinstance(term, (SupportsIndex, slice)): + return super().__getitem__(term) + + return self.get(term) + + def __contains__(self, item: object, /) -> bool: + """Check if an argument or argument name exists in the collection. + + Parameters + ---------- + item : Argument | str + Either an Argument object or a string name/alias to search for. + + Returns + ------- + bool + True if the item is in the collection. + + Examples + -------- + >>> argument_collection = ArgumentCollection( + ... [ + ... Argument(parameter=Parameter(name="--foo")), + ... Argument(parameter=Parameter(name=("--bar", "-b"))), + ... ] + ... ) + >>> "--foo" in argument_collection + True + >>> "-b" in argument_collection # Alias matching + True + >>> "--baz" in argument_collection + False + """ + if isinstance(item, str): + try: + self[item] + return True + except KeyError: + return False + else: + return super().__contains__(item) + + @overload + def get( + self, + term: str | int, + default: type[UNSET] = ..., + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> Argument: ... + @overload + def get( + self, + term: str | int, + default: T, + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> Argument | T: ... + def get( + self, + term: str | int, + default: Any = UNSET, + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> Argument | Any: + """Get an :class:`Argument` by name or index. + + This is a convenience wrapper around :meth:`match` that returns just + the :class:`Argument` object instead of a tuple. + + Parameters + ---------- + term : str | int + Either a string keyword or an integer positional index. + default : Any + Default value to return if term not found. If :data:`~cyclopts.utils.UNSET` (default), + will raise :exc:`KeyError`/:exc:`IndexError`. + transform : Callable[[str], str] | None + Optional function to transform string terms before matching. + delimiter : str + Delimiter for nested field access. + + Returns + ------- + Argument | None + The matched :class:`Argument`, or ``default`` if provided and not found. + + Raises + ------ + :exc:`KeyError` + If ``term`` is a string and not found (when ``default`` is :data:`~cyclopts.utils.UNSET`). + :exc:`IndexError` + If ``term`` is an int and is out-of-range (when ``default`` is :data:`~cyclopts.utils.UNSET`). + + See Also + -------- + :meth:`match` : Returns a tuple of (:class:`Argument`, keys, value) with more detailed information. + """ + try: + argument, _, _ = self.match(term, transform=transform, delimiter=delimiter) + return argument + except ValueError: + if default is UNSET: + if isinstance(term, str): + raise KeyError(f"No such Argument: {term}") from None + else: + raise IndexError(f"Argument index {term} out of range") from None + return default + + def match( + self, + term: str | int, + *, + transform: Callable[[str], str] | None = None, + delimiter: str = ".", + ) -> tuple[Argument, tuple[str, ...], Any]: + """Matches CLI keyword or index to their :class:`Argument`. + + Parameters + ---------- + term: str | int + One of: + + * :obj:`str` keyword like ``"--foo"`` or ``"-f"`` or ``"--foo.bar.baz"``. + + * :obj:`int` global positional index. + + Raises + ------ + ValueError + If the provided ``term`` doesn't match. + + Returns + ------- + Argument + Matched :class:`Argument`. + tuple[str, ...] + Python keys into :class:`Argument`. Non-empty iff :class:`Argument` accepts keys. + Any + Implicit value (if a flag). :obj:`~.UNSET` otherwise. + """ + best_match_argument, best_match_keys, best_implicit_value = None, None, UNSET + for argument in self: + try: + match_keys, implicit_value = argument.match(term, transform=transform, delimiter=delimiter) + except ValueError: + continue + if best_match_keys is None or len(match_keys) < len(best_match_keys): + best_match_keys = match_keys + best_match_argument = argument + best_implicit_value = implicit_value + if not match_keys: + break + + if best_match_argument is None or best_match_keys is None: + raise ValueError(f"No Argument matches {term!r}") + + return best_match_argument, best_match_keys, best_implicit_value + + def _set_marks(self, val: bool): + for argument in self: + argument._marked = val + + def _convert(self): + """Convert and validate all elements.""" + self._set_marks(False) + for argument in sorted(self, key=lambda x: x.keys): + if argument._marked: + continue + argument.convert_and_validate() + + @classmethod + def _from_type( + cls, + field_info, + keys: tuple[str, ...], + *default_parameters: Parameter | None, + group_lookup: dict[str, Group], + group_arguments: Group, + group_parameters: Group, + parse_docstring: bool = True, + docstring_lookup: dict[tuple[str, ...], Parameter] | None = None, + positional_index: int | None = None, + _resolve_groups: bool = True, + ): + from cyclopts.parameter import get_parameters + + out = cls() + + if docstring_lookup is None: + docstring_lookup = {} + + cyclopts_parameters_no_group = [] + + hint = field_info.hint + hint, hint_parameters = get_parameters(hint) + cyclopts_parameters_no_group.extend(hint_parameters) + + if not keys: + if field_info.kind is field_info.VAR_KEYWORD: + hint = dict[str, hint] + elif field_info.kind is field_info.VAR_POSITIONAL: + hint = tuple[hint, ...] + + if _resolve_groups: + cyclopts_parameters = [] + for cparam in cyclopts_parameters_no_group: + resolved_groups = [] + for group in cparam.group: # pyright:ignore + if isinstance(group, str): + group = group_lookup[group] + resolved_groups.append(group) + cyclopts_parameters.append(group.default_parameter) + cyclopts_parameters.append(cparam) + + if resolved_groups: + has_visible_group = any(g.show for g in resolved_groups) + all_nameless = all(not g.name for g in resolved_groups) + + if has_visible_group: + cyclopts_parameters.append(Parameter(group=resolved_groups)) + elif all_nameless: + default_group = ( + group_arguments + if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL) + else group_parameters + ) + all_groups = (default_group,) + tuple(resolved_groups) + cyclopts_parameters.append(Parameter(group=all_groups)) + else: + cyclopts_parameters.append(Parameter(group=resolved_groups)) + else: + cyclopts_parameters = cyclopts_parameters_no_group + + upstream_parameter = Parameter.combine( + ( + Parameter(group=group_arguments) + if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL) + else Parameter(group=group_parameters) + ), + *default_parameters, + ) + immediate_parameter = Parameter.combine(*cyclopts_parameters) + + if keys: + cparam = Parameter.combine( + upstream_parameter, + PARAMETER_SUBKEY_BLOCKER, + immediate_parameter, + ) + cparam = Parameter.combine( + cparam, + Parameter( + name=resolve_parameter_name( + upstream_parameter.name, # pyright: ignore + (immediate_parameter.name or tuple(cparam.name_transform(x) for x in field_info.names)) + + cparam.alias, # pyright: ignore + ) + ), + ) + else: + cparam = Parameter.combine( + upstream_parameter, + immediate_parameter, + ) + assert isinstance(cparam.alias, tuple) + if cparam.name: + if field_info.is_keyword: + assert isinstance(cparam.name, tuple) + cparam = Parameter.combine( + cparam, Parameter(name=resolve_parameter_name(cparam.name + cparam.alias)) + ) + else: + if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL): + cparam = Parameter.combine(cparam, Parameter(name=(name.upper() for name in field_info.names))) + elif field_info.kind is field_info.VAR_KEYWORD: + cparam = Parameter.combine(cparam, Parameter(name=("--[KEYWORD]",))) + else: + assert cparam.name_transform is not None + cparam = Parameter.combine( + cparam, + Parameter( + name=tuple("--" + cparam.name_transform(name) for name in field_info.names) + + resolve_parameter_name(cparam.alias) + ), + ) + + if field_info.is_keyword_only: + positional_index = None + + argument = Argument(field_info=field_info, parameter=cparam, keys=keys, hint=hint) + + if positional_index is not None: + if not argument._accepts_keywords or argument._enum_flag_type: + argument.index = positional_index + positional_index += 1 + + out.append(argument) + if argument._accepts_keywords: + hint_docstring_lookup = extract_docstring_help(argument.hint) if parse_docstring else {} + hint_docstring_lookup.update(docstring_lookup) + + for sub_field_name, sub_field_info in argument._lookup.items(): + updated_kind = KIND_PARENT_CHILD_REASSIGNMENT[(argument.field_info.kind, sub_field_info.kind)] + if updated_kind is None: + continue + + sub_field_info.kind = updated_kind + + if sub_field_info.is_keyword_only: + positional_index = None + + subkey_docstring_lookup = { + k[1:]: v for k, v in hint_docstring_lookup.items() if k[0] == sub_field_name and len(k) > 1 + } + + subkey_argument_collection = cls._from_type( + sub_field_info, + keys + (sub_field_name,), + cparam, + ( + Parameter(help=sub_field_info.help) + if sub_field_info.help + else hint_docstring_lookup.get((sub_field_name,)) + ), + Parameter(required=argument.required & sub_field_info.required), + group_lookup=group_lookup, + group_arguments=group_arguments, + group_parameters=group_parameters, + parse_docstring=parse_docstring, + docstring_lookup=subkey_docstring_lookup, + positional_index=positional_index, + _resolve_groups=_resolve_groups, + ) + if subkey_argument_collection: + argument.children.append(subkey_argument_collection[0]) + out.extend(subkey_argument_collection) + + if positional_index is not None: + positional_index = subkey_argument_collection._max_index + if positional_index is not None: + positional_index += 1 + + return out + + @classmethod + def _from_callable( + cls, + func: Callable, + *default_parameters: Parameter | None, + group_lookup: dict[str, Group] | None = None, + group_arguments: Group | None = None, + group_parameters: Group | None = None, + parse_docstring: bool = True, + _resolve_groups: bool = True, + ): + out = cls() + + if group_arguments is None: + group_arguments = Group.create_default_arguments() + if group_parameters is None: + group_parameters = Group.create_default_parameters() + + if _resolve_groups: + group_lookup = { + group.name: group + for group in _resolve_groups_from_callable( + func, + *default_parameters, + group_arguments=group_arguments, + group_parameters=group_parameters, + ) + } + else: + group_lookup = {} + + docstring_lookup = extract_docstring_help(func) if parse_docstring else {} + positional_index = 0 + for field_info in signature_parameters(func).values(): + if parse_docstring: + subkey_docstring_lookup = { + k[1:]: v for k, v in docstring_lookup.items() if k[0] == field_info.name and len(k) > 1 + } + else: + subkey_docstring_lookup = None + iparam_argument_collection = cls._from_type( + field_info, + (), + *default_parameters, + Parameter(help=field_info.help) if field_info.help else docstring_lookup.get((field_info.name,)), + group_lookup=group_lookup, + group_arguments=group_arguments, + group_parameters=group_parameters, + positional_index=positional_index, + parse_docstring=parse_docstring, + docstring_lookup=subkey_docstring_lookup, + _resolve_groups=_resolve_groups, + ) + if positional_index is not None: + positional_index = iparam_argument_collection._max_index + if positional_index is not None: + positional_index += 1 + out.extend(iparam_argument_collection) + + return out + + @property + def groups(self): + groups = [] + for argument in self: + assert isinstance(argument.parameter.group, tuple) + for group in argument.parameter.group: + if group not in groups: + groups.append(group) + return groups + + @property + def _root_arguments(self): + for argument in self: + if not argument.keys: + yield argument + + @property + def _max_index(self) -> int | None: + return max((x.index for x in self if x.index is not None), default=None) + + def filter_by( + self, + *, + group: Group | None = None, + has_tokens: bool | None = None, + has_tree_tokens: bool | None = None, + keys_prefix: tuple[str, ...] | None = None, + kind: inspect._ParameterKind | None = None, + parse: bool | None = None, + show: bool | None = None, + value_set: bool | None = None, + ) -> "ArgumentCollection": + """Filter the :class:`ArgumentCollection`. + + All non-None filters will be applied. + + Parameters + ---------- + group: Group | None + The :class:`.Group` the arguments should be in. + has_tokens: bool | None + Immediately has tokens (not including children). + has_tree_tokens: bool | None + :class:`Argument` and/or it's children have parsed tokens. + kind: inspect._ParameterKind | None + The :attr:`~inspect.Parameter.kind` of the argument. + parse: bool | None + If the argument is intended to be parsed or not. + show: bool | None + The :class:`Argument` is intended to be show on the help page. + value_set: bool | None + The converted value is set. + """ + ac = self.copy() + cls = type(self) + + if group is not None: + ac = cls(x for x in ac if group in x.parameter.group) # pyright: ignore + if kind is not None: + ac = cls(x for x in ac if x.field_info.kind == kind) + if has_tokens is not None: + ac = cls(x for x in ac if not (bool(x.tokens) ^ bool(has_tokens))) + if has_tree_tokens is not None: + ac = cls(x for x in ac if not (bool(x.tokens) ^ bool(has_tree_tokens))) + if keys_prefix is not None: + ac = cls(x for x in ac if x.keys[: len(keys_prefix)] == keys_prefix) + if show is not None: + ac = cls(x for x in ac if not (x.show ^ bool(show))) + if value_set is not None: + ac = cls(x for x in ac if ((x.value is UNSET) ^ bool(value_set))) + if parse is not None: + ac = cls(x for x in ac if not (x.parse ^ parse)) + + return ac + + +def _resolve_groups_from_callable( + func: Callable[..., Any], + *default_parameters: Parameter | None, + group_arguments: Group | None = None, + group_parameters: Group | None = None, +) -> list[Group]: + argument_collection = ArgumentCollection._from_callable( + func, + *default_parameters, + group_arguments=group_arguments, + group_parameters=group_parameters, + parse_docstring=False, + _resolve_groups=False, + ) + + resolved_groups = [] + if group_arguments is not None: + resolved_groups.append(group_arguments) + if group_parameters is not None: + resolved_groups.append(group_parameters) + + for argument in argument_collection: + for group in argument.parameter.group: # pyright: ignore + if not isinstance(group, Group): + continue + + if any(group != x and x._name == group._name for x in resolved_groups): + raise ValueError("Cannot register 2 distinct Group objects with same name.") + + if group.default_parameter is not None and group.default_parameter.group: + raise ValueError("Group.default_parameter cannot have a specified group.") # pragma: no cover + + try: + next(x for x in resolved_groups if x._name == group._name) + except StopIteration: + resolved_groups.append(group) + + for argument in argument_collection: + for group in argument.parameter.group: # pyright: ignore + if not isinstance(group, str): + continue + try: + next(x for x in resolved_groups if x.name == group) + except StopIteration: + resolved_groups.append(Group(group)) + + return resolved_groups + + +def _meta_arguments(apps: Sequence["App"]) -> ArgumentCollection: + argument_collection = ArgumentCollection() + for app in apps: + if app._meta is None: + continue + argument_collection.extend(app._meta.assemble_argument_collection()) + return argument_collection + + +def _is_valid_option_key(option_key: str, arguments: "ArgumentCollection") -> bool: + """Check if option_key corresponds to a valid root argument. + + When processing nested config keys like {"p": {"timeout": 3}}, the fallback + alias matching needs to verify that "p" is actually a valid parameter before + matching nested fields. This prevents unknown keys like "np" from incorrectly + matching against valid nested arguments. + + If no root argument exists (children-only collection, e.g., from JSON env var + processing), returns True since the option_key is implicitly valid. + + Parameters + ---------- + option_key : str + The top-level config key to validate (e.g., "p" from {"p": {"timeout": 3}}). + arguments : ArgumentCollection + The argument collection to validate against. + + Returns + ------- + bool + True if option_key is valid, False otherwise. + """ + root_arg = next((arg for arg in arguments if arg.keys == ()), None) + if not root_arg: + return True # Children-only collection, implicitly valid + cli_parent = to_cli_option_name(option_key) + return bool( + (root_arg.parameter.name and cli_parent in root_arg.parameter.name) or option_key in root_arg.field_info.names + ) + + +def update_argument_collection( + config: dict, + source: str, + arguments: ArgumentCollection, + apps: Sequence["App"] | None = None, + *, + root_keys: Iterable[str], + allow_unknown: bool, +): + """Updates an argument collection with values from a configuration dictionary. + + This function takes configuration data (typically from JSON, TOML, YAML files + or environment variables) and populates the corresponding arguments in the + ArgumentCollection with tokens representing those values. + + The function handles various naming conventions, including: + - Exact matches (e.g., "storage_class" matches "storage_class") + - Transformed matches (e.g., "storage-class" matches "storage_class") + - Pydantic aliases (e.g., "storageClass" matches field with alias "storageClass") + + Parameters + ---------- + config : dict + Configuration dictionary with nested structure mapping to CLI arguments. + source : str + Source identifier (e.g., file path or "env") for error messages and tracking. + arguments : ArgumentCollection + Collection of arguments to populate with configuration values. + apps : Optional[Sequence[App]] + Stack of App instances for meta-argument handling. + We need to know all the meta-apps leading up to the current application so that we can + properly detect unknown keys. + root_keys : Iterable[str] + Base path keys to prepend to all configuration keys. + allow_unknown : bool + If True, ignore unrecognized configuration keys instead of raising errors. + + Raises + ------ + UnknownOptionError + If a configuration key doesn't match any argument and allow_unknown is False. + + Notes + ----- + Arguments that already have tokens are skipped to preserve command-line + precedence over configuration files. + """ + meta_arguments = _meta_arguments(apps or ()) + + do_not_update = {} + + for option_key, option_value in config.items(): + for subkeys, value in walk_leaves(option_value): + cli_option_name = to_cli_option_name(option_key, *subkeys) + complete_keyword = "".join(f"[{k}]" for k in itertools.chain(root_keys, (option_key,), subkeys)) + + try: + meta_arguments.match(cli_option_name) + continue + except ValueError: + pass + + argument = None + remaining_keys = () + try: + argument, remaining_keys, _ = arguments.match(cli_option_name) + except ValueError: + if subkeys and _is_valid_option_key(option_key, arguments): + for arg in arguments: + if len(subkeys) != len(arg.keys): + continue + + all_match = True + for i, (subkey, arg_key) in enumerate(zip(subkeys, arg.keys, strict=False)): + if subkey == arg_key: + continue + + if i == len(arg.keys) - 1: + if subkey not in arg.field_info.names: + all_match = False + break + else: + parent_keys = arg.keys[: i + 1] + alias_found = False + for parent_arg in arguments: + if parent_arg.keys == parent_keys and subkey in parent_arg.field_info.names: + alias_found = True + break + if not alias_found: + all_match = False + break + + if all_match: + argument = arg + remaining_keys = () + break + + if not argument: + if allow_unknown: + continue + if apps and apps[-1]._meta_parent: + continue + raise UnknownOptionError( + token=Token(keyword=complete_keyword, source=source), argument_collection=arguments + ) from None + + if do_not_update.setdefault(id(argument), bool(argument.tokens)): + continue + + if not is_iterable(value): + value = (value,) + + if value: + for i, v in enumerate(value): + if v is None: + token = Token( + keyword=complete_keyword, + implicit_value=None, + source=source, + index=i, + keys=remaining_keys, + ) + else: + if isinstance(v, dict | list): + # Serialize to JSON string; will be deserialized in Argument._json() + value_str = json.dumps(v) + else: + value_str = str(v) + token = Token( + keyword=complete_keyword, value=value_str, source=source, index=i, keys=remaining_keys + ) + argument.append(token) + else: + token = Token( + keyword=complete_keyword, implicit_value=value, source=source, index=0, keys=remaining_keys + ) + argument.append(token) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/argument/utils.py b/.venv/lib/python3.10/site-packages/cyclopts/argument/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f92b731a9905b11c3c5560f6e22417364e2187 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/argument/utils.py @@ -0,0 +1,255 @@ +"""Shared helper functions and constants for the argument package.""" + +import sys +from collections.abc import Callable, Iterator +from contextlib import suppress +from enum import Enum, Flag +from functools import partial +from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, get_args, get_origin + +if TYPE_CHECKING: + from cyclopts.argument._argument import Argument + +F = TypeVar("F", bound=Flag) + +from cyclopts._convert import convert_enum_flag +from cyclopts.annotations import ( + ITERABLE_TYPES, + is_class_and_subclass, + is_union, + resolve_annotated, +) +from cyclopts.field_info import ( + KEYWORD_ONLY, + POSITIONAL_ONLY, + POSITIONAL_OR_KEYWORD, + VAR_KEYWORD, + VAR_POSITIONAL, + FieldInfo, +) +from cyclopts.parameter import Parameter + +if sys.version_info >= (3, 12): # pragma: no cover + from typing import TypeAliasType +else: # pragma: no cover + TypeAliasType = None + +PARAMETER_SUBKEY_BLOCKER = Parameter( + name=None, + alias=None, + converter=None, # pyright: ignore + validator=None, + accepts_keys=None, + consume_multiple=None, + env_var=None, +) + +KIND_PARENT_CHILD_REASSIGNMENT = { + (POSITIONAL_OR_KEYWORD, POSITIONAL_OR_KEYWORD): POSITIONAL_OR_KEYWORD, + (POSITIONAL_OR_KEYWORD, POSITIONAL_ONLY): POSITIONAL_ONLY, + (POSITIONAL_OR_KEYWORD, KEYWORD_ONLY): KEYWORD_ONLY, + (POSITIONAL_OR_KEYWORD, VAR_POSITIONAL): VAR_POSITIONAL, + (POSITIONAL_OR_KEYWORD, VAR_KEYWORD): VAR_KEYWORD, + (POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD): POSITIONAL_ONLY, + (POSITIONAL_ONLY, POSITIONAL_ONLY): POSITIONAL_ONLY, + (POSITIONAL_ONLY, KEYWORD_ONLY): None, + (POSITIONAL_ONLY, VAR_POSITIONAL): VAR_POSITIONAL, + (POSITIONAL_ONLY, VAR_KEYWORD): None, + (KEYWORD_ONLY, POSITIONAL_OR_KEYWORD): KEYWORD_ONLY, + (KEYWORD_ONLY, POSITIONAL_ONLY): None, + (KEYWORD_ONLY, KEYWORD_ONLY): KEYWORD_ONLY, + (KEYWORD_ONLY, VAR_POSITIONAL): None, + (KEYWORD_ONLY, VAR_KEYWORD): VAR_KEYWORD, + (VAR_POSITIONAL, POSITIONAL_OR_KEYWORD): POSITIONAL_ONLY, + (VAR_POSITIONAL, POSITIONAL_ONLY): POSITIONAL_ONLY, + (VAR_POSITIONAL, KEYWORD_ONLY): None, + (VAR_POSITIONAL, VAR_POSITIONAL): VAR_POSITIONAL, + (VAR_POSITIONAL, VAR_KEYWORD): None, + (VAR_KEYWORD, POSITIONAL_OR_KEYWORD): KEYWORD_ONLY, + (VAR_KEYWORD, POSITIONAL_ONLY): None, + (VAR_KEYWORD, KEYWORD_ONLY): KEYWORD_ONLY, + (VAR_KEYWORD, VAR_POSITIONAL): None, + (VAR_KEYWORD, VAR_KEYWORD): VAR_KEYWORD, +} + + +def get_choices_from_hint(type_: type, name_transform: Callable[[str], str]) -> list[str]: + """Extract completion choices from a type hint. + + Recursively extracts choices from Literal types, Enum types, and Union types. + + Parameters + ---------- + type_ : type + Type annotation to extract choices from. + name_transform : Callable[[str], str] + Function to transform choice names (e.g., for case conversion). + + Returns + ------- + list[str] + List of choice strings extracted from the type hint. + """ + get_choices = partial(get_choices_from_hint, name_transform=name_transform) + choices = [] + _origin = get_origin(type_) + if isinstance(type_, type) and is_class_and_subclass(type_, Enum): + choices.extend(name_transform(x) for x in type_.__members__) + elif is_union(_origin): + inner_choices = [get_choices(inner) for inner in get_args(type_)] + for x in inner_choices: + if x: + choices.extend(x) + elif _origin is Literal: + choices.extend(str(x) for x in get_args(type_)) + elif _origin in ITERABLE_TYPES: + args = get_args(type_) + if len(args) == 1 or (_origin is tuple and len(args) == 2 and args[1] is Ellipsis): + choices.extend(get_choices(args[0])) + elif _origin is Annotated: + choices.extend(get_choices(resolve_annotated(type_))) + elif TypeAliasType is not None and isinstance(type_, TypeAliasType): + choices.extend(get_choices(type_.__value__)) + return choices + + +def startswith(string, prefix): + def normalize(s): + return s.replace("_", "-") + + return normalize(string).startswith(normalize(prefix)) + + +def missing_keys_factory( + get_field_info: Callable[[Any], dict[str, FieldInfo]], +) -> Callable[["Argument", dict[str, Any]], list[str]]: + def inner(argument: "Argument", data: dict[str, Any]) -> list[str]: + provided_keys = set(data) + field_info = get_field_info(argument.hint) + return [k for k, v in field_info.items() if (v.required and k not in provided_keys)] + + return inner + + +def enum_flag_from_dict( + enum_type: type[F], + data: dict[str, bool], + name_transform: Callable[[str], str], +) -> F: + """Convert a dictionary of boolean flags to a Flag enum value. + + Parameters + ---------- + enum_type : type[F] + The Flag enum type to convert to. + data : dict[str, bool] + Dictionary mapping flag names to boolean values. + + Returns + ------- + F + The combined flag value. + """ + return convert_enum_flag(enum_type, (k for k, v in data.items() if v), name_transform) + + +def extract_docstring_help(f: Callable) -> dict[tuple[str, ...], Parameter]: + from docstring_parser import parse_from_object + + with suppress(AttributeError): + f = f.func # pyright: ignore[reportFunctionMemberAccess] + + result = {} + + # For classes, walk through MRO to include base class fields. + # parse_from_object only extracts docstrings from the **immediate** class's source code, + # not from inherited fields. + # From docstring_parser docs: + # + # When given a class, only the attribute docstrings of that class are parsed, not its + # inherited classes. This is a design decision. Separate calls to this function + # should be performed to get attribute docstrings of parent classes. + if mro := getattr(f, "__mro__", None): + # Process base classes first (reversed MRO order), so derived classes can override + # their parent's docstrings if they redefine the same field with a new docstring. + for base_class in reversed(mro[:-1]): # Exclude 'object' + try: + parsed = parse_from_object(base_class) + for dparam in parsed.params: + result[tuple(dparam.arg_name.split("."))] = Parameter(help=dparam.description) + except (TypeError, AttributeError): + # Some base classes may not have parseable docstrings (e.g., built-in classes) + continue + else: + # For functions/callables (original behavior) + try: + parsed = parse_from_object(f) + for dparam in parsed.params: + result[tuple(dparam.arg_name.split("."))] = Parameter(help=dparam.description) + except (TypeError, AttributeError): + # parse_from_object may fail for some callables + pass + + return result + + +def resolve_parameter_name_helper(elem): + if elem.endswith("*"): + elem = elem[:-1].rstrip(".") + if elem and not elem.startswith("-"): + elem = "--" + elem + return elem + + +def resolve_parameter_name(*argss: tuple[str, ...]) -> tuple[str, ...]: + """Resolve parameter names by combining and formatting multiple tuples of strings. + + Parameters + ---------- + *argss + Each tuple represents a group of parameter name components. + + Returns + ------- + tuple[str, ...] + A tuple of resolved parameter names. + """ + argss = tuple(x for x in argss if x) + + if len(argss) == 0: + return () + elif len(argss) == 1: + return tuple("*" if x == "*" else resolve_parameter_name_helper(x) for x in argss[0]) + + out = [] + for a1 in argss[0]: + a1 = resolve_parameter_name_helper(a1) + for a2 in argss[1]: + if a2.startswith("-") or not a1: + out.append(a2) + else: + out.append(a1 + "." + a2) + + return resolve_parameter_name(tuple(out), *argss[2:]) + + +def walk_leaves( + d, + parent_keys: tuple[str, ...] | None = None, +) -> Iterator[tuple[tuple[str, ...], Any]]: + if parent_keys is None: + parent_keys = () + + if isinstance(d, dict): + for key, value in d.items(): + current_keys = parent_keys + (key,) + if isinstance(value, dict): + yield from walk_leaves(value, current_keys) + else: + yield current_keys, value + else: + yield (), d + + +def to_cli_option_name(*keys: str) -> str: + return "--" + ".".join(keys) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/bind.py b/.venv/lib/python3.10/site-packages/cyclopts/bind.py new file mode 100644 index 0000000000000000000000000000000000000000..df5409b0b93eaa1fa7db1c771bf018d4bbcc4648 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/bind.py @@ -0,0 +1,614 @@ +import inspect +import itertools +import os +import shlex +import sys +from collections.abc import Callable, Iterable, Sequence +from contextlib import suppress +from functools import partial +from typing import TYPE_CHECKING, Any, NamedTuple, get_origin + +from cyclopts._convert import _bool +from cyclopts.annotations import resolve_optional +from cyclopts.argument import Argument, ArgumentCollection +from cyclopts.exceptions import ( + ArgumentOrderError, + CoercionError, + CombinedShortOptionError, + ConsumeMultipleError, + CycloptsError, + MissingArgumentError, + RequiresEqualsError, + UnknownOptionError, + ValidationError, +) +from cyclopts.field_info import POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD +from cyclopts.token import Token +from cyclopts.utils import UNSET, is_option_like + +if sys.version_info < (3, 11): # pragma: no cover + pass +else: # pragma: no cover + pass + + +if TYPE_CHECKING: + from cyclopts.group import Group + +CliToken = partial(Token, source="cli") + + +class _KeywordMatch(NamedTuple): + """Represents a matched CLI token with its corresponding argument.""" + + matched_token: str + """The actual CLI token that was matched (e.g., '-o', '--option').""" + + argument: Argument + """The matched Argument object.""" + + keys: tuple[str, ...] + """Leftover keys for nested arguments.""" + + implicit_value: Any + """Implicit value if this is a flag, otherwise UNSET.""" + + +def normalize_tokens(tokens: None | str | Iterable[str]) -> list[str]: + if tokens is None: + tokens = sys.argv[1:] # Remove the executable + elif isinstance(tokens, str): + tokens = shlex.split(tokens) + else: + tokens = list(tokens) + return tokens + + +def _common_root_keys(argument_collection) -> tuple[str, ...]: + if not argument_collection: + return () + common = argument_collection[0].keys + for argument in argument_collection[1:]: + if not argument.keys: + return () + for i, (common_key, argument_key) in enumerate(zip(common, argument.keys, strict=False)): + if common_key != argument_key: + if i == 0: + return () + + common = argument.keys[:i] + break + common = common[: len(argument.keys)] + return common + + +def _parse_kw_and_flags( + argument_collection: ArgumentCollection, + tokens: Sequence[str], + *, + end_of_options_delimiter: str = "--", + stop_at_first_unknown: bool = False, +) -> tuple[list[str], int | None]: + """Extract keyword arguments and flags from the token stream. + + Returns + ------- + unused_tokens: list[str] + Tokens not consumed by any keyword or flag. + contiguous_positional_count: int | None + Number of leading contiguous non-option tokens before the first gap + caused by keyword extraction. ``None`` if all non-option tokens are + contiguous (i.e. no keywords were interleaved among positional tokens). + + For example, given ``a b c --bar 8 --baz 10 d``, the unused tokens are + ``['a', 'b', 'c', 'd']`` with original indices ``[0, 1, 2, 6]``. + The gap between indices 2 and 6 yields ``contiguous_positional_count=3``. + This is used by ``_parse_pos`` to prevent positional-only list parameters + from consuming tokens that appeared after keyword arguments. + """ + unused_tokens, positional_only_tokens = [], [] + unused_token_original_indices: list[int] = [] + skip_next_iterations = 0 + if end_of_options_delimiter: + try: + delimiter_index = tokens.index(end_of_options_delimiter) + except ValueError: + pass # end_of_options_delimiter not in token stream + else: + positional_only_tokens = tokens[delimiter_index:] + tokens = tokens[:delimiter_index] + for i, token in enumerate(tokens): + # If the previous argument was a keyword, then this is its value + if skip_next_iterations > 0: + skip_next_iterations -= 1 + continue + + if not is_option_like(token, allow_numbers=True): + if stop_at_first_unknown: + # Stop parsing and return all remaining tokens as unused + unused_tokens.extend(tokens[i:]) + unused_token_original_indices.extend(range(i, len(tokens))) + break + unused_tokens.append(token) + unused_token_original_indices.append(i) + continue + + cli_values: list[str] = [] + consume_count = 0 + + # startswith("-") is redundant, but it's cheap safety. + allow_combined_flags = token.startswith("-") and not token.startswith("--") + + # Try splitting on "=" for long options or short options that match exactly + if "=" in token: + cli_option, cli_value = token.split("=", 1) + # Try to match the part before "=" + try: + argument_collection.match(cli_option) + # Matched! Use the split + cli_values.append(cli_value) + consume_count -= 1 + allow_combined_flags = False + except ValueError: + # No match - might be GNU-style like "-pfile=value" + # Don't split, treat whole token as the option + cli_option = token + else: + cli_option = token + + matches: list[_KeywordMatch] = [] + attached_value: str | None = None # Track value attached to a GNU-style combined option + try: + matches.append(_KeywordMatch(cli_option, *argument_collection.match(cli_option))) + except ValueError: + # Length has to be greater than 2 (hyphen + character) to be exploded. + # Also exclude numeric values (e.g., -10, -3.14) from combined flag parsing. + if allow_combined_flags and len(token) > 2 and is_option_like(token, allow_numbers=False): + # GNU-style combined short options: process left-to-right + # Once we hit an option that takes a value, the rest is the value + chars = cli_option.lstrip("-") + position = 0 + + while position < len(chars): + char = chars[position] + test_flag = f"-{char}" + + try: + arg, keys, implicit = argument_collection.match(test_flag) + + if implicit is not UNSET or arg.parameter.count: + # This is a flag (boolean or counting) - consume just this character + matches.append(_KeywordMatch(test_flag, arg, keys, implicit)) + position += 1 + else: + # This option takes a value - rest of the string is the value + remainder = chars[position + 1 :] + matches.append(_KeywordMatch(test_flag, arg, keys, implicit)) + if remainder: + # Value is attached: -uroot or -fvuroot + # Store it separately, will be added to cli_values when processing this match + attached_value = remainder + consume_count -= 1 + # Stop processing further characters + break + + except ValueError: + # Unknown flag + if stop_at_first_unknown: + unused_tokens.extend(tokens[i:]) + return unused_tokens, None + unused_tokens.append(test_flag) + unused_token_original_indices.append(i) + position += 1 + + if not matches: + # No valid matches found at all + continue + else: + if stop_at_first_unknown: + # Unknown option, stop parsing and return all remaining tokens + unused_tokens.extend(tokens[i:]) + return unused_tokens, None + unused_tokens.append(token) + unused_token_original_indices.append(i) + continue + for match_index, match in enumerate(matches): + # For GNU-style combined options, add the attached value only when processing + # the last match (the value-taking option), not for preceding flags + if attached_value is not None and match_index == len(matches) - 1: + cli_values.append(attached_value) + + if match.argument.parameter.count: + match.argument.append(CliToken(keyword=match.matched_token, implicit_value=1)) + elif match.implicit_value is not UNSET: + # A flag was parsed + if cli_values: + try: + coerced_value = _bool(cli_values[-1]) + except CoercionError as e: + if e.token is None: + e.token = CliToken(keyword=match.matched_token) + if e.argument is None: + e.argument = match.argument + raise + if coerced_value: # --positive-flag=true or --negative-flag=true or --empty-flag=true + match.argument.append( + CliToken(keyword=match.matched_token, implicit_value=match.implicit_value) + ) + else: # --positive-flag=false or --negative-flag=false or --empty-flag=false + if isinstance(match.implicit_value, bool): + match.argument.append( + CliToken(keyword=match.matched_token, implicit_value=not match.implicit_value) + ) + else: + # A negative for a non-bool field doesn't really make sense; + # e.g. --empty-list=False + # So we'll just silently skip it, as it may make bash scripting easier. + pass + else: + match.argument.append(CliToken(keyword=match.matched_token, implicit_value=match.implicit_value)) + else: + # This is a value-taking option (not a flag or counting parameter) + # Error only if we're trying to combine multiple value-taking options without values + # (e.g., -fu where both -f and -u take values would be invalid) + # But -fu where -f is a flag and -u takes a value is valid (GNU-style) + if len(matches) > 1: + # Count how many value-taking options we have + value_taking_count = sum( + 1 for m in matches if m.implicit_value is UNSET and not m.argument.parameter.count + ) + if value_taking_count > 1: + raise CombinedShortOptionError( + msg=f"Cannot combine multiple value-taking options in token {cli_option}" + ) + tokens_per_element, consume_all = match.argument.token_count(match.keys) + + if match.argument.parameter.requires_equals and match.matched_token.startswith("--") and not cli_values: + raise RequiresEqualsError( + argument=match.argument, + keyword=match.matched_token, + ) + + # Consume the appropriate number of tokens + # cm_bounds is either None or (min, max) — guaranteed by _consume_multiple_converter + cm_bounds = match.argument.parameter.consume_multiple + assert cm_bounds is None or isinstance(cm_bounds, tuple) + cm_min, cm_max = cm_bounds if cm_bounds is not None else (0, None) + with suppress(IndexError): + if consume_all and cm_bounds is not None: + for j in itertools.count(): + token = tokens[i + 1 + j] + if not match.argument.parameter.allow_leading_hyphen and is_option_like(token): + break + cli_values.append(token) + skip_next_iterations += 1 + else: + consume_count += tokens_per_element + for j in range(consume_count): + if len(cli_values) == 1 and ( + match.argument._should_attempt_json_dict(cli_values) + or match.argument._should_attempt_json_list(cli_values, match.keys) + ): + tokens_per_element = 1 + # Assume that the contents are json and that we shouldn't + # consume any additional tokens. + break + + token = tokens[i + 1 + j] + if not match.argument.parameter.allow_leading_hyphen and is_option_like(token): + raise MissingArgumentError( + argument=match.argument, + tokens_so_far=cli_values, + keyword=match.matched_token, + ) + cli_values.append(token) + skip_next_iterations += 1 + + if not cli_values: + # No values were consumed after the keyword + if consume_all and cm_bounds is not None: + if cm_min > 0: + # Minimum count not met — treat as missing argument + raise ConsumeMultipleError( + argument=match.argument, + tokens_so_far=cli_values, + keyword=match.matched_token, + min_required=cm_min, + max_allowed=cm_max, + actual_count=0, + ) + # Allow empty iterables (e.g., --urls with no values behaves like --empty-urls) + hint = resolve_optional(match.argument.hint) + empty_container = (get_origin(hint) or hint)() + match.argument.append( + CliToken(keyword=match.matched_token, implicit_value=empty_container, keys=match.keys) + ) + else: + # Non-iterables or consume_multiple=False require at least one value + raise MissingArgumentError( + argument=match.argument, tokens_so_far=cli_values, keyword=match.matched_token + ) + elif len(cli_values) % tokens_per_element: + # For multi-token elements (e.g., tuples), ensure we have complete sets + raise MissingArgumentError( + argument=match.argument, tokens_so_far=cli_values, keyword=match.matched_token + ) + else: + # Check min/max count for consume_multiple + if cm_bounds is not None: + n_elements = len(cli_values) // max(1, tokens_per_element) + if n_elements < cm_min: + raise ConsumeMultipleError( + argument=match.argument, + tokens_so_far=cli_values, + keyword=match.matched_token, + min_required=cm_min, + max_allowed=cm_max, + actual_count=n_elements, + ) + if cm_max is not None and n_elements > cm_max: + raise ConsumeMultipleError( + argument=match.argument, + tokens_so_far=cli_values, + keyword=match.matched_token, + min_required=cm_min, + max_allowed=cm_max, + actual_count=n_elements, + ) + # Normal case: append the consumed values + for index, cli_value in enumerate(cli_values): + match.argument.append( + CliToken(keyword=match.matched_token, value=cli_value, index=index, keys=match.keys) + ) + + # Compute the number of contiguous positional (non-option-like) unused tokens + # before the first gap caused by keyword extraction. This prevents positional-only + # list parameters from consuming tokens that appeared after keyword arguments. + # Only set when a gap is detected; None means no gap (all tokens are contiguous). + contiguous_positional_count: int | None = None + for j in range(1, len(unused_token_original_indices)): + if unused_token_original_indices[j] != unused_token_original_indices[j - 1] + 1: + contiguous_positional_count = j + break + + unused_tokens.extend(positional_only_tokens) + return unused_tokens, contiguous_positional_count + + +def _future_positional_only_token_count(argument_collection: ArgumentCollection, starting_index: int) -> int: + n_tokens_to_leave = 0 + for i in itertools.count(): + try: + argument, _, _ = argument_collection.match(starting_index + i) + except ValueError: + break + if argument.field_info.kind is not POSITIONAL_ONLY: + break + future_tokens_per_element, future_consume_all = argument.token_count() + if future_consume_all: + raise ValueError("Cannot have 2 all-consuming positional arguments.") + n_tokens_to_leave += future_tokens_per_element + return n_tokens_to_leave + + +def _preprocess_positional_tokens(tokens: Sequence[str], end_of_options_delimiter: str) -> list[tuple[str, bool]]: + try: + delimiter_index = tokens.index(end_of_options_delimiter) + return [(t, False) for t in tokens[:delimiter_index]] + [(t, True) for t in tokens[delimiter_index + 1 :]] + except ValueError: # delimiter not found + return [(t, False) for t in tokens] + + +def _parse_pos( + argument_collection: ArgumentCollection, + tokens: list[str], + *, + end_of_options_delimiter: str = "--", + contiguous_positional_count: int | None = None, +) -> list[str]: + """Assign positional tokens to positional parameters. + + Parameters + ---------- + argument_collection: ArgumentCollection + Arguments whose keyword/flag tokens have already been consumed. + tokens: list[str] + Unused tokens from ``_parse_kw_and_flags``. + end_of_options_delimiter: str + Delimiter after which all tokens are forced positional. + contiguous_positional_count: int | None + If not ``None``, the number of leading contiguous positional tokens + that were adjacent in the original CLI input (before keyword extraction + created a gap). Used to cap how many tokens a ``POSITIONAL_ONLY`` + list/iterable parameter may consume, preventing it from greedily + swallowing tokens that originally appeared after keyword arguments. + See ``_parse_kw_and_flags`` for how this value is computed. + """ + prior_positional_or_keyword_supplied_as_keyword_arguments = [] + + if not tokens: + return [] + + tokens_and_force_positional = _preprocess_positional_tokens(tokens, end_of_options_delimiter) + + for i in itertools.count(): + try: + argument, _, _ = argument_collection.match(i) + except ValueError: + break + if argument.field_info.kind is POSITIONAL_OR_KEYWORD: + if argument.tokens and argument.tokens[0].keyword is not None: + prior_positional_or_keyword_supplied_as_keyword_arguments.append(argument) + # Continue in case we hit a VAR_POSITIONAL argument. + continue + if prior_positional_or_keyword_supplied_as_keyword_arguments: + token = tokens[0] + if not argument.parameter.allow_leading_hyphen and is_option_like(token): + # It's more meaningful to interpret the token as an intended option, + # rather than an intended positional value for ``argument``. + raise UnknownOptionError(token=CliToken(value=token), argument_collection=argument_collection) + else: + raise ArgumentOrderError( + argument=argument, + prior_positional_or_keyword_supplied_as_keyword_arguments=prior_positional_or_keyword_supplied_as_keyword_arguments, + token=tokens_and_force_positional[0][0], + ) + + tokens_per_element, consume_all = argument.token_count() + tokens_per_element = max(1, tokens_per_element) + + if consume_all and argument.field_info.kind is POSITIONAL_ONLY: + # POSITIONAL_ONLY parameters can come after a POSITIONAL_ONLY list/iterable. + # This makes it easier to create programs that do something like: + # $ python my-program.py input_folder/*.csv output.csv + + # Need to see how many tokens we need to leave for subsequent POSITIONAL_ONLY parameters. + n_tokens_to_leave = _future_positional_only_token_count(argument_collection, i + 1) + + # Cap at the contiguous positional count to prevent consuming tokens + # that appeared after keyword arguments (issue #763). + if contiguous_positional_count is not None: + n_tokens_to_leave = max( + n_tokens_to_leave, len(tokens_and_force_positional) - contiguous_positional_count + ) + else: + n_tokens_to_leave = 0 + + new_tokens = [] + while (len(tokens_and_force_positional) - n_tokens_to_leave) > 0: + if (len(tokens_and_force_positional) - n_tokens_to_leave) < tokens_per_element: + raise MissingArgumentError( + argument=argument, + tokens_so_far=[x[0] for x in tokens_and_force_positional], + ) + + for index, (token, force_positional) in enumerate(tokens_and_force_positional[:tokens_per_element]): + if not force_positional and not argument.parameter.allow_leading_hyphen and is_option_like(token): + raise UnknownOptionError(token=CliToken(value=token), argument_collection=argument_collection) + new_tokens.append(CliToken(value=token, index=index)) + tokens_and_force_positional = tokens_and_force_positional[tokens_per_element:] + if not consume_all: + break + argument.tokens[:0] = new_tokens # Prepend the new tokens to the argument. + if not tokens_and_force_positional: + break + + return [x[0] for x in tokens_and_force_positional] + + +def _parse_env(argument_collection: ArgumentCollection): + for argument in argument_collection: + if argument.tokens: + # Don't check environment variables for parameters that already have values from CLI. + continue + assert argument.parameter.env_var is not None + for env_var_name in argument.parameter.env_var: + try: + env_var_value = os.environ[env_var_name] + except KeyError: + pass + else: + argument.tokens.append(Token(keyword=env_var_name, value=env_var_value, source="env")) + break + + +def _bind( + argument_collection: ArgumentCollection, + func: Callable, +): + """Bind the mapping to the function signature.""" + bound = inspect.signature(func).bind_partial() + for argument in argument_collection._root_arguments: + if argument.value is not UNSET: + bound.arguments[argument.field_info.name] = argument.value + return bound + + +def _parse_configs(argument_collection: ArgumentCollection, configs): + for config in configs: + # Each ``config`` is a partial that already has apps and commands provided. + config(argument_collection) + + +def _sort_group(argument_collection) -> list[tuple["Group", ArgumentCollection]]: + """Sort groups into "deepest common-root-keys first" order. + + This is imperfect, but probably works sufficiently well for practical use-cases. + """ + out = {} + # Sort alphabetically by group-name to enfroce some determinism. + for i, group in enumerate(sorted(argument_collection.groups, key=lambda x: x.name)): + group_arguments = argument_collection.filter_by(group=group) + common_root_keys = _common_root_keys(group_arguments) + # Add i to key so that we don't get collisions. + out[(common_root_keys, i)] = (group, group_arguments.filter_by(keys_prefix=common_root_keys)) + return [ga for _, ga in sorted(out.items(), reverse=True)] + + +def create_bound_arguments( + func: Callable, + argument_collection: ArgumentCollection, + tokens: list[str], + configs: Iterable[Callable], + *, + end_of_options_delimiter: str = "--", +) -> tuple[inspect.BoundArguments, list[str]]: + """Parse and coerce CLI tokens to match a function's signature. + + Parameters + ---------- + func: Callable + Function. + argument_collection: ArgumentCollection + tokens: list[str] + CLI tokens to parse and coerce to match ``f``'s signature. + configs: Iterable[Callable] + end_of_options_delimiter: str + Everything after this special token is forced to be supplied as a positional argument. + + Returns + ------- + bound: inspect.BoundArguments + The converted and bound positional and keyword arguments for ``f``. + + unused_tokens: list[str] + Remaining tokens that couldn't be matched to ``f``'s signature. + """ + unused_tokens = tokens + + try: + unused_tokens, contiguous_positional_count = _parse_kw_and_flags( + argument_collection, unused_tokens, end_of_options_delimiter=end_of_options_delimiter + ) + unused_tokens = _parse_pos( + argument_collection, + unused_tokens, + end_of_options_delimiter=end_of_options_delimiter, + contiguous_positional_count=contiguous_positional_count, + ) + + _parse_env(argument_collection) + _parse_configs(argument_collection, configs) + + argument_collection._convert() + groups_with_arguments = _sort_group(argument_collection) + try: + for group, group_arguments in groups_with_arguments: + for validator in group.validator: # pyright: ignore + validator(group_arguments) # pyright: ignore[reportOptionalCall] + except (AssertionError, ValueError, TypeError) as e: + raise ValidationError(exception_message=e.args[0] if e.args else "", group=group) from e # pyright: ignore + + for argument in argument_collection: + # if a dict-like argument is missing, raise a MissingArgumentError on the first + # required child (as opposed generically to the root dict-like object). + if argument.parse and argument.field_info.required and not argument.keys and not argument.has_tokens: + raise MissingArgumentError(argument=argument) + + bound = _bind(argument_collection, func) + except CycloptsError as e: + e.root_input_tokens = tokens + e.unused_tokens = unused_tokens + raise + + return bound, unused_tokens diff --git a/.venv/lib/python3.10/site-packages/cyclopts/cli/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..13c474e4bad434a7345eb621a9e466d4bd8429c8 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/cli/__init__.py @@ -0,0 +1,21 @@ +"""Cyclopts CLI implementation.""" + +import cyclopts + +# Create the main CLI app +app = cyclopts.App(name="cyclopts") +app.register_install_completion_command( + help="""\ + Register shell-completion for the cyclopts CLI itself. + """ +) + + +# Explicitly import command modules +from cyclopts.cli import ( + _complete, # noqa: F401 + docs, # noqa: F401 + run, # noqa: F401 +) + +__all__ = ["app"] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/cli/_complete.py b/.venv/lib/python3.10/site-packages/cyclopts/cli/_complete.py new file mode 100644 index 0000000000000000000000000000000000000000..fa50db9cd041369df6ef54575ced730c6d82ed0f --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/cli/_complete.py @@ -0,0 +1,130 @@ +"""Hidden completion helper command for dynamic shell completion.""" + +from pathlib import Path +from typing import TYPE_CHECKING, Annotated + +from cyclopts.cli import app +from cyclopts.loader import load_app_from_script +from cyclopts.parameter import Parameter + +if TYPE_CHECKING: + from cyclopts import App + +MAX_DESCRIPTION_LENGTH = 60 + + +def _extract_short_description(help_text: str | None) -> str: + """Extract first line of help text as a short description. + + Parameters + ---------- + help_text : str | None + Full help text to extract from. + + Returns + ------- + str + First line of help text, or empty string if parsing fails. + """ + from cyclopts.help.help import docstring_parse + + try: + parsed = docstring_parse(help_text, "plaintext") + return parsed.short_description or "" + except Exception: + return str(help_text or "").split("\n")[0] + + +def _print_subcommand_completions(app_obj: "App") -> None: + """Print completions for subcommands of the given app. + + Parameters + ---------- + app_obj : App + Application object to extract subcommands from. + """ + from cyclopts.group_extractors import groups_from_app + + for _, registered_commands in groups_from_app(app_obj): + for registered_command in registered_commands: + if registered_command.app.show: + for name in registered_command.names: + if not name.startswith("-"): + short_desc = _extract_short_description(registered_command.app.help) + + if short_desc: + print(f"{name}:{short_desc}") + else: + print(name) + + +def _print_option_completions(app_obj: "App") -> None: + """Print completions for options of the given app's default command. + + Parameters + ---------- + app_obj : App + Application object to extract options from. + """ + if not app_obj.default_command: + return + + try: + arguments = app_obj.assemble_argument_collection(parse_docstring=True) + for argument in arguments: + if not argument.is_positional_only() and argument.show: + for name in argument.names: + if name.startswith("-"): + desc = argument.parameter.help or "" + desc = desc.split("\n")[0][:MAX_DESCRIPTION_LENGTH] + if desc: + print(f"{name}:{desc}") + else: + print(name) + except Exception: + pass + + +@app.command(name="_complete", show=False) +def complete( + subcommand: Annotated[str, Parameter(allow_leading_hyphen=True)], + script: Annotated[Path, Parameter(allow_leading_hyphen=True)], + *words: Annotated[str, Parameter(allow_leading_hyphen=True)], +) -> None: + """Internal completion helper (hidden from users). + + This command is called by the shell completion system to dynamically + generate completions for the 'run' command by loading the target script + and extracting its available commands and options. + + Parameters + ---------- + subcommand : str + The cyclopts subcommand being completed (e.g., "run"). + script : Path + Python script path to load for completion extraction. + words : str + Current command line words for context-aware completion. + """ + if subcommand != "run": + return + + try: + app_obj, _ = load_app_from_script(script) + except (ImportError, SyntaxError, AttributeError, FileNotFoundError): + return + + words_list = list(words) if words else [] + + # Complete from root app if no words or only empty string (initial completion) + if not words_list or (len(words_list) == 1 and not words_list[0]): + _print_subcommand_completions(app_obj) + _print_option_completions(app_obj) + else: + try: + _, execution_path, _ = app_obj.parse_commands(words_list) + current_app = execution_path[-1] + _print_subcommand_completions(current_app) + _print_option_completions(current_app) + except Exception: + pass diff --git a/.venv/lib/python3.10/site-packages/cyclopts/cli/docs.py b/.venv/lib/python3.10/site-packages/cyclopts/cli/docs.py new file mode 100644 index 0000000000000000000000000000000000000000..a858d2cdaea0b171b87e03f638935294f77a84c1 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/cli/docs.py @@ -0,0 +1,111 @@ +"""Generate documentation for Cyclopts applications.""" + +from pathlib import Path +from typing import Annotated + +from cyclopts.cli import app +from cyclopts.docs.types import ( + FORMAT_ALIASES, + DocFormat, + normalize_format, +) +from cyclopts.group import Group +from cyclopts.loader import load_app_from_script +from cyclopts.parameter import Parameter +from cyclopts.utils import UNSET + + +def _format_group_validator(argument_collection): + format_arg = argument_collection.get("--format") + output_arg = argument_collection.get("--output") + + if format_arg.value is UNSET: + if output_arg.value is UNSET: + raise ValueError('"--format" must be specified when output path is not provided.') + + if not output_arg.value or not hasattr(output_arg.value, "suffix"): + raise ValueError('"--output" must be a valid file path when format is not specified.') + + suffix = output_arg.value.suffix.lower() + + if not suffix: + raise ValueError( + "Output file must have an extension to infer format (e.g., .md, .html, .rst). " + 'Please specify "--format" explicitly or add an extension to the output file.' + ) + + # Strip the leading period from suffix to look up in FORMAT_ALIASES + suffix_key = suffix.lstrip(".") + + if not suffix_key: + raise ValueError( + "Invalid file extension. Output file must have a valid extension after the period. " + 'Please specify "--format" explicitly.' + ) + + inferred_format = FORMAT_ALIASES.get(suffix_key) + + if inferred_format is None: + supported_extensions = [f".{ext}" for ext in FORMAT_ALIASES.keys() if len(ext) <= 4] + raise ValueError( + f'Cannot infer format from output extension "{suffix}". ' + f"Supported extensions: {', '.join(sorted(set(supported_extensions)))}. " + f'Please specify "--format" explicitly.' + ) + + format_arg.value = inferred_format + + +format_group = Group(validator=_format_group_validator) + + +@app.command(default_parameter=Parameter(negative="")) +def generate_docs( + script: str, + output: Annotated[Path | None, Parameter(alias="-o", group=format_group)] = None, + *, + format: Annotated[ + DocFormat | None, + Parameter(alias="-f", group=format_group), + ] = None, + include_hidden: bool = False, + heading_level: int = 1, + usage_name: str | None = None, +): + """Generate documentation for a Cyclopts application. + + Parameters + ---------- + script : str + Python script path, optionally with ``':app_object'`` notation to specify + the App object. If not specified, will search for App objects in the + script's global namespace. + output : Optional[Path] + Output file path. If not specified, prints to stdout. + format : Optional[DocFormat] + Output format for documentation. If not specified, inferred from output + file extension. + include_hidden : bool + Include hidden commands in documentation. + heading_level : int + Starting heading level for markdown format. + usage_name : Optional[str] + Replace the app name shown in ``Usage:`` lines with this string. For + example, ``"uv run cli"`` for an app whose runtime name is ``"cli"``. + Headings and anchors are unaffected. Default is None. + """ + if format is None: # Handled by _format_group_validator + raise ValueError("Must specify format.") + format = normalize_format(format) + app_obj, _ = load_app_from_script(script) + docs_content = app_obj.generate_docs( + output_format=format, + include_hidden=include_hidden, + heading_level=heading_level, + usage_name=usage_name, + ) + + if output: + output.write_text(docs_content) + else: + print(docs_content) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/cli/run.py b/.venv/lib/python3.10/site-packages/cyclopts/cli/run.py new file mode 100644 index 0000000000000000000000000000000000000000..2eeba2965fdd4757406a85498f6709a0aefee4f6 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/cli/run.py @@ -0,0 +1,46 @@ +"""Run Cyclopts applications from Python scripts.""" + +from pathlib import Path +from typing import Annotated + +from cyclopts.cli import app +from cyclopts.loader import load_app_from_script +from cyclopts.parameter import Parameter + + +@app.command(help_flags="") +def run( + script: Annotated[ + Path, + Parameter(allow_leading_hyphen=True), + ], + /, + *args: Annotated[str, Parameter(allow_leading_hyphen=True)], +): + """Run a Cyclopts application from a Python script with dynamic shell completion. + + All arguments after the script path are passed to the loaded application. + + Shell completion is available. Run once to install (persistent): + ``cyclopts --install-completion`` + + Parameters + ---------- + script : str + Python script path with optional ':app_object' notation. + args : str + Arguments to pass to the loaded application. + + Examples + -------- + Run a script: + cyclopts run myapp.py --verbose foo bar + + Specify app object: + cyclopts run myapp.py:app --help + """ + if str(script) in app.help_flags: + app.help_print() + return + app_obj, _ = load_app_from_script(script) + return app_obj(args) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/command_spec.py b/.venv/lib/python3.10/site-packages/cyclopts/command_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..86b642003f4dcd73da33b6ccc21bfd9ef33a0939 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/command_spec.py @@ -0,0 +1,174 @@ +"""Lazy-loadable command specification for deferred imports.""" + +import importlib +from itertools import chain +from typing import TYPE_CHECKING, Any + +from attrs import Factory, define, field + +if TYPE_CHECKING: + from cyclopts.core import App + from cyclopts.group import Group + + +@define +class CommandSpec: + """Specification for a command that will be lazily loaded on first access. + + This allows registering commands via import path strings (e.g., "myapp.commands:create") + without importing them until they're actually used, improving CLI startup time. + + Parameters + ---------- + import_path : str + Import path in the format "module.path:attribute_name". + The attribute should be either a function or an App instance. + name : str | tuple[str, ...] | None + CLI command name. If None, will be derived from the attribute name via name_transform. + For function imports: used as the name of the wrapper App. + For App imports: must match the App's internal name, or ValueError is raised at resolution. + app_kwargs : dict + Keyword arguments to pass to App() if wrapping a function. + Raises ValueError if used with App imports (Apps should be configured in their own definition). + + Examples + -------- + >>> from cyclopts import App + >>> app = App() + >>> # Lazy load - doesn't import myapp.commands until "create" is executed + >>> app.command("myapp.commands:create_user", name="create") + >>> app() + """ + + import_path: str + name: str | tuple[str, ...] | None = None + app_kwargs: dict[str, Any] = Factory(dict) + help: str | None = None + sort_key: Any = None + group: "Group | str | tuple[Group | str, ...] | None" = None + _show: bool | None = field(default=None, alias="show") + + @property + def show(self) -> bool: + if self._show is None: + return True + return self._show + + _resolved: "App | None" = field(init=False, default=None, repr=False) + + def resolve(self, parent_app: "App") -> "App": + """Import and resolve the command on first access. + + Parameters + ---------- + parent_app : App + Parent app to inherit defaults from (help_flags, version_flags, groups). + Required to match the behavior of direct command registration. + + Returns + ------- + App + The resolved App instance, either imported directly or wrapping a function. + + Raises + ------ + ValueError + If import_path is not in the correct format "module.path:attribute_name". + ImportError + If the module cannot be imported. + AttributeError + If the attribute doesn't exist in the module. + """ + if self._resolved is not None: + return self._resolved + + # Parse import path + module_path, _, attr_name = self.import_path.rpartition(":") + if not module_path or not attr_name: + raise ValueError( + f"Invalid import path: {self.import_path!r}. Expected format: 'module.path:attribute_name'" + ) + + # Import the module and get the attribute + try: + module = importlib.import_module(module_path) + except ImportError as e: + raise ImportError(f"Cannot import module {module_path!r} from {self.import_path!r}") from e + + try: + target = getattr(module, attr_name) + except AttributeError as e: + raise AttributeError( + f"Module {module_path!r} has no attribute {attr_name!r} (from import path {self.import_path!r})" + ) from e + + # Wrap in App if needed + from cyclopts.core import App + + if isinstance(target, App): + # Validate that no kwargs were provided for App imports + if self.app_kwargs: + raise ValueError( + f"Cannot apply configuration to imported App. " + f"Import path {self.import_path!r} resolves to an App, " + f"but kwargs were specified: {self.app_kwargs!r}. " + f"Configure the App in its definition instead." + ) + + # Validate that the App's name matches the expected CLI command name + # The name used for CLI registration is stored in self.name + if self.name is not None and target.name[0] != self.name: + raise ValueError( + f"Imported App name mismatch. " + f"Import path {self.import_path!r} resolves to an App with name={target.name[0]!r}, " + f"but it was registered with CLI command name={self.name!r}. " + f"Either use app.command('{self.import_path}', name='{target.name[0]}') " + f"or change the App's name to match." + ) + + # Copy parent groups if not set (matches direct App registration behavior) + from cyclopts.core import _apply_parent_defaults_to_app + + _apply_parent_defaults_to_app(target, parent_app) + + self._resolved = target + else: + # It's a function - wrap it in an App with parent defaults + # Match the behavior of direct function registration + app_kwargs = dict(self.app_kwargs) # Copy to avoid mutating + + from cyclopts.core import _apply_parent_groups_to_kwargs + + app_kwargs.setdefault("help_flags", parent_app.help_flags) + app_kwargs.setdefault("version_flags", parent_app.version_flags) + if "version" not in app_kwargs and parent_app.version is not None: + app_kwargs["version"] = parent_app.version + + _apply_parent_groups_to_kwargs(app_kwargs, parent_app) + + self._resolved = App(name=self.name, **app_kwargs) + self._resolved.default(target) + + # Apply registration-time overrides to the resolved App + if self.help is not None: + self._resolved.help = self.help + if self.sort_key is not None: + self._resolved.sort_key = self.sort_key + if self.group is not None: + self._resolved.group = self.group + if self._show is not None: + self._resolved.show = self._show + if self._resolved._name_transform is None: + self._resolved.name_transform = parent_app.name_transform + + # Hide help and version flags from subapp help output + # This matches the behavior of direct App/function registration in core.py + for flag in chain(self._resolved.help_flags, self._resolved.version_flags): + self._resolved[flag].show = False + + return self._resolved + + @property + def is_resolved(self) -> bool: + """Check if this command has been imported and resolved yet.""" + return self._resolved is not None diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10b6ad44ff21f9245381bf8c5fa9fce872bc448f --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/__init__.py @@ -0,0 +1,11 @@ +"""Shell completion generation for Cyclopts applications.""" + +from cyclopts.completion.detect import ShellDetectionError, detect_shell +from cyclopts.completion.install import add_to_rc_file, get_default_completion_path + +__all__ = [ + "detect_shell", + "ShellDetectionError", + "get_default_completion_path", + "add_to_rc_file", +] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/_base.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..79d9ab1f60abeaf0d25d706ac4538b7109aad3e9 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/_base.py @@ -0,0 +1,216 @@ +"""Shared shell completion infrastructure. + +Provides data extraction, type analysis, and text processing utilities. +""" + +import os +import re +import warnings +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, Any, get_args, get_origin + +from cyclopts.annotations import ITERABLE_TYPES, is_annotated, is_union +from cyclopts.argument import ArgumentCollection +from cyclopts.exceptions import CycloptsError +from cyclopts.group_extractors import RegisteredCommand, groups_from_app +from cyclopts.utils import frozen, is_class_and_subclass + +if TYPE_CHECKING: + from cyclopts import App + + +class CompletionAction(Enum): + """Shell-agnostic completion action types.""" + + NONE = "none" + FILES = "files" + DIRECTORIES = "directories" + + +@frozen +class CompletionData: + """Completion data for a command path.""" + + arguments: "ArgumentCollection" + commands: list[RegisteredCommand] + help_format: str + + +def extract_completion_data(app: "App") -> dict[tuple[str, ...], CompletionData]: + """Recursively extract completion data for app and all subcommands. + + Parameters + ---------- + app : App + The Cyclopts application to extract completion data from. + + Returns + ------- + dict[tuple[str, ...], CompletionData] + Mapping from command path tuples to their completion data. + """ + completion_data: dict[tuple[str, ...], CompletionData] = {} + + def _extract(command_path: tuple[str, ...] = ()): + """Recursively extract completion data for command and subcommands.""" + try: + _, execution_path, _ = app.parse_commands(list(command_path)) + command_app = execution_path[-1] + except (CycloptsError, ValueError, TypeError) as e: + if os.environ.get("CYCLOPTS_COMPLETION_DEBUG"): + raise + warnings.warn(f"Failed to extract completion data for command path {command_path!r}: {e}", stacklevel=2) + help_format = app.app_stack.resolve("help_format", fallback="markdown") + completion_data[command_path] = CompletionData( + arguments=ArgumentCollection(), commands=[], help_format=help_format + ) + return + + arguments = ArgumentCollection() + apps_for_params = app._get_resolution_context(execution_path) + with app.app_stack(execution_path): + for subapp in apps_for_params: + if subapp.default_command: + app_arguments = subapp.assemble_argument_collection(parse_docstring=True) + arguments.extend(app_arguments) + + commands = [] + for group, registered_commands in groups_from_app(command_app, resolve_lazy=True): + if group.show: + for registered_command in registered_commands: + if registered_command.app.show and registered_command not in commands: + commands.append(registered_command) + + help_format = command_app.app_stack.resolve("help_format", fallback="markdown") + + completion_data[command_path] = CompletionData(arguments=arguments, commands=commands, help_format=help_format) + + for registered_command in commands: + for cmd_name in registered_command.names: + if not cmd_name.startswith("-"): + _extract(command_path + (cmd_name,)) + + _extract() + return completion_data + + +def get_completion_action(type_hint: Any) -> CompletionAction: + """Get completion action from type hint. + + Parameters + ---------- + type_hint : Any + Type annotation. + + Returns + ------- + CompletionAction + Completion action for type. + """ + if is_annotated(type_hint): + return get_completion_action(get_args(type_hint)[0]) + + if is_union(type_hint): + for arg in get_args(type_hint): + if arg is not type(None): + action = get_completion_action(arg) + if action != CompletionAction.NONE: + return action + return CompletionAction.NONE + + origin = get_origin(type_hint) + + # For collection types, unwrap to get element type + if is_class_and_subclass(origin, tuple(ITERABLE_TYPES)): + args = get_args(type_hint) + if args and len(args) >= 1: + # list[Path], set[Path], tuple[Path, ...] -> check first arg + return get_completion_action(args[0]) + + target_type = origin or type_hint + + if target_type is Path or is_class_and_subclass(target_type, Path): + return CompletionAction.FILES + + return CompletionAction.NONE + + +def clean_choice_text(text: str) -> str: + """Clean choice text without shell-specific escaping. + + Parameters + ---------- + text : str + Raw choice text. + + Returns + ------- + str + Cleaned text (not shell-escaped). + """ + text = re.sub(r"[\x00-\x1f\x7f]", "", text) + text = re.sub(r"\s+", " ", text).strip() + return text + + +def escape_for_shell_pattern(name: str, chars: str = "*?[]") -> str: + """Escape glob/pattern characters for shell case patterns. + + Both bash and zsh case patterns treat glob characters as special even inside + quotes. This function escapes them with backslashes for literal matching. + + Parameters + ---------- + name : str + String to escape. + chars : str + Characters to escape. Default covers basic glob chars. + For zsh, also pass "()|" for extended patterns. + + Returns + ------- + str + Escaped string safe for shell case patterns. + """ + # Escape backslashes first to avoid double-escaping + result = name.replace("\\", "\\\\") + for char in chars: + result = result.replace(char, f"\\{char}") + return result + + +def strip_markup(text: str, format: str = "markdown", max_length: int = 80) -> str: + """Strip markup and render to plain text for shell completions. + + Converts formatted text (markdown/RST/rich) to plain text suitable for + shell completion descriptions. Removes control characters, normalizes + whitespace, and truncates if needed. + + Parameters + ---------- + text : str + Text with markup. + format : str + Markup format: "markdown", "rst", "rich", or "plaintext". + max_length : int + Maximum length before truncation. + + Returns + ------- + str + Plain text (not shell-escaped). + """ + from cyclopts._markup import extract_text + from cyclopts.help.inline_text import InlineText + + inline = InlineText.from_format(text, format=format) + text = extract_text(inline) + + text = re.sub(r"[\x00-\x1f\x7f]", "", text) + text = re.sub(r"\s+", " ", text).strip() + + if len(text) > max_length: + text = text[: max_length - 1] + "…" + + return text diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/bash.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/bash.py new file mode 100644 index 0000000000000000000000000000000000000000..f587a1980d200f13e122a70ebbd75c5de0aedd88 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/bash.py @@ -0,0 +1,580 @@ +"""Bash completion script generator. + +Generates static bash completion scripts using COMPREPLY and compgen. +Targets bash 3.2+ with no external dependencies. +""" + +import re +from typing import TYPE_CHECKING + +from cyclopts.annotations import is_iterable_type +from cyclopts.completion._base import ( + CompletionAction, + CompletionData, + clean_choice_text, + escape_for_shell_pattern, + extract_completion_data, + get_completion_action, +) + +if TYPE_CHECKING: + from cyclopts import App + + +def generate_completion_script(app: "App", prog_name: str) -> str: + """Generate bash completion script. + + Parameters + ---------- + app : App + The Cyclopts application to generate completion for. + prog_name : str + Program name (alphanumeric with hyphens/underscores). + + Returns + ------- + str + Complete bash completion script. + + Raises + ------ + ValueError + If prog_name contains invalid characters. + """ + if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name): + raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.") + + func_name = prog_name.replace("-", "_") + completion_data = extract_completion_data(app) + + lines = [ + f"# Bash completion for {prog_name}", + "# Generated by Cyclopts", + "", + f"_{func_name}() {{", + " local cur prev", + "", + ] + + lines.extend(_generate_completion_function_body(completion_data, prog_name, app)) + + lines.extend(["}"]) + lines.append("") + lines.append(f"complete -F _{func_name} {prog_name}") + lines.append("") + + return "\n".join(lines) + + +def _escape_bash_choice(choice: str) -> str: + r"""Escape single quotes for bash strings.""" + return choice.replace("'", "'\\''") + + +def _escape_bash_description(text: str) -> str: + r"""Escape description text for bash comments.""" + text = text.replace("\n", " ") + text = text.replace("\r", " ") + return text + + +def _map_completion_action_to_bash(action: CompletionAction) -> str: + """Map completion action to bash compgen flags. + + Parameters + ---------- + action : CompletionAction + Completion action type. + + Returns + ------- + str + Compgen flags ("-f", "-d", or ""). + """ + if action == CompletionAction.FILES: + return "-f" + elif action == CompletionAction.DIRECTORIES: + return "-d" + return "" + + +def _generate_completion_function_body( + completion_data: dict[tuple[str, ...], CompletionData], + prog_name: str, + app: "App", +) -> list[str]: + """Generate the body of the bash completion function. + + Parameters + ---------- + completion_data : dict + All extracted completion data. + prog_name : str + Program name. + app : App + Application instance. + + Returns + ------- + list[str] + Lines of bash code for the completion function body. + """ + lines = [] + lines.append(' cur="${COMP_WORDS[COMP_CWORD]}"') + lines.append(' prev="${COMP_WORDS[COMP_CWORD-1]}"') + lines.append("") + + lines.extend(_generate_command_path_detection(completion_data)) + lines.append("") + + lines.extend(_generate_completion_logic(completion_data, prog_name, app)) + + return lines + + +def _generate_command_path_detection(completion_data: dict[tuple[str, ...], CompletionData]) -> list[str]: + """Generate bash code to detect the current command path. + + This function generates two passes through COMP_WORDS: + 1. First pass builds cmd_path by identifying valid command names + 2. Second pass counts positionals (non-option words after the command path) + + The two-pass approach is necessary because we need to know the full command + path length before we can correctly identify which words are positionals. + + Note: all_commands is built globally across all command levels. If a positional + argument value happens to match a command name from a different level, it could + be incorrectly classified (though this represents poor CLI design). + + Parameters + ---------- + completion_data : dict + All extracted completion data. + + Returns + ------- + list[str] + Lines of bash code for command path detection. + """ + options_with_values = set() + all_commands = set() + + for data in completion_data.values(): + for argument in data.arguments: + if not argument.is_flag() and argument.parameter.name: + for name in argument.parameter.name: + if name.startswith("-"): + options_with_values.add(name) + + for registered_command in data.commands: + for cmd_name in registered_command.names: + if not cmd_name.startswith("-"): + all_commands.add(cmd_name) + + lines = [] + lines.append(" # Build list of options that take values (to skip their arguments)") + if options_with_values: + escaped_opts = [_escape_bash_choice(opt) for opt in sorted(options_with_values)] + opts_str = " ".join(escaped_opts) + lines.append(f" local options_with_values='{opts_str}'") + else: + lines.append(" local options_with_values=''") + + lines.append("") + lines.append(" # Build list of all valid command names (to distinguish from positionals)") + if all_commands: + escaped_cmds = [_escape_bash_choice(cmd) for cmd in sorted(all_commands)] + cmds_str = " ".join(escaped_cmds) + lines.append(f" local all_commands='{cmds_str}'") + else: + lines.append(" local all_commands=''") + + lines.append("") + lines.append(" # Detect command path by collecting valid command words only") + lines.append(" local -a cmd_path=()") + lines.append(" local i skip_next=0") + lines.append(" for ((i=1; i list[str]: + """Generate the main completion logic using case statements. + + Parameters + ---------- + completion_data : dict + All extracted completion data. + prog_name : str + Program name. + app : App + Application instance. + + Returns + ------- + list[str] + Lines of bash code for completion logic. + """ + lines = [] + + help_flags = tuple(app.help_flags) if app.help_flags else () + version_flags = tuple(app.version_flags) if app.version_flags else () + + lines.append(" # Determine command level and generate completions") + lines.append(' case "${#cmd_path[@]}" in') + + max_depth = max(len(path) for path in completion_data.keys()) + for depth in range(max_depth + 1): + relevant_paths = [path for path in completion_data.keys() if len(path) == depth] + if not relevant_paths: + continue + + lines.append(f" {depth})") + + if depth == 0: + lines.extend(_generate_completions_for_path(completion_data, (), " ", help_flags, version_flags)) + else: + lines.append(' case "${cmd_path[@]}" in') + for path in sorted(relevant_paths): + # Escape glob characters in command names for case pattern matching + escaped_path = [escape_for_shell_pattern(cmd) for cmd in path] + path_str = " ".join(escaped_path) + lines.append(f' "{path_str}")') + lines.extend( + _generate_completions_for_path(completion_data, path, " ", help_flags, version_flags) + ) + lines.append(" ;;") + lines.append(" *)") + lines.append(" ;;") + lines.append(" esac") + + lines.append(" ;;") + + lines.append(" *)") + lines.append(" ;;") + lines.append(" esac") + + return lines + + +def _generate_completions_for_path( + completion_data: dict[tuple[str, ...], CompletionData], + command_path: tuple[str, ...], + indent: str, + help_flags: tuple[str, ...], + version_flags: tuple[str, ...], +) -> list[str]: + """Generate completions for a specific command path. + + Parameters + ---------- + completion_data : dict + All extracted completion data. + command_path : tuple[str, ...] + Current command path. + indent : str + Indentation string. + help_flags : tuple[str, ...] + Help flag names. + version_flags : tuple[str, ...] + Version flag names. + + Returns + ------- + list[str] + Lines of bash code for completions at this command path. + """ + if command_path not in completion_data: + return [f"{indent}COMPREPLY=()"] + + data = completion_data[command_path] + lines = [] + + options = [] + keyword_args = [arg for arg in data.arguments if not arg.is_positional_only() and arg.show] + + for argument in keyword_args: + for name in argument.parameter.name or []: + if name.startswith("-"): + options.append(name) + + for name in argument.negatives: + if name.startswith("-"): + options.append(name) + + flag_commands = [] + for registered_command in data.commands: + for name in registered_command.names: + if name.startswith("-"): + flag_commands.append(name) + + for flag in help_flags: + if flag.startswith("-") and flag not in options and flag not in flag_commands: + options.append(flag) + + for flag in version_flags: + if flag.startswith("-") and flag not in options and flag not in flag_commands: + options.append(flag) + + options.extend(flag_commands) + + commands = [] + for registered_command in data.commands: + for cmd_name in registered_command.names: + if not cmd_name.startswith("-"): + commands.append(cmd_name) + + positional_args = [arg for arg in data.arguments if arg.index is not None and arg.show] + positional_args.sort(key=lambda a: a.index if a.index is not None else 0) + + lines.append(f"{indent}if [[ ${{cur}} == -* ]]; then") + + if options: + escaped_options = [_escape_bash_choice(opt) for opt in options] + options_str = " ".join(escaped_options) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{options_str}' -- \"${{cur}}\") )") + else: + lines.append(f"{indent} COMPREPLY=()") + + lines.append(f"{indent}else") + + needs_value_completion = _check_if_prev_needs_value(data.arguments) + + if needs_value_completion: + value_completion_lines = _generate_value_completion_for_prev( + data.arguments, commands, positional_args, f"{indent} " + ) + lines.extend(value_completion_lines) + elif commands: + escaped_commands = [_escape_bash_choice(cmd) for cmd in commands] + commands_str = " ".join(escaped_commands) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )") + elif positional_args: + lines.extend(_generate_positional_completion(positional_args, f"{indent} ")) + else: + lines.append(f"{indent} COMPREPLY=()") + + lines.append(f"{indent}fi") + + return lines + + +def _generate_positional_completion(positional_args, indent: str) -> list[str]: + """Generate position-aware positional argument completion. + + Parameters + ---------- + positional_args : list + List of positional arguments sorted by index. + indent : str + Indentation string. + + Returns + ------- + list[str] + Lines of bash code for position-aware positional completion. + """ + lines = [] + + if len(positional_args) == 1: + # Single positional - simple case + choices = positional_args[0].get_choices(force=True) + action = get_completion_action(positional_args[0].hint) + if choices: + escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + lines.append(f"{indent}COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )") + else: + compgen_flag = _map_completion_action_to_bash(action) + if compgen_flag: + lines.append(f'{indent}COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )') + else: + lines.append(f"{indent}COMPREPLY=()") + else: + # Multiple positionals - use case statement for position-aware completion + lines.append(f"{indent}case ${{positional_count}} in") + + for idx, argument in enumerate(positional_args): + choices = argument.get_choices(force=True) + action = get_completion_action(argument.hint) + lines.append(f"{indent} {idx})") + if choices: + escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )") + else: + compgen_flag = _map_completion_action_to_bash(action) + if compgen_flag: + lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )') + else: + lines.append(f"{indent} COMPREPLY=()") + lines.append(f"{indent} ;;") + + # Default case for positions beyond defined positionals + # If any positional is a collection type, use it as the default + iterable_arg = next((arg for arg in positional_args if is_iterable_type(arg.hint)), None) + lines.append(f"{indent} *)") + if iterable_arg: + choices = iterable_arg.get_choices(force=True) + action = get_completion_action(iterable_arg.hint) + if choices: + escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )") + else: + compgen_flag = _map_completion_action_to_bash(action) + if compgen_flag: + lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )') + else: + lines.append(f"{indent} COMPREPLY=()") + else: + lines.append(f"{indent} COMPREPLY=()") + lines.append(f"{indent} ;;") + lines.append(f"{indent}esac") + + return lines + + +def _check_if_prev_needs_value(arguments) -> bool: + """Check if any options take values, requiring prev-word completion logic. + + Parameters + ---------- + arguments : ArgumentCollection + Arguments to check. + + Returns + ------- + bool + True if any option (starts with -) takes a value (is not a flag). + """ + for argument in arguments: + if not argument.is_flag(): + for name in argument.parameter.name or []: + if name.startswith("-"): + return True + return False + + +def _generate_value_completion_for_prev(arguments, commands: list[str], positional_args, indent: str) -> list[str]: + """Generate value completion based on previous word. + + Parameters + ---------- + arguments : ArgumentCollection + Arguments with potential values. + commands : list[str] + Available commands at this level. + positional_args : list + List of positional arguments sorted by index. + indent : str + Indentation string. + + Returns + ------- + list[str] + Lines of bash code for value completion. + """ + lines = [] + lines.append(f'{indent}case "${{prev}}" in') + + has_cases = False + for argument in arguments: + if argument.is_flag(): + continue + + names = [name for name in (argument.parameter.name or []) if name.startswith("-")] + if not names: + continue + + has_cases = True + choices = argument.get_choices(force=True) + action = get_completion_action(argument.hint) + + for name in names: + lines.append(f"{indent} {name})") + + if choices: + escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )") + else: + compgen_flag = _map_completion_action_to_bash(action) + if compgen_flag: + lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )') + else: + lines.append(f"{indent} COMPREPLY=()") + + lines.append(f"{indent} ;;") + + if has_cases: + lines.append(f"{indent} *)") + if commands: + escaped_commands = [_escape_bash_choice(cmd) for cmd in commands] + commands_str = " ".join(escaped_commands) + lines.append(f"{indent} COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )") + elif positional_args: + lines.extend(_generate_positional_completion(positional_args, f"{indent} ")) + else: + lines.append(f"{indent} COMPREPLY=()") + lines.append(f"{indent} ;;") + lines.append(f"{indent}esac") + else: + lines = [] + if commands: + escaped_commands = [_escape_bash_choice(cmd) for cmd in commands] + commands_str = " ".join(escaped_commands) + lines.append(f"{indent}COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )") + elif positional_args: + lines.extend(_generate_positional_completion(positional_args, indent)) + else: + lines.append(f"{indent}COMPREPLY=()") + + return lines diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/detect.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..db02ebe1f9ebd9e3594eac4512e9736cd0a20d9d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/detect.py @@ -0,0 +1,90 @@ +"""Shell detection utilities for completion generation. + +This module provides functionality to detect the current shell type by inspecting +environment variables. This is useful for dynamically generating appropriate completion +scripts for different shell environments. +""" + +import os +import subprocess +from pathlib import Path +from typing import Literal + + +class ShellDetectionError(Exception): + """Raised when the shell type cannot be detected.""" + + +def _extract_shell_name(shell_string: str) -> Literal["zsh", "bash", "fish"] | None: + """Extract shell name from a string (path or process name). + + Parameters + ---------- + shell_string : str + String that may contain a shell name (e.g., "/bin/bash", "zsh", "-bash"). + + Returns + ------- + Literal["zsh", "bash", "fish"] | None + The detected shell type, or None if not recognized. + """ + shell_lower = shell_string.lower() + if "zsh" in shell_lower: + return "zsh" + elif "bash" in shell_lower: + return "bash" + elif "fish" in shell_lower: + return "fish" + return None + + +def detect_shell() -> Literal["zsh", "bash", "fish"]: + """Detect the current shell type using multiple detection methods. + + Returns + ------- + Literal["zsh", "bash", "fish"] + The detected shell type. + + Raises + ------ + ShellDetectionError + If the shell type cannot be determined from any detection method. + + Examples + -------- + >>> shell = detect_shell() # doctest: +SKIP + >>> print(f"Detected shell: {shell}") # doctest: +SKIP + Detected shell: bash + """ + if os.environ.get("ZSH_VERSION"): + return "zsh" + elif os.environ.get("BASH_VERSION"): + return "bash" + elif os.environ.get("FISH_VERSION"): + return "fish" + + try: + ppid = os.getppid() + result = subprocess.run( + ["ps", "-p", str(ppid), "-o", "comm="], + capture_output=True, + text=True, + timeout=1, + ) + if result.returncode == 0 and result.stdout: + parent_process = result.stdout.strip() + shell = _extract_shell_name(parent_process) + if shell: + return shell + except (subprocess.SubprocessError, FileNotFoundError, OSError): + pass + + shell_path = os.environ.get("SHELL", "") + if shell_path: + shell_name = Path(shell_path).name + shell = _extract_shell_name(shell_name) + if shell: + return shell + + raise ShellDetectionError("Unable to detect shell type.") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/fish.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/fish.py new file mode 100644 index 0000000000000000000000000000000000000000..6113251ce8bcc2c34af5e2e1ff18a91e68e0c716 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/fish.py @@ -0,0 +1,543 @@ +"""Fish completion script generator. + +Generates static fish completion scripts using `complete -c COMMAND` statements. +Completions auto-load from ~/.config/fish/completions/PROGNAME.fish. +""" + +import re +from typing import TYPE_CHECKING + +from cyclopts.completion._base import ( + CompletionAction, + CompletionData, + clean_choice_text, + extract_completion_data, + get_completion_action, + strip_markup, +) + +if TYPE_CHECKING: + from cyclopts import App + from cyclopts.command_spec import CommandSpec + + +def generate_completion_script(app: "App", prog_name: str) -> str: + """Generate fish completion script. + + Parameters + ---------- + app : App + The Cyclopts application to generate completion for. + prog_name : str + Program name for completion (alphanumeric with hyphens/underscores). + + Returns + ------- + str + Complete fish completion script. + + Raises + ------ + ValueError + If prog_name contains invalid characters. + """ + if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name): + raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.") + + completion_data = extract_completion_data(app) + + lines = [ + f"# Fish completion for {prog_name}", + "# Generated by Cyclopts", + "", + ] + + has_nested_commands = any(len(path) > 0 for path in completion_data.keys()) + if has_nested_commands: + lines.extend(_generate_helper_functions(prog_name, completion_data)) + lines.append("") + + help_flags = tuple(app.help_flags) if app.help_flags else () + version_flags = tuple(app.version_flags) if app.version_flags else () + + lines.extend(_generate_completions(completion_data, prog_name, help_flags, version_flags)) + + return "\n".join(lines) + "\n" + + +def _escape_fish_string(text: str) -> str: + r"""Escape single quotes for fish strings.""" + return text.replace("'", r"'\''") + + +def _escape_fish_description(text: str) -> str: + """Escape description text for fish.""" + text = text.replace("\n", " ") + text = text.replace("\r", " ") + return _escape_fish_string(text) + + +def _generate_helper_functions( + prog_name: str, + completion_data: dict[tuple[str, ...], CompletionData], +) -> list[str]: + """Generate helper function for command path detection. + + Parameters + ---------- + prog_name : str + Program name. + completion_data : dict + Completion data used to identify options that take values. + + Returns + ------- + list[str] + Lines defining the helper function. + """ + options_with_values = set() + for data in completion_data.values(): + for argument in data.arguments: + if not argument.is_flag() and argument.parameter.name: + for name in argument.parameter.name: + if name.startswith("-"): + options_with_values.add(name) + + func_name = f"__fish_{prog_name}_using_command" + lines = [ + "# Helper function to check exact command path sequence", + f"function {func_name}", + " set -l cmd (commandline -opc)", + " set -l subcommands", + ] + + if options_with_values: + escaped_opts = " ".join(_escape_fish_string(opt) for opt in sorted(options_with_values)) + lines.append(f" set -l options_with_values '{escaped_opts}'") + else: + lines.append(" set -l options_with_values ''") + + lines.extend( + [ + " set -l skip_next 0", + " # Extract non-option words (commands) from command line", + " for i in (seq 2 (count $cmd))", + " set -l word $cmd[$i]", + " if test $skip_next -eq 1", + " set skip_next 0", + " continue", + " end", + " if string match -qr -- '^-' $word", + " # Check if this option takes a value (exact match)", + ' if string match -q -- "* $word *" " $options_with_values "', + " set skip_next 1", + " end", + " else", + " # Non-option word is a command", + " set -a subcommands $word", + " end", + " end", + " # Check if subcommand sequence matches expected path", + " if test (count $subcommands) -ne (count $argv)", + " return 1", + " end", + " for i in (seq 1 (count $argv))", + " if test $subcommands[$i] != $argv[$i]", + " return 1", + " end", + " end", + " return 0", + "end", + ] + ) + return lines + + +def _map_completion_action_to_fish(action: CompletionAction) -> str: + """Map completion action to fish flags. + + Parameters + ---------- + action : CompletionAction + Completion action type. + + Returns + ------- + str + Fish completion flags ("-r -F" for files, "-r -a '(...)'" for directories, "" otherwise). + """ + if action == CompletionAction.FILES: + return "-r -F" + if action == CompletionAction.DIRECTORIES: + return "-r -a '(__fish_complete_directories)'" + return "" + + +def _generate_completions( + completion_data: dict[tuple[str, ...], CompletionData], + prog_name: str, + help_flags: tuple[str, ...], + version_flags: tuple[str, ...], +) -> list[str]: + """Generate all fish completion commands. + + Parameters + ---------- + completion_data : dict + Extracted completion data. + prog_name : str + Program name. + help_flags : tuple[str, ...] + Help flags. + version_flags : tuple[str, ...] + Version flags. + + Returns + ------- + list[str] + Completion command lines. + """ + lines = [] + + for command_path, _data in sorted(completion_data.items()): + lines.extend( + _generate_completions_for_path( + completion_data, + command_path, + prog_name, + help_flags, + version_flags, + ) + ) + if command_path != max(completion_data.keys(), key=len): + lines.append("") + + return lines + + +def _generate_completions_for_path( + completion_data: dict[tuple[str, ...], CompletionData], + command_path: tuple[str, ...], + prog_name: str, + help_flags: tuple[str, ...], + version_flags: tuple[str, ...], +) -> list[str]: + """Generate completions for a specific command path. + + Parameters + ---------- + completion_data : dict + Extracted completion data. + command_path : tuple[str, ...] + Command path. + prog_name : str + Program name. + help_flags : tuple[str, ...] + Help flags. + version_flags : tuple[str, ...] + Version flags. + + Returns + ------- + list[str] + Completion command lines. + """ + if command_path not in completion_data: + return [] + + data = completion_data[command_path] + lines = [] + condition = _get_condition_for_path(command_path, prog_name) + + lines.extend(_generate_subcommand_completions(data, command_path, prog_name, condition)) + + keyword_args = [arg for arg in data.arguments if not arg.is_positional_only() and arg.show] + if keyword_args or help_flags or version_flags: + lines.extend(_generate_option_section_header(command_path)) + lines.extend(_generate_help_version_completions(prog_name, condition, help_flags, version_flags)) + lines.extend(_generate_keyword_arg_completions(keyword_args, prog_name, condition, data.help_format)) + lines.extend(_generate_command_option_completions(data.commands, prog_name, condition, data.help_format)) + + return lines + + +def _generate_subcommand_completions( + data: CompletionData, + command_path: tuple[str, ...], + prog_name: str, + condition: str, +) -> list[str]: + """Generate completions for subcommands. + + Parameters + ---------- + data : CompletionData + Completion data. + command_path : tuple[str, ...] + Command path. + prog_name : str + Program name. + condition : str + Fish condition. + + Returns + ------- + list[str] + Completion command lines. + """ + commands = [ + name for registered_command in data.commands for name in registered_command.names if not name.startswith("-") + ] + if not commands: + return [] + + lines = [] + if command_path: + lines.append(f"# Subcommands for: {' '.join(command_path)}") + else: + lines.append("# Root-level commands") + + for registered_command in data.commands: + for cmd_name in registered_command.names: + if cmd_name.startswith("-"): + continue + + desc = _get_description_from_app(registered_command.app, data.help_format) + escaped_desc = _escape_fish_description(desc) + escaped_cmd = _escape_fish_string(cmd_name) + + lines.append(f"complete -c {prog_name} {condition} -a '{escaped_cmd}' -d '{escaped_desc}'") + + return lines + + +def _generate_option_section_header(command_path: tuple[str, ...]) -> list[str]: + """Generate section header comment for options. + + Parameters + ---------- + command_path : tuple[str, ...] + Command path. + + Returns + ------- + list[str] + Comment line. + """ + if command_path: + return [f"# Options for: {' '.join(command_path)}"] + return ["# Root-level options"] + + +def _generate_help_version_completions( + prog_name: str, + condition: str, + help_flags: tuple[str, ...], + version_flags: tuple[str, ...], +) -> list[str]: + """Generate completions for help and version flags. + + Parameters + ---------- + prog_name : str + Program name. + condition : str + Fish condition. + help_flags : tuple[str, ...] + Help flags. + version_flags : tuple[str, ...] + Version flags. + + Returns + ------- + list[str] + Completion command lines. + """ + lines = [] + + for flag in help_flags: + if flag.startswith("--"): + long_name = flag[2:] + lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d 'Display this message and exit.'") + elif flag.startswith("-") and len(flag) == 2: + short_name = flag[1] + lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d 'Display this message and exit.'") + + for flag in version_flags: + if flag.startswith("--"): + long_name = flag[2:] + lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d 'Display application version.'") + elif flag.startswith("-") and len(flag) == 2: + short_name = flag[1] + lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d 'Display application version.'") + + return lines + + +def _generate_keyword_arg_completions( + keyword_args: list, + prog_name: str, + condition: str, + help_format: str, +) -> list[str]: + """Generate completions for keyword arguments. + + Parameters + ---------- + keyword_args : list + Keyword arguments. + prog_name : str + Program name. + condition : str + Fish condition. + help_format : str + Help text format. + + Returns + ------- + list[str] + Completion command lines. + """ + lines = [] + + for argument in keyword_args: + desc = strip_markup(argument.parameter.help or "", format=help_format) + escaped_desc = _escape_fish_description(desc) + + is_flag = argument.is_flag() + choices = argument.get_choices(force=True) + action = get_completion_action(argument.hint) + + for name in argument.parameter.name or []: + if not name.startswith("-"): + continue + + if name.startswith("--"): + long_name = name[2:] + line_parts = [f"complete -c {prog_name} {condition} -l {long_name}"] + elif len(name) == 2: + short_name = name[1] + line_parts = [f"complete -c {prog_name} {condition} -s {short_name}"] + else: + continue + + if is_flag: + line_parts.append(f"-d '{escaped_desc}'") + elif choices: + escaped_choices = [_escape_fish_string(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + line_parts.append(f"-x -a '{choices_str}' -d '{escaped_desc}'") + else: + action_flags = _map_completion_action_to_fish(action) + if action_flags: + line_parts.append(f"{action_flags} -d '{escaped_desc}'") + else: + line_parts.append(f"-r -d '{escaped_desc}'") + + lines.append(" ".join(line_parts)) + + for name in argument.negatives: + if not name.startswith("-"): + continue + + if name.startswith("--"): + long_name = name[2:] + lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d '{escaped_desc}'") + elif len(name) == 2: + short_name = name[1] + lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d '{escaped_desc}'") + + return lines + + +def _generate_command_option_completions( + commands: list, + prog_name: str, + condition: str, + help_format: str, +) -> list[str]: + """Generate completions for commands that look like options. + + Parameters + ---------- + commands : list + List of RegisteredCommand tuples. + prog_name : str + Program name. + condition : str + Fish condition. + help_format : str + Help text format. + + Returns + ------- + list[str] + Completion command lines. + """ + lines = [] + + for registered_command in commands: + for cmd_name in registered_command.names: + if not cmd_name.startswith("-"): + continue + + desc = _get_description_from_app(registered_command.app, help_format) + escaped_desc = _escape_fish_description(desc) + + if cmd_name.startswith("--"): + long_name = cmd_name[2:] + lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d '{escaped_desc}'") + elif len(cmd_name) == 2: + short_name = cmd_name[1] + lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d '{escaped_desc}'") + + return lines + + +def _get_condition_for_path(command_path: tuple[str, ...], prog_name: str) -> str: + """Generate fish condition string for a command path. + + Parameters + ---------- + command_path : tuple[str, ...] + Command path (empty for root). + prog_name : str + Program name. + + Returns + ------- + str + Fish condition flag. + """ + if not command_path: + return "-n __fish_use_subcommand" + + func_name = f"__fish_{prog_name}_using_command" + escaped_commands = " ".join(_escape_fish_string(cmd) for cmd in command_path) + return f"-n '{func_name} {escaped_commands}'" + + +def _get_description_from_app(cmd_app: "App | CommandSpec", help_format: str) -> str: + """Extract description from App. + + Parameters + ---------- + cmd_app : App | CommandSpec + Command app or spec. + help_format : str + Help text format. + + Returns + ------- + str + Description text. + """ + from cyclopts.help.help import docstring_parse + + try: + parsed = docstring_parse(cmd_app.help, "plaintext") + text = parsed.short_description or "" + except Exception: + text = str(cmd_app.help or "") + + return strip_markup(text, format=help_format) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/install.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/install.py new file mode 100644 index 0000000000000000000000000000000000000000..f93cfd38f6fbbac57d65f977f9568272820e08b1 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/install.py @@ -0,0 +1,237 @@ +"""Shell completion installation utilities. + +This module handles the installation of completion scripts to shell-specific +locations and the updating of shell RC files to load completions. +""" + +import os +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Annotated, Literal + +from cyclopts.parameter import Parameter + + +def _detect_omz_completions_dir() -> Path | None: + """Detect oh-my-zsh custom completions directory. + + Uses ``$ZSH_CUSTOM/completions`` (the recommended location for user + completions in oh-my-zsh). Falls back to ``$ZSH/custom/completions`` + when ``$ZSH_CUSTOM`` is not set. + + Returns + ------- + Path | None + Path to the oh-my-zsh custom completions directory, or None if + oh-my-zsh is not detected. + """ + zsh_custom_str = os.environ.get("ZSH_CUSTOM") + if zsh_custom_str: + zsh_custom = Path(zsh_custom_str) + if zsh_custom.is_dir(): + return zsh_custom / "completions" + zsh_dir_str = os.environ.get("ZSH") + if not zsh_dir_str: + return None + zsh_dir = Path(zsh_dir_str) + if zsh_dir.is_dir(): + return zsh_dir / "custom" / "completions" + return None + + +def get_default_completion_path(shell: Literal["zsh", "bash", "fish"], prog_name: str) -> Path: + """Get the default completion script path for a given shell. + + Parameters + ---------- + shell : Literal["zsh", "bash", "fish"] + Shell type. + prog_name : str + Program name for the completion script. + + Returns + ------- + Path + Default installation path for the shell. + + Raises + ------ + ValueError + If shell type is unsupported. + """ + home = Path.home() + if shell == "zsh": + omz_completions = _detect_omz_completions_dir() + if omz_completions is not None: + omz_completions.mkdir(parents=True, exist_ok=True) + return omz_completions / f"_{prog_name}" + # Vanilla zsh fallback + zsh_completions = home / ".zsh" / "completions" + zsh_completions.mkdir(parents=True, exist_ok=True) + return zsh_completions / f"_{prog_name}" + elif shell == "bash": + bash_completions = home / ".local" / "share" / "bash-completion" / "completions" + bash_completions.mkdir(parents=True, exist_ok=True) + return bash_completions / prog_name + elif shell == "fish": + fish_completions = home / ".config" / "fish" / "completions" + fish_completions.mkdir(parents=True, exist_ok=True) + return fish_completions / f"{prog_name}.fish" + else: + raise ValueError(f"Unsupported shell: {shell}") + + +def add_to_rc_file(script_path: Path, prog_name: str, shell: Literal["bash", "zsh"]) -> bool: + """Add completion configuration to shell RC file. + + For bash, adds a source line to load the completion script. + For zsh, adds the completion directory to fpath so compinit can find it. + + Parameters + ---------- + script_path : Path + Path to the completion script. + prog_name : str + Program name for display in comments. + shell : Literal["bash", "zsh"] + Shell type. + + Returns + ------- + bool + True if configuration was added, False if it already existed or on error. + """ + if shell == "bash": + rc_file = Path.home() / ".bashrc" + config_line = f'[ -f "{script_path}" ] && . "{script_path}"' + comment = f"# Load {prog_name} completion" + elif shell == "zsh": + if _detect_omz_completions_dir(): + return False + rc_file = Path.home() / ".zshrc" + completion_dir = script_path.parent + config_line = f"fpath=({completion_dir} $fpath)" + comment = f"# {prog_name} completions" + else: + raise NotImplementedError + + rc_file = rc_file.resolve() + + if rc_file.exists(): + content = rc_file.read_text() + # For zsh, check if this directory is already in fpath configuration + # For bash, check if the exact source line exists + if shell == "zsh" and str(script_path.parent) in content and "fpath=" in content: + return False + elif config_line in content: + return False + else: + content = "" + + if shell == "zsh": + # Prepend to ensure fpath is set before any compinit call + rc_file.write_text(f"{comment}\n{config_line}\n{content}") + else: + # Bash: append + needs_newline = content and not content.endswith("\n") + with rc_file.open("a") as f: + if needs_newline: + f.write("\n") + f.write(f"{comment}\n{config_line}\n") + + return True + + +def create_install_completion_command( + install_completion_fn: Callable[..., Path], + add_to_startup: bool, +): + """Create a command function for installing shell completion. + + Parameters + ---------- + install_completion_fn : Callable + Function that performs the actual installation (typically App.install_completion). + Should accept (shell, output, add_to_startup) and return the installation path. + add_to_startup : bool + Whether to add source line to shell RC file. + + Returns + ------- + Callable + Command function that can be registered with App.command(). + """ + + def _install_completion_command( + *, + shell: Annotated[Literal["zsh", "bash", "fish"] | None, Parameter()] = None, + output: Annotated[Path | None, Parameter(name=["-o", "--output"])] = None, + ): + """Install shell completion for this application. + + This command generates and installs the completion script to the appropriate + location for your shell. After installation, you may need to restart your + shell or source your shell configuration file. + + Parameters + ---------- + shell : Literal["zsh", "bash", "fish"] | None + Shell type for completion. If not specified, attempts to auto-detect current shell. + output : Path | None + Output path for the completion script. If not specified, uses shell-specific default. + """ + from cyclopts.completion.detect import ShellDetectionError, detect_shell + + if shell is None: + try: + shell = detect_shell() + except ShellDetectionError: + print( + "Could not auto-detect shell. Please specify --shell explicitly.", + file=sys.stderr, + ) + sys.exit(1) + + install_path = install_completion_fn(shell=shell, output=output, add_to_startup=add_to_startup) + + print(f"✓ Completion script installed to {install_path}") + + if shell == "zsh": + if _detect_omz_completions_dir(): + print("✓ Detected oh-my-zsh: completions directory is already in $fpath.") + print("\nRestart your shell or run: exec zsh") + elif add_to_startup: + zshrc = Path.home() / ".zshrc" + completion_dir = install_path.parent + print(f"✓ Added {completion_dir} to fpath in {zshrc}") + print("\nNote: Ensure compinit is configured in your .zshrc (most zsh setups already have this).") + print("Restart your shell or run: exec zsh") + else: + completion_dir = install_path.parent + print(f"\nTo enable completions, ensure {completion_dir} is in your $fpath.") + print("Add this to your ~/.zshrc or ~/.zprofile if not already present:") + print(f" fpath=({completion_dir} $fpath)") + print(" autoload -Uz compinit && compinit") + print("\nThen restart your shell or run: exec zsh") + elif shell == "bash": + if add_to_startup: + bashrc = Path.home() / ".bashrc" + print(f"✓ Added completion loader to {bashrc}") + print("\nRestart your shell or run: source ~/.bashrc") + else: + print("\nCompletions will be automatically loaded by bash-completion.") + print("If completions don't work:") + print(" 1. Ensure bash-completion is installed (v2.8+)") + print(" 2. Restart your shell or run: exec bash") + print("\nNote: bash-completion is typically installed via:") + print(" - macOS: brew install bash-completion@2") + print(" - Debian/Ubuntu: apt install bash-completion") + print(" - Fedora/RHEL: dnf install bash-completion") + elif shell == "fish": + print("\nCompletions are automatically loaded in fish.") + print("Restart your shell or run: source ~/.config/fish/config.fish") + else: + raise NotImplementedError + + return _install_completion_command diff --git a/.venv/lib/python3.10/site-packages/cyclopts/completion/zsh.py b/.venv/lib/python3.10/site-packages/cyclopts/completion/zsh.py new file mode 100644 index 0000000000000000000000000000000000000000..f6594f634ca69c9af207f3720d9e2805d8da4d78 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/completion/zsh.py @@ -0,0 +1,680 @@ +"""Zsh completion script generator. + +Generates static zsh completion scripts using the compsys framework. +No runtime Python dependency. +""" + +import re +from textwrap import dedent +from textwrap import indent as textwrap_indent +from typing import TYPE_CHECKING + +from cyclopts.annotations import is_iterable_type +from cyclopts.completion._base import ( + CompletionAction, + CompletionData, + clean_choice_text, + escape_for_shell_pattern, + extract_completion_data, + get_completion_action, + strip_markup, +) +from cyclopts.help.help import docstring_parse + +if TYPE_CHECKING: + from cyclopts import App + from cyclopts.argument import Argument, ArgumentCollection + from cyclopts.command_spec import CommandSpec + + +def generate_completion_script(app: "App", prog_name: str) -> str: + """Generate zsh completion script. + + Parameters + ---------- + app : App + The Cyclopts application to generate completion for. + prog_name : str + Program name (alphanumeric with hyphens/underscores). + + Returns + ------- + str + Complete zsh completion script. + + Raises + ------ + ValueError + If prog_name contains invalid characters. + """ + if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name): + raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.") + + completion_data = extract_completion_data(app) + + lines = [ + f"#compdef {prog_name}", + "", + f"_{prog_name}() {{", + " local line state", + "", + ] + + lines.extend( + _generate_completion_for_path( + completion_data, + (), + prog_name=prog_name, + help_flags=tuple(app.help_flags) if app.help_flags else (), + version_flags=tuple(app.version_flags) if app.version_flags else (), + ) + ) + + lines.extend( + [ + "}", + "", + ] + ) + + return "\n".join(lines) + "\n" + + +def _generate_run_command_completion( + arguments: "ArgumentCollection", + indent_str: str, + prog_name: str, +) -> list[str]: + """Generate dynamic completion for the 'run' command. + + Parameters + ---------- + arguments : ArgumentCollection + Arguments for run command. + indent_str : str + Indentation string. + prog_name : str + Program name. + + Returns + ------- + list[str] + Zsh completion code lines. + """ + template = dedent(f"""\ + local script_path + local -a completions + local -a remaining_words + + # If completing first argument (the script path), suggest files + if [[ $CURRENT -eq 2 ]]; then + _files + return + fi + + # Get absolute path to the script file + script_path=${{words[2]}} + script_path=${{script_path:a}} + if [[ -f $script_path ]]; then + remaining_words=(${{words[3,-1]}}) + local result + local cmd + + if command -v {prog_name} &>/dev/null; then + cmd="{prog_name}" + else + return + fi + # Call back into cyclopts to get dynamic completions from the script + result=$($cmd _complete run "$script_path" "${{remaining_words[@]}}" 2>/dev/null) + if [[ -n $result ]]; then + # Parse and display completion results + completions=() + while IFS= read -r line; do + completions+=($line) + done <<< $result + _describe 'command' completions + fi + fi""") + + indented = textwrap_indent(template, indent_str) + return [line.rstrip() for line in indented.split("\n")] + + +def _generate_nested_positional_specs( + positional_args: list["Argument"], + help_format: str, +) -> list[str]: + """Generate positional argument specs for nested command context. + + In nested contexts (after *::arg:->args), word indexing is shifted: + - words[1] = subcommand name + - words[2] = first positional argument + - words[3] = second positional argument, etc. + + Parameters + ---------- + positional_args : list[Argument] + Positional arguments to generate specs for. + help_format : str + Help text format. + + Returns + ------- + list[str] + List of zsh positional argument specs. + """ + specs = [] + + # Check if we have variadic positionals (including collection types like list[X]) + variadic_args = [arg for arg in positional_args if arg.is_var_positional() or is_iterable_type(arg.hint)] + non_variadic_args = [ + arg for arg in positional_args if not arg.is_var_positional() and not is_iterable_type(arg.hint) + ] + + # Generate specs for non-variadic positionals + for arg in non_variadic_args: + # Position in nested context: After *::arg:->args, $words[1] is the subcommand + # So positionals start at position 1 (not 2) + # Use 1-based indexing: first positional is '1:', second is '2:', etc. + pos = 1 + (arg.index or 0) + desc = _get_description_from_argument(arg, help_format) + + # Check for choices first (Literal/Enum types) + choices = arg.get_choices(force=True) + if choices: + escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + action = f"({choices_str})" + else: + action = _map_completion_action_to_zsh(get_completion_action(arg.hint)) + + spec = f"'{pos}:{desc}:{action}'" if action else f"'{pos}:{desc}'" + specs.append(spec) + + # Generate specs for variadic positionals + for arg in variadic_args: + desc = _get_description_from_argument(arg, help_format) + + choices = arg.get_choices(force=True) + if choices: + escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + action = f"({choices_str})" + else: + action = _map_completion_action_to_zsh(get_completion_action(arg.hint)) + + spec = f"'*:{desc}:{action}'" if action else f"'*:{desc}'" + specs.append(spec) + + return specs + + +def _generate_describe_completion( + argument: "Argument", + help_format: str, + indent_str: str, +) -> list[str]: + """Generate _describe-based completion for a single positional argument. + + Parameters + ---------- + argument : Argument + Argument to generate completion for. + help_format : str + Help text format. + indent_str : str + Indentation string. + + Returns + ------- + list[str] + Zsh completion code lines. + """ + lines = [] + desc = _get_description_from_argument(argument, help_format) + + # Check for choices (Literal/Enum types) + choices = argument.get_choices(force=True) + if choices: + # Generate choices array with descriptions + escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices] + lines.append(f"{indent_str}local -a choices") + lines.append(f"{indent_str}choices=(") + for choice in escaped_choices: + lines.append(f"{indent_str} '{choice}:{desc}'") + lines.append(f"{indent_str})") + lines.append(f"{indent_str}_describe 'argument' choices") + else: + # Use completion action (files, directories, or nothing) + action = get_completion_action(argument.hint) + if action == CompletionAction.FILES: + lines.append(f"{indent_str}_files") + elif action == CompletionAction.DIRECTORIES: + lines.append(f"{indent_str}_directories") + # For other types, provide no completion + + return lines + + +def _generate_completion_for_path( + completion_data: dict[tuple[str, ...], CompletionData], + command_path: tuple[str, ...], + indent: int = 2, + prog_name: str = "cyclopts", + help_flags: tuple[str, ...] = (), + version_flags: tuple[str, ...] = (), +) -> list[str]: + """Generate completion code for a specific command path. + + Parameters + ---------- + completion_data : dict + Extracted completion data. + command_path : tuple[str, ...] + Command path. + indent : int + Indentation level. + prog_name : str + Program name. + help_flags : tuple[str, ...] + Help flags. + version_flags : tuple[str, ...] + Version flags. + + Returns + ------- + list[str] + Zsh code lines. + """ + data = completion_data[command_path] + commands = data.commands + arguments = data.arguments + indent_str = " " * indent + lines = [] + + if command_path == ("run",) and prog_name == "cyclopts": + lines.extend(_generate_run_command_completion(arguments, indent_str, prog_name)) + return lines + + args_specs = [] + positional_specs = [] + + # Separate positional from keyword arguments + # Include all arguments with an index (both positional-only and positional-or-keyword) + positional_args = [arg for arg in arguments if arg.index is not None and arg.show] + keyword_args = [arg for arg in arguments if not arg.is_positional_only() and arg.show] + + # Sort positionals by index (should never be None for positional-only args) + positional_args.sort(key=lambda a: a.index or 0) + + # Generate keyword argument specs + for argument in keyword_args: + specs = _generate_keyword_specs(argument, data.help_format) + args_specs.extend(specs) + + # Check for flag commands (commands that look like options) + flag_command_names = set() + for registered_command in commands: + if any(name.startswith("-") for name in registered_command.names): + specs = _generate_keyword_specs_for_command( + registered_command.names, registered_command.app, data.help_format + ) + args_specs.extend(specs) + flag_command_names.update(registered_command.names) + + # Add help and version flags to all command paths (if not already added as flag commands) + for flag in help_flags: + if flag.startswith("-") and flag not in flag_command_names: + spec = f"'{flag}[Display this message and exit.]'" + args_specs.append(spec) + + for flag in version_flags: + if flag.startswith("-") and flag not in flag_command_names: + spec = f"'{flag}[Display application version.]'" + args_specs.append(spec) + + has_non_flag_commands = any( + not cmd_name.startswith("-") for registered_command in commands for cmd_name in registered_command.names + ) + + # Generate positional argument specs + # Only add positionals if there are no subcommands (they conflict in zsh) + if positional_args and not has_non_flag_commands: + if command_path: + # Nested context: use shifted positional indexing (words[1] is subcommand) + positional_specs = _generate_nested_positional_specs(positional_args, data.help_format) + else: + # Root context: standard _arguments works fine + for argument in positional_args: + spec = _generate_positional_spec(argument, data.help_format) + positional_specs.append(spec) + + # Add positionals BEFORE options to prioritize them in completion + args_specs = positional_specs + args_specs + + if has_non_flag_commands: + args_specs.append("'1: :->cmds'") + args_specs.append("'*::arg:->args'") + + if args_specs: + c_flag = "-C " if has_non_flag_commands else "" + lines.append(f"{indent_str}_arguments {c_flag}\\") + for spec in args_specs[:-1]: + lines.append(f"{indent_str} {spec} \\") + lines.append(f"{indent_str} {args_specs[-1]}") + lines.append("") + + if has_non_flag_commands: + lines.append(f"{indent_str}case $state in") + lines.append(f"{indent_str} cmds)") + + cmd_list = [] + for registered_command in commands: + for cmd_name in registered_command.names: + if not cmd_name.startswith("-"): + desc = _safe_get_description_from_app(registered_command.app, data.help_format) + escaped_cmd_name = _escape_completion_choice(cmd_name) + cmd_list.append(f"'{escaped_cmd_name}:{desc}'") + + lines.append(f"{indent_str} local -a commands") + lines.append(f"{indent_str} commands=(") + for cmd in cmd_list: + lines.append(f"{indent_str} {cmd}") + lines.append(f"{indent_str} )") + lines.append(f"{indent_str} _describe -t commands 'command' commands") + lines.append(f"{indent_str} ;;") + + lines.append(f"{indent_str} args)") + lines.append(f"{indent_str} case $words[1] in") + + for registered_command in commands: + for cmd_name in registered_command.names: + if cmd_name.startswith("-"): + continue + + sub_path = command_path + (cmd_name,) + if sub_path in completion_data: + escaped_case_name = _escape_command_name_for_case(cmd_name) + lines.append(f"{indent_str} {escaped_case_name})") + sub_lines = _generate_completion_for_path( + completion_data, sub_path, indent + 8, prog_name, help_flags, version_flags + ) + lines.extend(sub_lines) + lines.append(f"{indent_str} ;;") + + lines.append(f"{indent_str} esac") + lines.append(f"{indent_str} ;;") + lines.append(f"{indent_str}esac") + + return lines + + +def _escape_completion_choice(choice: str) -> str: + """Escape special characters in a completion choice value for zsh. + + Choice should already be cleaned via clean_choice_text() before calling this function. + This function only applies zsh-specific escaping. + + Parameters + ---------- + choice : str + Cleaned choice value. + + Returns + ------- + str + Escaped choice value safe for zsh completion. + """ + choice = choice.replace("\\", "\\\\") + choice = choice.replace("'", r"'\''") + choice = choice.replace("`", "\\`") + choice = choice.replace("$", "\\$") + choice = choice.replace('"', '\\"') + choice = choice.replace(" ", "\\ ") + choice = choice.replace("(", "\\(") + choice = choice.replace(")", "\\)") + choice = choice.replace("[", "\\[") + choice = choice.replace("]", "\\]") + choice = choice.replace(";", "\\;") + choice = choice.replace("|", "\\|") + choice = choice.replace("&", "\\&") + choice = choice.replace(":", "\\:") + return choice + + +def _escape_command_name_for_case(name: str) -> str: + """Escape special characters in command name for zsh case patterns. + + In zsh case patterns, glob characters need to be escaped to match literally. + Colons also need escaping because zsh's completion system may treat them + specially when populating the $words array after _describe completion. + + Parameters + ---------- + name : str + Command name. + + Returns + ------- + str + Escaped command name safe for zsh case patterns. + """ + # zsh case patterns have more special chars than bash: includes ()| + # Colons (:) also need escaping for completion $words matching (issue #715) + return escape_for_shell_pattern(name, chars="*?[]()|:") + + +def _escape_zsh_description(text: str) -> str: + """Escape special characters in description text for zsh. + + Parameters + ---------- + text : str + Cleaned description text. + + Returns + ------- + str + Escaped description safe for zsh completion. + """ + text = text.replace("\\", "\\\\") + text = text.replace("`", "\\`") + text = text.replace("$", "\\$") + text = text.replace('"', '\\"') + text = text.replace("'", r"'\''") + text = text.replace(":", r"\:") + text = text.replace("[", r"\[") + text = text.replace("]", r"\]") + return text + + +def _generate_keyword_specs(argument: "Argument", help_format: str) -> list[str]: + """Generate zsh _arguments specs for a keyword argument. + + Parameters + ---------- + argument : Argument + Argument object from ArgumentCollection. + help_format : str + Help text format. + + Returns + ------- + list[str] + List of zsh argument specs. + """ + specs = [] + desc = _get_description_from_argument(argument, help_format) + + flag = argument.is_flag() + + # Determine completion action + action = "" + choices = argument.get_choices(force=True) + if choices: + escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + action = f"({choices_str})" + flag = False + else: + action = _map_completion_action_to_zsh(get_completion_action(argument.hint)) + + # Generate specs for positive names (from parameter.name) + for name in argument.parameter.name: # pyright: ignore[reportOptionalIterable] + if not name.startswith("-"): + continue + if flag and not action: + spec = f"'{name}[{desc}]'" + elif action: + spec = f"'{name}[{desc}]:{name.lstrip('-')}:{action}'" + else: + spec = f"'{name}[{desc}]:{name.lstrip('-')}'" + specs.append(spec) + + # Generate specs for negative names (always flags, consume no tokens) + for name in argument.negatives: + if not name.startswith("-"): + continue + # Negative flags always consume zero tokens (e.g., --empty-items, --no-verbose) + spec = f"'{name}[{desc}]'" + specs.append(spec) + + return specs + + +def _generate_positional_spec(argument: "Argument", help_format: str) -> str: + """Generate zsh _arguments spec for a positional argument. + + Parameters + ---------- + argument : Argument + Positional argument object. + help_format : str + Help text format. + + Returns + ------- + str + Zsh positional argument spec. + """ + desc = _get_description_from_argument(argument, help_format) + + # Check for choices first (Literal/Enum types) + choices = argument.get_choices(force=True) + if choices: + escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices] + choices_str = " ".join(escaped_choices) + action = f"({choices_str})" + else: + action = _map_completion_action_to_zsh(get_completion_action(argument.hint)) + + if argument.is_var_positional() or is_iterable_type(argument.hint): + # Variadic positional (*args) or collection type (list[X], set[X], etc.) + return f"'*:{desc}:{action}'" if action else f"'*:{desc}'" + + # Regular positional - zsh uses 1-based indexing + if argument.index is None: + raise ValueError(f"Positional-only argument {argument.names} missing index") + pos = argument.index + 1 + return f"'{pos}:{desc}:{action}'" if action else f"'{pos}:{desc}'" + + +def _generate_keyword_specs_for_command( + names: tuple[str, ...], cmd_app: "App | CommandSpec", help_format: str +) -> list[str]: + """Generate zsh _arguments specs for a command that looks like a flag. + + Parameters + ---------- + names : tuple[str, ...] + Registered names for the command. + cmd_app : App | CommandSpec + Command app or spec. + help_format : str + Help text format. + + Returns + ------- + list[str] + List of zsh argument specs. + """ + specs = [] + desc = _safe_get_description_from_app(cmd_app, help_format) + + for name in names: + if name.startswith("-"): + spec = f"'{name}[{desc}]'" + specs.append(spec) + + return specs + + +def _map_completion_action_to_zsh(action: CompletionAction) -> str: + """Map shell-agnostic completion action to zsh-specific completion command. + + Parameters + ---------- + action : CompletionAction + Shell-agnostic completion action. + + Returns + ------- + str + Zsh completion command (e.g., "_files", "_directories", or ""). + """ + if action == CompletionAction.FILES: + return "_files" + elif action == CompletionAction.DIRECTORIES: + return "_directories" + return "" + + +def _get_description_from_argument(argument: "Argument", help_format: str) -> str: + """Extract plain text description from Argument, escaping zsh special chars. + + Parameters + ---------- + argument : Argument + Argument object with parameter help text. + help_format : str + Help text format. + + Returns + ------- + str + Escaped plain text description (truncated to 80 chars). + Falls back to argument name if help text is empty, since zsh _arguments + requires a non-empty description for positional specs to work correctly. + """ + text = strip_markup(argument.parameter.help or "", format=help_format) + if not text: + # Use primary argument name as fallback - zsh _arguments requires non-empty + # description for positional specs to provide completions + text = argument.names[0] if argument.names else "argument" + return _escape_zsh_description(text) + + +def _safe_get_description_from_app(cmd_app: "App | CommandSpec", help_format: str) -> str: + """Extract plain text description from App, escaping zsh special chars. + + Parameters + ---------- + cmd_app : App | CommandSpec + Command app or spec with help text. + help_format : str + Help text format. + + Returns + ------- + str + Escaped plain text description (truncated to 80 chars). + """ + try: + parsed = docstring_parse(cmd_app.help, "plaintext") + text = parsed.short_description or "" + except Exception: + text = str(cmd_app.help or "") + + text = strip_markup(text, format=help_format) + return _escape_zsh_description(text) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18a1617040432e13c6c53d6e540f6ef4f2dda583 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/__init__.py @@ -0,0 +1,14 @@ +__all__ = [ + "ConfigFromFile", + "Dict", + "Env", + "Json", + "Toml", + "Yaml", +] + +from cyclopts.config._common import ConfigFromFile, Dict +from cyclopts.config._env import Env +from cyclopts.config._json import Json +from cyclopts.config._toml import Toml +from cyclopts.config._yaml import Yaml diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/_common.py b/.venv/lib/python3.10/site-packages/cyclopts/config/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a72f74d10cff085181874210e1a3de983eb25f8f --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/_common.py @@ -0,0 +1,211 @@ +import errno +import os +from abc import ABC, abstractmethod +from collections.abc import Iterable +from contextlib import suppress +from itertools import chain +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from attrs import define, field + +from cyclopts.argument import ArgumentCollection, update_argument_collection +from cyclopts.exceptions import CycloptsError +from cyclopts.utils import to_tuple_converter + + +def _root_keys_converter(value: Iterable[str]) -> tuple[str, ...]: + return to_tuple_converter(value) # type: ignore[return-value] + + +if TYPE_CHECKING: + from cyclopts.core import App + + +@define(kw_only=True) +class ConfigBase(ABC): + """Base class for configuration sources. + + Handles the common logic of processing configuration dictionaries + and updating ArgumentCollections. + """ + + root_keys: Iterable[str] = field(default=(), converter=_root_keys_converter) + allow_unknown: bool = field(default=False) + use_commands_as_keys: bool = field(default=True) + _source: str | None = field(default=None, alias="source") + + @property + @abstractmethod + def config(self) -> dict[str, Any]: + """Return the configuration dictionary.""" + raise NotImplementedError + + @property + @abstractmethod + def source(self) -> str: + """Return a string identifying the configuration source for error messages.""" + raise NotImplementedError + + def __call__( + self, + app: "App", + commands: tuple[str, ...], + arguments: ArgumentCollection, + ): + config: dict[str, Any] = self.config.copy() + try: + for key in chain(self.root_keys, commands if self.use_commands_as_keys else ()): + config = config[key] + except KeyError: + return + + # Hierarchical config uses current app; flat config uses root app to filter sibling commands + if self.use_commands_as_keys: + filter_app = app + else: + filter_app = next((a for a in app.app_stack.current_frame if not a._meta_parent), app) + config = {k: v for k, v in config.items() if k not in filter_app} + + update_argument_collection( + config, + self.source, + arguments, + app.app_stack.stack[-1], + root_keys=self.root_keys, + allow_unknown=self.allow_unknown, + ) + + +class FileCacheKey: + """Abstraction to quickly check if a file needs to be read again. + + If a newly instantiated ``CacheKey`` doesn't equal a previously instantiated ``CacheKey``, + then the file needs to be re-read. + """ + + def __init__(self, path: str | Path): + self.path = Path(path).absolute() + if self.path.exists(): + stat = self.path.stat() + self._mtime = stat.st_mtime + self._size = stat.st_size + else: + self._mtime = None + self._size = None + + def __eq__(self, other): + if not isinstance(other, type(self)): + return False + + return self._mtime == other._mtime and self._size == other._size and self.path == other.path + + +@define +class ConfigFromFile(ConfigBase): + """Configuration source that loads from a file. + + Supports file caching and parent directory searching. + """ + + path: str | Path = field(converter=Path) + must_exist: bool = field(default=False, kw_only=True) + search_parents: bool = field(default=False, kw_only=True) + + _config: dict[str, Any] | None = field(default=None, init=False, repr=False) + "Loaded configuration structure (to be loaded by subclassed ``_load_config`` method)." + + _config_cache_key: FileCacheKey | None = field(default=None, init=False, repr=False) + "Conditions under which ``_config`` was loaded." + + @abstractmethod + def _load_config(self, path: Path) -> dict[str, Any]: + """Load the config dictionary from path. + + Do **not** do any downstream caching; ``ConfigFromFile`` handles caching. + + Parameters + ---------- + path: Path + Path to the file. Guaranteed to exist. + + Returns + ------- + dict + Loaded configuration. + """ + raise NotImplementedError + + @property + def config(self) -> dict[str, Any]: + assert isinstance(self.path, Path) + for parent in self.path.expanduser().resolve().absolute().parents: + candidate = parent / self.path.name + if candidate.exists(): + cache_key = FileCacheKey(candidate) + if self._config_cache_key == cache_key: + return self._config or {} + + try: + self._config = self._load_config(candidate) + self._config_cache_key = cache_key + except CycloptsError: + raise + except Exception as e: + msg = getattr(type(e), "__name__", "") + with suppress(IndexError): + exception_msg = e.args[0] + if msg: + msg += ": " + msg += exception_msg + raise CycloptsError(msg=msg) from e + return self._config + elif self.search_parents: + # Continue iterating over parents. + continue + elif self.must_exist: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), str(self.path)) + + # No matching file was found. + if self.must_exist: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), str(self.path)) + + self._config = {} + return self._config + + @property + def source(self) -> str: + """Return a string identifying the configuration source for error messages.""" + if self._source is not None: + return self._source + assert isinstance(self.path, Path) + return str(self.path.absolute()) + + @source.setter + def source(self, value: str) -> None: + self._source = value + + +@define +class Dict(ConfigBase): + """Configuration source from an in-memory dictionary. + + Useful for programmatically generated configurations. + """ + + data: dict[str, Any] + + @property + def config(self) -> dict[str, Any]: + return self.data + + @property + def source(self) -> str: + """Return a string identifying the configuration source for error messages.""" + if self._source is not None: + return self._source + return "dict" + + @source.setter + def source(self, value: str) -> None: + self._source = value diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/_env.py b/.venv/lib/python3.10/site-packages/cyclopts/config/_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0683f866bdad9138baee343d94785eb0f27db162 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/_env.py @@ -0,0 +1,69 @@ +import os +from typing import TYPE_CHECKING + +from attrs import define, field + +from cyclopts.argument import Argument, ArgumentCollection, Token + +if TYPE_CHECKING: + from cyclopts.core import App + + +def _transform(s: str) -> str: + return s.upper().replace("-", "_").replace(".", "_").lstrip("_") + + +@define +class Env: + prefix: str = "" + source: str = field(default="env", kw_only=True) + command: bool = field(default=True, kw_only=True) + show: bool = field(default=True, kw_only=True) + + def _prefix(self, commands: tuple[str, ...]) -> str: + prefix = self.prefix + if self.command and commands: + prefix += "_".join(x.upper() for x in commands) + "_" + + return prefix + + def _convert_argument(self, commands: tuple[str, ...], argument: Argument) -> str: + """For generating environment variable names for the help-page. + + Internal Cyclopts use only. + """ + return self._prefix(commands) + _transform(argument.name) + + def __call__(self, app: "App", commands: tuple[str, ...], arguments: ArgumentCollection): + added_tokens = set() + + prefix = self._prefix(commands) + + candidate_env_keys = [x for x in os.environ if x.startswith(prefix)] + candidate_env_keys.sort() + delimiter = "_" + for candidate_env_key in candidate_env_keys: + try: + argument, remaining_keys, _ = arguments.match( + candidate_env_key[len(prefix) :], + transform=_transform, + delimiter=delimiter, + ) + except ValueError: + continue + if set(argument.tokens) - added_tokens: + # Skip if there are any tokens from another source. + continue + + # There's inherently an ambiguity because we use "_" as the key-delimiter. + # However, we can somewhat resolve this ambiguity by checking if the argument + # accepts subkeys. If there are no children arguments, then just re-combine the + # remaining_keys. + if not argument.children and remaining_keys: + remaining_keys = (delimiter.join(remaining_keys),) + + remaining_keys = tuple(x.lower() for x in remaining_keys) + for i, value in enumerate(argument.env_var_split(os.environ[candidate_env_key])): + token = Token(keyword=candidate_env_key, value=value, source=self.source, index=i, keys=remaining_keys) + argument.append(token) + added_tokens.add(token) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/_json.py b/.venv/lib/python3.10/site-packages/cyclopts/config/_json.py new file mode 100644 index 0000000000000000000000000000000000000000..e6f1e060350a8540c29f45515ceb18723f5eaf3d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/_json.py @@ -0,0 +1,15 @@ +import json +from pathlib import Path +from typing import Any + +from cyclopts.config._common import ConfigFromFile +from cyclopts.exceptions import CoercionError + + +class Json(ConfigFromFile): + def _load_config(self, path: Path) -> dict[str, Any]: + with path.open() as f: + try: + return json.load(f) + except json.JSONDecodeError as e: + raise CoercionError from e diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/_toml.py b/.venv/lib/python3.10/site-packages/cyclopts/config/_toml.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc37f8bebeb5e455f5859f9af37df4ad66a7da7 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/_toml.py @@ -0,0 +1,17 @@ +from pathlib import Path +from typing import Any + +from cyclopts.config._common import ConfigFromFile + + +class Toml(ConfigFromFile): + def _load_config(self, path: Path) -> dict[str, Any]: + try: + # Attempt to use builtin >=python3.11 + import tomllib # pyright: ignore[reportMissingImports] + except ImportError: + # Fallback to most popular pypi toml package. + import tomli as tomllib # pyright: ignore[reportMissingImports] + + with path.open("rb") as f: + return tomllib.load(f) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/config/_yaml.py b/.venv/lib/python3.10/site-packages/cyclopts/config/_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..46ca925d46d45322d09100d3a229a8d1ddafa5be --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/config/_yaml.py @@ -0,0 +1,12 @@ +from pathlib import Path +from typing import Any + +from cyclopts.config._common import ConfigFromFile + + +class Yaml(ConfigFromFile): + def _load_config(self, path: Path) -> dict[str, Any]: + from yaml import safe_load # pyright: ignore[reportMissingImports] + + with path.open() as f: + return safe_load(f) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/core.py b/.venv/lib/python3.10/site-packages/cyclopts/core.py new file mode 100644 index 0000000000000000000000000000000000000000..0b725b5c68400f4507a745ea47b633d00f213cdb --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/core.py @@ -0,0 +1,2776 @@ +import importlib +import inspect +import os +import sys +import traceback +from collections.abc import Callable, Coroutine, Iterable, Iterator, Sequence +from contextlib import suppress +from copy import copy +from enum import Enum +from functools import lru_cache, partial +from itertools import chain +from pathlib import Path +from types import ModuleType +from typing import ( + TYPE_CHECKING, + Annotated, + Any, + Literal, + Optional, + TypeVar, + Union, + cast, + overload, +) + +from attrs import Factory, define, field + +from cyclopts.annotations import resolve_annotated +from cyclopts.app_stack import AppStack +from cyclopts.argument import ArgumentCollection +from cyclopts.bind import create_bound_arguments, is_option_like, normalize_tokens +from cyclopts.command_spec import CommandSpec +from cyclopts.config._env import Env +from cyclopts.exceptions import ( + CommandCollisionError, + CycloptsError, + UnknownCommandError, + UnknownOptionError, + UnusedCliTokensError, + ValidationError, +) +from cyclopts.group import Group, sort_groups +from cyclopts.group_extractors import groups_from_app +from cyclopts.panel import CycloptsPanel +from cyclopts.parameter import Parameter, validate_command +from cyclopts.protocols import Dispatcher +from cyclopts.token import Token +from cyclopts.utils import ( + UNSET, + create_error_console_from_console, + default_name_transform, + help_formatter_converter, + optional_to_tuple_converter, + sort_key_converter, + to_list_converter, + to_tuple_converter, +) + +if sys.version_info < (3, 11): # pragma: no cover + pass +else: # pragma: no cover + pass + +with suppress(ImportError): + # By importing, makes things like the arrow-keys work. + # Not available on windows + import readline # noqa: F401 + +if TYPE_CHECKING: + from rich.console import Console + + from cyclopts.docs.types import DocFormat + from cyclopts.help import HelpPanel + from cyclopts.help.protocols import HelpFormatter + +from cyclopts._result_action import ResultAction, ResultActionSingle +from cyclopts._run import _run_maybe_async_command + +T = TypeVar("T", bound=Callable[..., Any]) +V = TypeVar("V") + +DEFAULT_FORMAT = "markdown" + + +def _result_action_converter( + value: "ResultAction | ResultActionSingle | None", +) -> tuple["ResultActionSingle", ...] | None: + """Convert result_action value, ensuring non-empty sequences. + + Intended to be used in an ``attrs.Field`` for result_action. + Raises ValueError if an empty iterable is provided. + """ + if value is None: + return None + + result = to_tuple_converter(value) + + if not result: + raise ValueError("result_action cannot be an empty sequence") + + return result + + +class _CannotDeriveCallingModuleNameError(Exception): + pass + + +def _get_root_module_name(): + """Get the calling package name from the call-stack.""" + for elem in inspect.stack(): + module = inspect.getmodule(elem.frame) + if module is None: + continue + root_module_name = module.__name__.split(".")[0] + if root_module_name == "cyclopts": + continue + return root_module_name + + raise _CannotDeriveCallingModuleNameError # pragma: no cover + + +def _validate_default_command(x: Callable[..., Any] | None) -> Callable[..., Any] | None: + if isinstance(x, App): + raise TypeError("Cannot register a sub-App to default.") + return x + + +def _get_version_command(app): + if callable(app.version) and inspect.iscoroutinefunction(app.version): + return app._version_print_async + else: + return app.version_print + + +def _apply_parent_defaults_to_app(app: "App", parent_app: "App") -> None: + """Apply parent app's group defaults to app if not already set. + + Parameters + ---------- + app : App + The app to apply defaults to. + parent_app : App + The parent app to inherit defaults from. + """ + if app._group_commands is None: + app._group_commands = copy(parent_app._group_commands) + if app._group_parameters is None: + app._group_parameters = copy(parent_app._group_parameters) + if app._group_arguments is None: + app._group_arguments = copy(parent_app._group_arguments) + if app.version is None and parent_app.version is not None: + app.version = parent_app.version + + +def _apply_parent_groups_to_kwargs(kwargs: dict[str, Any], parent_app: "App") -> None: + """Apply parent app's groups to kwargs dict if not already specified. + + Parameters + ---------- + kwargs : dict + Keyword arguments dict to modify. + parent_app : App + The parent app to inherit groups from. + """ + if "group_commands" not in kwargs: + kwargs["group_commands"] = copy(parent_app._group_commands) + if "group_parameters" not in kwargs: + kwargs["group_parameters"] = copy(parent_app._group_parameters) + if "group_arguments" not in kwargs: + kwargs["group_arguments"] = copy(parent_app._group_arguments) + + +def _normalize_for_matching(s: str) -> str: + """Normalize a string for fuzzy command matching. + + Removes hyphens, underscores, and converts to lowercase (e.g., + 'mycommand' matches 'my-command'). + + .. warning:: + This fuzzy matching is primarily for backward compatibility with the + introduction of ``_pascal_to_snake`` in ``default_name_transform``. + It should **probably be removed in v5** once users have migrated their + camelCase command names. + + Parameters + ---------- + s : str + String to normalize. + + Returns + ------- + str + Normalized string with hyphens/underscores removed and lowercased. + """ + return s.replace("-", "").replace("_", "").lower() + + +def _combined_meta_command_mapping( + app: Optional["App"], recurse_meta=True, recurse_parent_meta=True +) -> dict[str, "App | CommandSpec"]: + """Return a mapping of command names to Apps or CommandSpecs. + + CommandSpec instances are NOT resolved here - they are resolved lazily + only when the command is actually executed, enabling true lazy loading. + + Parameters + ---------- + app : App | None + The app to get commands from. + recurse_meta : bool + If True, include commands from the app's meta. + recurse_parent_meta : bool + If True, include commands from parent meta apps. + + Returns + ------- + dict[str, App | CommandSpec] + Mapping of command names to :class:`App` or :class:`CommandSpec` instances. + """ + if app is None: + return {} + command_mapping = dict(app._commands) + + # Add flattened subapp commands (parent commands take precedence) + for subapp in app._flattened_subapps: + for cmd_name in subapp: + if cmd_name not in command_mapping: + command_mapping[cmd_name] = subapp[cmd_name] + + if recurse_meta and app._meta: + command_mapping.update(_combined_meta_command_mapping(app._meta, recurse_parent_meta=False)) + if recurse_parent_meta and app._meta_parent: + meta_parent_commands = _combined_meta_command_mapping(app._meta_parent, recurse_meta=False) + command_mapping.update(meta_parent_commands) + return command_mapping + + +def _walk_metas(app: "App"): + """Typically the result looks like [app] or [meta_app, app]. + + Iterates from deepest to shallowest meta-app (and app). + """ + meta_list = [app] # shallowest to deepest + meta = app + while (meta := meta._meta) and meta.default_command: + meta_list.append(meta) + yield from reversed(meta_list) + + +def _group_converter(input_value: None | str | Group) -> Group | None: + if input_value is None: + return None + elif isinstance(input_value, str): + return Group(input_value) + elif isinstance(input_value, Group): + return input_value + else: + raise TypeError + + +_ConfigCallable = Callable[["App", "tuple[str, ...]", "ArgumentCollection"], Any] + + +def _app_optional_name_converter(value: str | Iterable[str] | None) -> tuple[str, ...] | None: + return optional_to_tuple_converter(value) # type: ignore[return-value] + + +def _app_str_tuple_converter(value: str | Iterable[str] | None) -> tuple[str, ...]: + return to_tuple_converter(value) # type: ignore[return-value] + + +def _app_config_converter( + value: "_ConfigCallable | Iterable[_ConfigCallable] | None", +) -> "tuple[_ConfigCallable, ...] | None": + return optional_to_tuple_converter(value) # type: ignore[return-value] + + +def _app_group_tuple_converter(value: Group | str | Iterable[Group | str] | None) -> tuple[Group | str, ...]: + return cast(tuple[Group | str, ...], to_tuple_converter(value)) + + +def _app_validator_converter( + value: Callable[..., Any] | Iterable[Callable[..., Any]] | None, +) -> list[Callable[..., Any]]: + return to_list_converter(value) # type: ignore[return-value] + + +@define +class App: + # This can ONLY ever be Tuple[str, ...] due to converter. + # The other types is to make mypy happy for Cyclopts users. + _name: None | str | tuple[str, ...] = field(default=None, alias="name", converter=_app_optional_name_converter) + + _help: str | None = field(default=None, alias="help") + + usage: str | None = field(default=None) + + # Everything below must be kw_only + + alias: None | str | tuple[str, ...] = field( + default=None, + converter=_app_str_tuple_converter, + kw_only=True, + ) + + default_command: Callable[..., Any] | None = field(default=None, converter=_validate_default_command, kw_only=True) + default_parameter: Parameter | None = field(default=None, kw_only=True) + + # This can ONLY ever be None or Tuple[Callable, ...] + _config: ( + None + | Callable[["App", tuple[str, ...], ArgumentCollection], Any] + | Iterable[Callable[["App", tuple[str, ...], ArgumentCollection], Any]] + ) = field( + default=None, + alias="config", + converter=_app_config_converter, + kw_only=True, + ) + + version: None | str | Callable[..., str] | Callable[..., Coroutine[Any, Any, str]] = field( + default=None, kw_only=True + ) + # This can ONLY ever be a Tuple[str, ...] + _version_flags: str | Iterable[str] = field( + default=["--version"], + converter=_app_str_tuple_converter, + alias="version_flags", + kw_only=True, + ) + + show: bool = field(default=True, kw_only=True) + + _console: Optional["Console"] = field(default=None, kw_only=True, alias="console") + + _error_console: Optional["Console"] = field(default=None, kw_only=True, alias="error_console") + + # This can ONLY ever be a Tuple[str, ...] + _help_flags: str | Iterable[str] = field( + default=["--help", "-h"], + converter=_app_str_tuple_converter, + alias="help_flags", + kw_only=True, + ) + help_format: Literal["markdown", "md", "plaintext", "restructuredtext", "rst", "rich"] | None = field( + default=None, kw_only=True + ) + help_on_error: bool | None = field(default=None, kw_only=True) + help_prologue: str | None = field(default=None, kw_only=True) + help_epilogue: str | None = field(default=None, kw_only=True) + + version_format: Literal["markdown", "md", "plaintext", "restructuredtext", "rst", "rich"] | None = field( + default=None, kw_only=True + ) + + # This can ONLY ever be Tuple[Union[Group, str], ...] due to converter. + # The other types is to make mypy happy for Cyclopts users. + group: Group | str | tuple[Group | str, ...] = field( + default=None, converter=_app_group_tuple_converter, kw_only=True + ) + + # This can ONLY ever be a Group or None + _group_arguments: Group | str | None = field( + alias="group_arguments", + default=None, + converter=_group_converter, + kw_only=True, + ) + # This can ONLY ever be a Group or None + _group_parameters: Group | str | None = field( + alias="group_parameters", + default=None, + converter=_group_converter, + kw_only=True, + ) + # This can ONLY ever be a Group or None + _group_commands: Group | str | None = field( + alias="group_commands", + default=None, + converter=_group_converter, + kw_only=True, + ) + + validator: list[Callable[..., Any]] = field(default=None, converter=_app_validator_converter, kw_only=True) + + _name_transform: Callable[[str], str] | None = field( + default=None, + alias="name_transform", + kw_only=True, + ) + + _sort_key: Any = field( + default=None, + alias="sort_key", + converter=sort_key_converter, + kw_only=True, + ) + + end_of_options_delimiter: str | None = field(default=None, kw_only=True) + + print_error: bool | None = field(default=None, kw_only=True) + + exit_on_error: bool | None = field(default=None, kw_only=True) + + verbose: bool | None = field(default=None, kw_only=True) + + suppress_keyboard_interrupt: bool = field(default=True, kw_only=True) + + backend: Literal["asyncio", "trio"] | None = field(default=None, kw_only=True) + + help_formatter: Union[None, Literal["default", "plain"], "HelpFormatter"] = field( + default=None, converter=help_formatter_converter, kw_only=True + ) + + error_formatter: Callable[["CycloptsError"], Any] | None = field(default=None, kw_only=True) + + # This can ONLY ever be None or Tuple[ResultActionSingle, ...] due to converter. + # The other types is to make type checkers happy for Cyclopts users. + result_action: ResultAction | ResultActionSingle | None = field( + default=None, + converter=_result_action_converter, + kw_only=True, + ) + + ###################### + # Private Attributes # + ###################### + # `init=False` tells attrs not to include it in the generated __init__ + + # Maps CLI-name of a command to either an App or a CommandSpec (lazy). + _commands: dict[str, "App | CommandSpec"] = field(init=False, factory=dict) + + # Subapps whose commands should be flattened into this app (registered via name="*") + _flattened_subapps: list["App"] = field(init=False, factory=list) + + _meta: Optional["App"] = field(init=False, default=None) + _meta_parent: Optional["App"] = field(init=False, default=None) + + _instantiating_module_name: str | None = field(init=False, default=None, repr=False) + """Module name (e.g., '__main__' or 'mypackage.cli') captured during App initialization. + + Captured from the calling frame's __name__ for lazy module resolution and automatic + version detection. Populated in __attrs_post_init__ via frame introspection. + Used by the _instantiating_module property to lazily resolve the actual module object. + + This optimization avoids the expensive inspect.getmodule() call at init time, + deferring it until the module is actually needed (typically for --version). + """ + + _instantiating_module_cache: ModuleType | None | type[UNSET] = field(init=False, default=UNSET, repr=False) + """Cached module object resolved from _instantiating_module_name. + + Starts as UNSET sentinel value. On first access via the _instantiating_module property, + the module name is resolved to a module object from sys.modules and cached here. + Subsequent accesses return this cached value without re-resolution. + + Set to None if module name was not captured or module is not in sys.modules. + """ + + _fallback_console: Optional["Console"] = field(init=False, default=None) + + _fallback_error_console: Optional["Console"] = field(init=False, default=None) + + app_stack: AppStack = field(init=False, default=Factory(AppStack, takes_self=True)) + + def __attrs_post_init__(self): + # Trigger the setters + self.help_flags = self._help_flags + self.version_flags = self._version_flags + + # Capture the module name from the instantiating frame. + # This is cheap (just dict lookup) compared to inspect.getmodule(). + # inspect.stack()[2] is needed in attrs class because the call stack is deeper: + # [0]: __attrs_post_init__ + # [1]: the attrs-generated __init__ + # [2]: the caller who created the instance + try: + frame = sys._getframe(2) + self._instantiating_module_name = frame.f_globals.get("__name__") + except (IndexError, AttributeError): + self._instantiating_module_name = None + + ########### + # Methods # + ########### + def _delete_commands(self, commands: Iterable[str]): + """Safely delete commands. + + Will **not** raise an exception if command(s) do not exist. + + Parameters + ---------- + commands: Iterable[str, ...] + Strings of commands to delete. + """ + # Remove all the old version-flag commands. + for command in commands: + try: + del self[command] + except KeyError: + pass + + @property + def version_flags(self): + return self._version_flags + + @version_flags.setter + def version_flags(self, value): + self._delete_commands(self._version_flags) + self._version_flags = value + if self._version_flags: + self.command( + self.version_print, + name=self._version_flags, + help_flags=[], + version_flags=[], + version=self.version, + help="Display application version.", + ) + + @property + def help_flags(self): + return self._help_flags + + @help_flags.setter + def help_flags(self, value): + self._delete_commands(self._help_flags) + self._help_flags = value + if self._help_flags: + self.command( + self.help_print, + name=self._help_flags, + help_flags=[], + version_flags=[], + version=self.version, + help="Display this message and exit.", + ) + + @property + def name(self) -> tuple[str, ...]: + """Application name(s). Dynamically derived if not previously set.""" + if self._name: + return self._name + self.alias # pyright: ignore + elif self.default_command is None: + name = Path(sys.argv[0]).name + if name == "__main__.py": + name = _get_root_module_name() + return (name,) + self.alias # pyright: ignore + else: + try: + func_name = self.default_command.__name__ + except AttributeError: + # This could happen if default_command is wrapped in a functools.partial + func_name = self.default_command.func.__name__ # pyright: ignore[reportFunctionMemberAccess] + return (self.name_transform(func_name),) + self.alias # pyright: ignore + + @property + def group_arguments(self): + if self._group_arguments is None: + return Group.create_default_arguments() + return self._group_arguments + + @group_arguments.setter + def group_arguments(self, value): + self._group_arguments = value + + @property + def group_parameters(self): + if self._group_parameters is None: + return Group.create_default_parameters() + return self._group_parameters + + @group_parameters.setter + def group_parameters(self, value): + self._group_parameters = value + + @property + def group_commands(self): + if self._group_commands is None: + return Group.create_default_commands() + return self._group_commands + + @group_commands.setter + def group_commands(self, value): + self._group_commands = value + + @property + def config(self): + return self.app_stack.resolve("_config") + + @config.setter + def config(self, value): + self._config = value + + @property + def help(self) -> str: + if self._help is not None: + return self._help + elif self.default_command is None: + # Try and fallback to a meta-app docstring. + if self._meta is None: + return "" + else: + return self.meta.help + else: + # Try to handle a potential partial function + if "functools" in sys.modules: + from functools import partial + + if isinstance(self.default_command, partial): + doc = self.default_command.func.__doc__ + else: + doc = self.default_command.__doc__ + else: + doc = self.default_command.__doc__ + + if doc is None: + return "" + else: + return doc + + @help.setter + def help(self, value): + self._help = value + + @property + def name_transform(self): + return self._name_transform if self._name_transform else default_name_transform + + @name_transform.setter + def name_transform(self, value): + self._name_transform = value + + @property + def sort_key(self): + return None if self._sort_key is UNSET else self._sort_key + + @sort_key.setter + def sort_key(self, value): + self._sort_key = sort_key_converter(value) + + @property + def _registered_commands(self) -> dict[str, "App"]: + """Commands that are not help or version commands. + + This includes commands from flattened subapps. + """ + out = {} + for x in self: + if x in self.help_flags or x in self.version_flags: + continue + out[x] = self[x] + return out + + @property + def console(self) -> "Console": + result = self.app_stack.resolve("_console") + if result is not None: + return result + + # We always want to return back the same console object, + # but if someone manually overrides `console`, then + # we want to return that. + if self._fallback_console is None: + from rich.console import Console + + self._fallback_console = Console() + + return self._fallback_console + + @console.setter + def console(self, console: Optional["Console"]): + self._console = console + + @property + def error_console(self) -> "Console": + result = self.app_stack.resolve("_error_console") + if result is not None: + return result + + if self._fallback_error_console is None: + self._fallback_error_console = create_error_console_from_console(self.console) + + return self._fallback_error_console + + @error_console.setter + def error_console(self, console: Optional["Console"]): + self._error_console = console + + @property + def _instantiating_module(self) -> ModuleType | None: + """Lazily resolve the module name to a module object.""" + if self._instantiating_module_cache is UNSET: + if self._instantiating_module_name: + self._instantiating_module_cache = sys.modules.get(self._instantiating_module_name) + else: + self._instantiating_module_cache = None + return cast(ModuleType | None, self._instantiating_module_cache) + + def _get_fallback_version_string(self, default: str = "0.0.0") -> str: + """Get the version string with multiple fallback strategies. + + First tries to derive from the instantiating module, then tries to get it + from the calling code's module, and finally falls back to a default. + + Parameters + ---------- + default : str + Default version to use if no version can be determined. + + Returns + ------- + str + Version string. + """ + from importlib.metadata import PackageNotFoundError + from importlib.metadata import version as importlib_metadata_version + + if self._instantiating_module is not None: + full_module_name = self._instantiating_module.__name__ + root_module_name = full_module_name.split(".")[0] + try: + return importlib_metadata_version(root_module_name) + except PackageNotFoundError: + pass + + try: + return self._instantiating_module.__version__ # type: ignore[attr-defined] + except AttributeError: + pass + + try: + root_module_name = _get_root_module_name() + except _CannotDeriveCallingModuleNameError: # pragma: no cover + return default + + try: + return importlib_metadata_version(root_module_name) + except PackageNotFoundError: + pass + + # Attempt packagename.__version__ + # Not sure if this is redundant with ``importlib.metadata``, + # but there's no real harm in checking. + try: + module = importlib.import_module(root_module_name) + return module.__version__ # type: ignore[attr-defined] + except (ImportError, AttributeError): + pass + + return default + + def _format_and_print_version(self, version_raw: str, console: Optional["Console"]) -> None: + """Format and print the version string. + + Parameters + ---------- + version_raw : str + Raw version string to format and print. + console : ~rich.console.Console + Console to print to. + """ + from cyclopts.help import InlineText + + version_format = self.app_stack.resolve("version_format") + if version_format is None: + version_format = self.app_stack.resolve("help_format", fallback=DEFAULT_FORMAT) + version_formatted = InlineText.from_format(version_raw, format=version_format) + (console or self.console).print(version_formatted) + + def version_print( + self, + console: Annotated[Optional["Console"], Parameter(parse=False)] = None, + ) -> None: + """Print the application version. + + Parameters + ---------- + console: ~rich.console.Console + Console to print version string to. + If not provided, follows the resolution order defined in :attr:`App.console`. + + """ + if self.version is not None: + if callable(self.version): + # Note: async version callables are handled by _version_print_async + if inspect.iscoroutinefunction(self.version): + raise ValueError("async version handler detected. Use App.run_async within an async context.") + version_raw = cast(str, self.version()) + else: + version_raw = self.version + else: + version_raw = self._get_fallback_version_string() + + self._format_and_print_version(version_raw, console) + + async def _version_print_async( + self, + console: Annotated[Optional["Console"], Parameter(parse=False)] = None, + ) -> None: + """Async version of version_print for handling async version callables. + + Parameters + ---------- + console: ~rich.console.Console + Console to print version string to. + If not provided, follows the resolution order defined in :attr:`App.console`. + + """ + if self.version is not None: + if callable(self.version): + if inspect.iscoroutinefunction(self.version): + version_raw = await self.version() + else: + # This should never happen, since if ``self.version`` is callable + # and not async, then we would be using ``App.version_print``. + # This is only here for completeness. + version_raw = cast(str, self.version()) + else: + version_raw = self.version + else: + version_raw = self._get_fallback_version_string() + + self._format_and_print_version(version_raw, console) + + @property + def subapps(self): + for k in self: + yield self[k] + + def resolved_commands(self) -> dict[str, "App"]: + """Get all commands as resolved App instances. + + This function resolves any lazy-loaded commands (CommandSpec) into App instances. + Note: This will import modules for all lazy-loaded commands, which may impact performance + and memory usage. Consider accessing commands individually via ``app["command_name"]`` if + you don't need all commands at once. + + Returns + ------- + dict[str, App] + Mapping of command names to resolved :class:`App` instances. + + Examples + -------- + .. code-block:: python + + from cyclopts import App + + app = App() + app.command("myapp.commands:create") + app.command("myapp.commands:delete") + + # Resolve all lazy commands + commands = app.resolved_commands() + assert "create" in commands + assert isinstance(commands["create"], App) + """ + resolved = { + name: cmd.resolve(self) if isinstance(cmd, CommandSpec) else cmd for name, cmd in self._commands.items() + } + + # Add flattened subapp commands (parent commands take precedence) + for subapp in self._flattened_subapps: + for cmd_name in subapp: + if cmd_name not in resolved: + resolved[cmd_name] = subapp[cmd_name] + + return resolved + + def __getitem__(self, key: str) -> "App": + """Get the subapp from a command string. + + All commands get registered to Cyclopts as subapps. + The actual function handler is at ``app[key].default_command``. + + If the command was registered via lazy loading (import path string), + it will be imported and resolved on first access. + + Example usage: + + .. code-block:: python + + from cyclopts import App + + app = App() + app.command(App(name="foo")) + + + @app["foo"].command + def bar(): + print("Running bar.") + + + app() + """ + cmd = self._get_item(key) + # Resolve lazy commands on access + if isinstance(cmd, CommandSpec): + return cmd.resolve(self) + return cmd + + def _get_item(self, key, recurse_meta=True) -> "App | CommandSpec": + """Internal getter that returns App or unresolved CommandSpec.""" + if recurse_meta and self._meta: + with suppress(KeyError): + return self.meta._get_item(key, recurse_meta=True) + if self._meta_parent: + with suppress(KeyError): + return self._meta_parent._get_item(key, recurse_meta=False) + + # Check local commands first + if key in self._commands: + return self._commands[key] + + # Check flattened subapps + for subapp in self._flattened_subapps: + with suppress(KeyError): + return subapp._get_item(key, recurse_meta=False) + + raise KeyError(key) + + def __delitem__(self, key: str): + del self._commands[key] + + def __contains__(self, k: str) -> bool: + if k in self._commands: + return True + if self._meta_parent: + if k in self._meta_parent: + return True + for subapp in self._flattened_subapps: + if k in subapp: + return True + return False + + def __iter__(self) -> Iterator[str]: + """Iterate over command & meta command names. + + Example usage: + + .. code-block:: python + + from cyclopts import App + + app = App() + + + @app.command + def foo(): + pass + + + @app.command + def bar(): + pass + + + # help and version flags are treated as commands. + assert list(app) == ["--help", "-h", "--version", "foo", "bar"] + """ + commands = list(self._commands) + yield from commands + commands = set(commands) + + if self._meta_parent: + for command in self._meta_parent: + if command not in commands: + yield command + commands.add(command) + + for subapp in self._flattened_subapps: + for command in subapp: + if command not in commands: + yield command + commands.add(command) + + @property + def meta(self) -> "App": + if self._meta is None: + self._meta = type(self)( + help_flags=self.help_flags, + version_flags=self.version_flags, + group_commands=copy(self._group_commands), + group_arguments=copy(self._group_arguments), + group_parameters=copy(self._group_parameters), + result_action=self.result_action, + ) + self._meta._meta_parent = self + return self._meta + + def parse_commands( + self, + tokens: None | str | Iterable[str] = None, + *, + include_parent_meta=True, + ) -> tuple[tuple[str, ...], tuple["App", ...], list[str]]: + """Extract out the command tokens from a command. + + You are probably actually looking for :meth:`parse_args`. + + Parameters + ---------- + tokens: None | str | Iterable[str] + Either a string, or a list of strings to launch a command. + Defaults to ``sys.argv[1:]`` + include_parent_meta: bool + Controls whether parent meta apps are included in the execution path. + + When True (default): + - Parent meta apps (i.e. the "normal" app ) are added to the apps list. + - Meta app options are consumed while parsing commands. + - Used for getting the inheritance hierarchy. + + When False: + - Meta app options are treated as regular arguments. + - Used for getting the execution hierarchy. + + This parameter is primarily for internal use. + + Returns + ------- + tuple[str, ...] + Strings that are interpreted as a valid command chain. + tuple[App, ...] + The execution path - apps that will be invoked in order. + list[str] + The remaining non-command tokens. + """ + tokens = normalize_tokens(tokens) + + command_chain = [] + app = self + apps: list[App] = [] + unused_tokens = tokens + + def add_parent_metas(app): + """If ``app`` is a meta-app, also add it's "normal" app. + + We assume that ``app._meta`` will always invoke the ``app``. + """ + if not include_parent_meta: + return + meta_parents = [] + meta_parent = app + while (meta_parent := meta_parent._meta_parent) is not None: + meta_parents.append(meta_parent) + # The "root" non-meta app gets highest priority (first) + apps.extend(meta_parents[::-1]) + + add_parent_metas(app) + apps.append(app) + command_mapping = _combined_meta_command_mapping(app, recurse_parent_meta=include_parent_meta) + + unused_tokens = tokens + while unused_tokens: + token = unused_tokens[0] + app_or_spec = None + + # Try exact match first; O(1) + if token in command_mapping: + app_or_spec = command_mapping[token] + # Don't apply fuzzy matching to option-like tokens (starting with -) + # Fuzzy matching is for camelCase command names, not for flags like --h matching -h + # Issue #698 + elif not token.startswith("-"): + # Try fuzzy match (backward compatibility for camelCase commands) O(n). + # NOTE: This fuzzy matching is for v4 backward compatibility with + # _pascal_to_snake introduction. Consider removing in v5. + normalized_token = _normalize_for_matching(token) + # Also exclude option-like commands (--help, --version, etc.) from fuzzy matching. + # Prevents "version" from matching to "--version" + matches = [ + cmd_name + for cmd_name in command_mapping + if not cmd_name.startswith("-") and _normalize_for_matching(cmd_name) == normalized_token + ] + + if len(matches) == 1: + # Single fuzzy match found + app_or_spec = command_mapping[matches[0]] + elif len(matches) > 1: + # Ambiguous match - multiple commands match after normalization + raise ValueError(f"Ambiguous command '{token}'. Could match: {', '.join(sorted(matches))}.") + + if app_or_spec is None: + # Token is not a command. Try to consume it as a meta app parameter. + # This is only relevant when ``include_parent_meta==True``, because + # otherwise it will be handled by the natural parsing process. + if include_parent_meta: + remaining = self._consume_leading_meta_options(apps, unused_tokens) + if len(remaining) < len(unused_tokens): + # Some meta parameters were consumed, continue looking for commands + unused_tokens = remaining + continue + # Not a command or meta parameter, stop parsing commands + break + + # Resolve CommandSpec if needed (lazy loading) + # Note: CommandSpec.resolve() has built-in caching via its _resolved field + # Pass the current app as parent to inherit its defaults + if isinstance(app_or_spec, CommandSpec): + parent_app = app # Save parent before overwriting + app = app_or_spec.resolve(parent_app) + else: + app = app_or_spec + + # Found a command - add it to the chain + add_parent_metas(app) + apps.append(app) + command_mapping = _combined_meta_command_mapping(app, recurse_parent_meta=include_parent_meta) + command_chain.append(token) + unused_tokens = unused_tokens[1:] + + return tuple(command_chain), tuple(apps), unused_tokens + + def _get_resolution_context(self, execution_path: Sequence["App"]) -> list["App"]: + """Get all apps that contribute to parameter resolution for the given execution path. + + This includes parent meta apps and the meta app of the final command app. + + Parameters + ---------- + execution_path : Sequence[App] + The execution path returned from parse_commands. + + Returns + ------- + list[App] + All apps that contribute configuration and parameters, ordered by priority. + """ + apps = [] + + # For the last app in execution path, include it and its meta + if execution_path: + last_app = execution_path[-1] + # Include all metas from walk_metas (includes the app itself) + for app in _walk_metas(last_app): + if app not in apps: + apps.append(app) + + # Include parent metas from the stack if they exist + if last_app.app_stack.stack: + for app in last_app.app_stack.stack[-1]: + # Include the app's meta if it exists and isn't already in the list + if app._meta and app._meta not in apps: + # Check if last_app is a command from the meta app + is_meta_command = last_app in app._meta._commands.values() + if not is_meta_command: + apps.append(app._meta) + + return apps + + def _consume_leading_meta_options(self, apps: list["App"], tokens: list[str]) -> list[str]: + """Consume meta app options from the beginning of the token stream. + + This is used to skip over meta app parameters when looking for commands. + + Limitation: positional parameters for the meta app are NOT skipped. + This is because we do not know which meta-parameters are for the + meta-app itself vs which it will pass along to the normal app. + + Parameters + ---------- + apps: list[App] + Current app stack including parent meta apps. + tokens: list[str] + Tokens to try parsing, starting from current position. + + Returns + ------- + list[str] + The remaining unused tokens after consuming any leading meta options. + """ + if not apps or not tokens: + return tokens + + from cyclopts.bind import _parse_kw_and_flags + + # Resolve end_of_options_delimiter from the partially-resolved app stack + with self.app_stack(apps): + end_of_options_delimiter = self.app_stack.resolve("end_of_options_delimiter", fallback="--") + + # Collect meta apps that could have parameters + # We need both: + # 1. Meta apps in the current stack (apps that ARE meta apps) + # 2. The meta app of the current context (if it exists) + meta_apps_to_try = [app for app in apps if app._meta_parent is not None and app.default_command] + + # Add the current app's meta if it exists + if apps[-1]._meta and apps[-1]._meta.default_command: + meta_apps_to_try.append(apps[-1]._meta) + + # Try to parse with each meta app's parameters + unused_tokens = tokens + for meta_app in meta_apps_to_try: + try: + argument_collection = meta_app.assemble_argument_collection() + + # Try to consume tokens with this meta app's parameters + # stop_at_first_unknown=True ensures we only consume contiguous leading options + unused_tokens, _ = _parse_kw_and_flags( + argument_collection, + unused_tokens, + end_of_options_delimiter=end_of_options_delimiter, + stop_at_first_unknown=True, + ) + except Exception: + # If parsing fails, try next meta app + continue + + return unused_tokens + + # This overload is used in code like: + # + # @app.command + # def my_command(foo: str): + # ... + @overload + def command( # pragma: no cover + self, + obj: T, + name: None | str | Iterable[str] = None, + *, + alias: None | str | Iterable[str] = None, + **kwargs: object, + ) -> T: ... + + # This overload is used in code like: + # + # @app.command(name="bar") + # def my_command(foo: str): + # ... + @overload + def command( # pragma: no cover + self, + obj: None = None, + name: None | str | Iterable[str] = None, + *, + alias: None | str | Iterable[str] = None, + **kwargs: object, + ) -> Callable[[T], T]: ... + + # This overload is used for lazy loading: + # + # app.command("mymodule.commands:create_user", name="create") + @overload + def command( # pragma: no cover + self, + obj: str, + name: None | str | Iterable[str] = None, + *, + alias: None | str | Iterable[str] = None, + **kwargs: object, + ) -> None: ... + + def command( + self, + obj: T | None | str = None, + name: None | str | Iterable[str] = None, + *, + alias: None | str | Iterable[str] = None, + **kwargs: object, + ) -> T | Callable[[T], T] | None: + """Decorator to register a function as a CLI command. + + Example usage: + + .. code-block:: + + from cyclopts import App + + app = App() + + @app.command + def foo(): + print("foo!") + + @app.command(name="buzz") + def bar(): + print("bar!") + + # Lazy loading via import path + app.command("myapp.commands:create_user", name="create") + + app() + + .. code-block:: console + + $ my-script foo + foo! + + $ my-script buzz + bar! + + $ my-script create + # Imports and runs myapp.commands:create_user + + Parameters + ---------- + obj: Callable | App | str | None + Function, :class:`App`, or import path string to be registered as a command. + For lazy loading, provide a string in format "module.path:function_or_app_name". + name: None | str | Iterable[str] + Name(s) to register the command to. + If not provided, defaults to: + + * If registering an :class:`App`, then the app's name. + * If registering a **function**, then the function's name after applying :attr:`name_transform`. + * If registering via **import path**, then the attribute name after applying :attr:`name_transform`. + + Special value ``"*"`` flattens all sub-App commands into this app (App instances only). + See :ref:`Flattening SubCommands` for details. + `**kwargs` + Any argument that :class:`App` can take. + """ + if obj is None: # Called ``@app.command(...)`` + return partial(self.command, name=name, alias=alias, **kwargs) # pyright: ignore[reportReturnType] + + # Handle flattening: app.command(subapp, name="*") + if name == "*": + if not isinstance(obj, App): + raise TypeError( + 'Flattening (name="*") is only supported for App instances, not functions or import paths.' + ) + if kwargs: + raise ValueError('Cannot supply additional configuration when flattening a sub-App (name="*").') + + _apply_parent_defaults_to_app(obj, self) + self._flattened_subapps.append(obj) + return obj # pyright: ignore[reportReturnType] + + # Convert string path to a CommandSpec + if isinstance(obj, str): + # Determine command name(s) + if name is None: + # Extract from import path: "myapp.commands:create_user" -> "create-user" + _, _, func_name = obj.rpartition(":") + name = (self.name_transform(func_name),) + else: + name = to_tuple_converter(name) + + if alias is None: + alias = () + else: + alias = to_tuple_converter(alias) + + # Create CommandSpec with the resolved name (first name if multiple) + # The name will be used when wrapping functions in an App + # Pop CommandSpec-specific fields from kwargs before storing the rest as app_kwargs + spec = CommandSpec( + import_path=obj, + name=name[0] if name else None, + help=kwargs.pop("help", None), # type: ignore[arg-type] + sort_key=kwargs.pop("sort_key", None), + group=kwargs.pop("group", None), # type: ignore[arg-type] + show=kwargs.pop("show", None), # type: ignore[arg-type] + app_kwargs=kwargs, + ) + + # Register the CommandSpec + for n in name + alias: + if n in self: + raise CommandCollisionError(f'Command "{n}" already registered.') + self._commands[n] = spec + + return None + + if isinstance(obj, App): + app = obj + + if app._name is None and name is None: + raise ValueError("Sub-app MUST have a name specified.") + + if kwargs: + raise ValueError("Cannot supplied additional configuration when registering a sub-App.") + + _apply_parent_defaults_to_app(app, self) + else: + kwargs.setdefault("help_flags", self.help_flags) + kwargs.setdefault("version_flags", self.version_flags) + if "version" not in kwargs and self.version is not None: + kwargs["version"] = self.version + + _apply_parent_groups_to_kwargs(kwargs, self) + app = type(self)(**kwargs) # pyright: ignore + # directly call the default decorator, in case we do additional processing there. + app.default(obj) + + for flag in chain(app.help_flags, app.version_flags): + app[flag].show = False + + if app._name_transform is None: + app.name_transform = self.name_transform + + if name is None: + name = app.name + else: + name = to_tuple_converter(name) + + if alias is None: + alias = () + else: + alias = to_tuple_converter(alias) + + for n in name + alias: # pyright: ignore[reportOperatorIssue] + if n in self: + raise CommandCollisionError(f'Command "{n}" already registered.') + self._commands[n] = app + + return obj # pyright: ignore[reportReturnType] + + # This overload is used in code like: + # + # @app.default + # def my_command(foo: str): + # ... + @overload + def default( # pragma: no cover + self, + obj: T, + *, + validator: Callable[..., Any] | None = None, + ) -> T: ... + + # This overload is used in code like: + # + # @app.default() + # def my_command(foo: str): + # ... + @overload + def default( # pragma: no cover + self, + obj: None = None, + *, + validator: Callable[..., Any] | None = None, + ) -> Callable[[T], T]: ... + + def default( + self, + obj: T | None = None, + *, + validator: Callable[..., Any] | None = None, + ) -> T | Callable[[T], T]: + """Decorator to register a function as the default action handler. + + Example usage: + + .. code-block:: python + + from cyclopts import App + + app = App() + + + @app.default + def main(): + print("Hello world!") + + + app() + + .. code-block:: console + + $ my-script + Hello world! + """ + if obj is None: # Called ``@app.default_command(...)`` + return partial(self.default, validator=validator) # pyright: ignore[reportReturnType] + + if isinstance(obj, App): # Registering a sub-App + raise TypeError("Cannot register a sub-App to default.") + + if self.default_command is not None: + raise CommandCollisionError(f"Default command previously set to {self.default_command}.") + + validate_command(obj) + + self.default_command = obj + if validator: + self.validator = validator # pyright: ignore[reportAttributeAccessIssue] + return obj + + def assemble_argument_collection( + self, + *, + default_parameter: Parameter | None = None, + parse_docstring: bool = False, + ) -> ArgumentCollection: + """Assemble the argument collection for this app. + + Parameters + ---------- + default_parameter: Parameter | None + Default parameter with highest priority. + parse_docstring: bool + Parse the docstring of :attr:`default_command`. + Set to :obj:`True` if we need help strings, otherwise set to :obj:`False` for performance reasons. + + Returns + ------- + ArgumentCollection + All arguments for this app. + """ + if self.default_command is None: + raise ValueError( + "Cannot assemble argument collection: no default command is registered. " + "Use @app.default to register a default command, or access a specific " + "subcommand's argument collection via app['command_name'].assemble_argument_collection()." + ) + return ArgumentCollection._from_callable( + self.default_command, # pyright: ignore + Parameter.combine(self.app_stack.default_parameter, default_parameter), + group_arguments=self._group_arguments, # pyright: ignore + group_parameters=self._group_parameters, # pyright: ignore + parse_docstring=parse_docstring, + ) + + def parse_known_args( + self, + tokens: None | str | Iterable[str] = None, + *, + console: Optional["Console"] = None, + error_console: Optional["Console"] = None, + end_of_options_delimiter: str | None = None, + ) -> tuple[Callable[..., Any], inspect.BoundArguments, list[str], dict[str, Any]]: + """Interpret arguments into a registered function, :class:`~inspect.BoundArguments`, and any remaining unknown tokens. + + Parameters + ---------- + tokens: None | str | Iterable[str] + Either a string, or a list of strings to launch a command. + Defaults to ``sys.argv[1:]`` + console: ~rich.console.Console + Console to print help and runtime Cyclopts errors. + If not provided, follows the resolution order defined in :attr:`App.console`. + error_console: ~rich.console.Console + Console to print error messages. + If not provided, follows the resolution order defined in :attr:`App.error_console`. + end_of_options_delimiter: str | None + All tokens after this delimiter will be force-interpreted as positional arguments. + If None, inherits from :attr:`App.end_of_options_delimiter`, eventually defaulting to POSIX-standard ``"--"``. + Set to an empty string to disable. + + Returns + ------- + command: Callable + Bare function to execute. + + bound: inspect.BoundArguments + Bound arguments for ``command``. + + unused_tokens: list[str] + Any remaining CLI tokens that didn't get parsed for ``command``. + + ignored: dict[str, Any] + A mapping of python-variable-name to annotated type of any + parameter with annotation ``parse=False``. + :obj:`~typing.Annotated` will be resolved. + Intended to simplify :ref:`meta apps `. + """ + overrides = { + "_console": console, + "_error_console": error_console, + "end_of_options_delimiter": end_of_options_delimiter, + } + with self.app_stack([], overrides=overrides): + command, bound, unused_tokens, ignored, _ = self._parse_known_args(tokens) + + return command, bound, unused_tokens, ignored + + def _parse_known_args( + self, + tokens: None | str | Iterable[str] = None, + *, + raise_on_unused_tokens: bool = False, + ) -> tuple[Callable[..., Any], inspect.BoundArguments, list[str], dict[str, Any], ArgumentCollection]: + if tokens is None: + _log_framework_warning(_detect_test_framework()) + + tokens = normalize_tokens(tokens) + + meta_parent = self + + # We need both versions of the apps list: + # 1. apps_for_context (with parent metas) - for setting up the app_stack context + # 2. execution_apps (without parent metas) - for determining the actual execution command + # These can differ when parse_commands is called from a meta app, so we must + # call parse_commands twice. This is not inefficient since the parsing is fast. + _, apps_for_context, _ = self.parse_commands(tokens, include_parent_meta=True) + command_chain, execution_apps, unused_tokens = self.parse_commands(tokens, include_parent_meta=False) + + # We don't want the command_app to be the version/help handler; we handle those specially + command_app = execution_apps[-1] + with suppress(IndexError): + # Remove trailing help/version commands from the execution chain. + # When users provide multiple flags (e.g., "myapp cmd --help --help"), the parser + # may treat trailing help/version flags as commands in the chain. We must remove ALL + # such trailing commands and keep command_chain synchronized with execution_apps. + while command_chain and command_chain[-1] in set( + execution_apps[-2].help_flags + execution_apps[-2].version_flags # pyright: ignore[reportOperatorIssue] + ): + execution_apps = execution_apps[:-1] + command_chain = command_chain[:-1] + + command_app = execution_apps[-1] + del execution_apps # Always use AppStack from here-on. + + ignored: dict[str, Any] = {} + + with self.app_stack(apps_for_context): + config: tuple[Callable, ...] = command_app.app_stack.resolve("_config") or () + config = tuple(partial(x, command_app, command_chain) for x in config) + end_of_options_delimiter = self.app_stack.resolve("end_of_options_delimiter", fallback="--") + + # Special flags (help/version) get intercepted by the root app. + # Special flags are allows to be **anywhere** in the token stream. + + help_flag_index = _get_help_flag_index(tokens, command_app.help_flags, end_of_options_delimiter) + + try: + if help_flag_index is not None: + # Remove ALL help and version flags from both token lists. + # Users can provide multiple flags (e.g., "myapp --help --help --version"). + # When help is requested, it takes priority over version, so we remove all + # occurrences of both flag types to prevent downstream parsing errors. + flags_to_remove = set(command_app.help_flags + command_app.version_flags) # pyright: ignore[reportOperatorIssue] + tokens[:] = [t for t in tokens if t not in flags_to_remove] + unused_tokens[:] = [t for t in unused_tokens if t not in flags_to_remove] + + command = self.help_print + while meta_parent := meta_parent._meta_parent: + command = meta_parent.help_print + bound = inspect.signature(command).bind(tokens, console=command_app.console) + unused_tokens = [] + argument_collection = ArgumentCollection() + elif any(flag in tokens for flag in command_app.version_flags): + command = _get_version_command(command_app) + while meta_parent := meta_parent._meta_parent: + command = _get_version_command(meta_parent) + + bound = inspect.signature(command).bind(console=command_app.console) + unused_tokens = [] + argument_collection = ArgumentCollection() + else: + if command_app.default_command: + command = command_app.default_command + validate_command(command) + argument_collection = command_app.assemble_argument_collection() + ignored: dict[str, Any] = { + argument.field_info.name: resolve_annotated(argument.field_info.annotation) + for argument in argument_collection.filter_by(parse=False) + } + + bound, unused_tokens = create_bound_arguments( + command_app.default_command, + argument_collection, + unused_tokens, + config, + end_of_options_delimiter=end_of_options_delimiter, + ) + try: + for validator in command_app.validator: + validator(**bound.arguments) + except (AssertionError, ValueError, TypeError) as e: + raise ValidationError(exception_message=e.args[0] if e.args else "", app=command_app) from e + + try: + for command_group in command_app.app_stack.command_groups: + for validator in command_group.validator: # pyright: ignore + validator(**bound.arguments) + except (AssertionError, ValueError, TypeError) as e: + raise ValidationError( + exception_message=e.args[0] if e.args else "", + group=command_group, # pyright: ignore + ) from e + + else: + if unused_tokens: + raise UnknownCommandError(unused_tokens=unused_tokens) + else: + # Running the application with no arguments and no registered + # ``default_command`` will default to ``help_print``. + command = self.help_print + bound = inspect.signature(command).bind(tokens=tokens, console=command_app.console) + unused_tokens = [] + argument_collection = ArgumentCollection() + if raise_on_unused_tokens and unused_tokens: + for token in unused_tokens: + if is_option_like(token): + token = token.split("=")[0] + raise UnknownOptionError( + token=Token(keyword=token, source="cli"), + argument_collection=argument_collection, + ) + raise UnusedCliTokensError(target=command, unused_tokens=unused_tokens) + except CycloptsError as e: + e.target = command_app.default_command + e.app = command_app + if command_chain: + e.command_chain = command_chain + if e.console is None: + e.console = command_app.error_console + raise + + return command, bound, unused_tokens, ignored, argument_collection + + def parse_args( + self, + tokens: None | str | Iterable[str] = None, + *, + console: Optional["Console"] = None, + error_console: Optional["Console"] = None, + print_error: bool | None = None, + exit_on_error: bool | None = None, + help_on_error: bool | None = None, + verbose: bool | None = None, + end_of_options_delimiter: str | None = None, + error_formatter: Callable[["CycloptsError"], Any] | None = None, + ) -> tuple[Callable[..., Any], inspect.BoundArguments, dict[str, Any]]: + """Interpret arguments into a function and :class:`~inspect.BoundArguments`. + + Raises + ------ + UnusedCliTokensError + If any tokens remain after parsing. + + Parameters + ---------- + tokens: None | str | Iterable[str] + Either a string, or a list of strings to launch a command. + Defaults to ``sys.argv[1:]``. + console: ~rich.console.Console + Console to print help and runtime Cyclopts errors. + If not provided, follows the resolution order defined in :attr:`App.console`. + error_console: ~rich.console.Console + Console to print error messages. + If not provided, follows the resolution order defined in :attr:`App.error_console`. + print_error: bool | None + Print a rich-formatted error on error. + If :obj:`None`, inherits from :attr:`App.print_error`, eventually defaulting to :obj:`True`. + exit_on_error: bool | None + If there is an error parsing the CLI tokens invoke ``sys.exit(1)``. + Otherwise, continue to raise the exception. + If :obj:`None`, inherits from :attr:`App.exit_on_error`, eventually defaulting to :obj:`True`. + help_on_error: bool | None + Prints the help-page before printing an error. + If :obj:`None`, inherits from :attr:`App.help_on_error`, eventually defaulting to :obj:`False`. + verbose: bool | None + Populate exception strings with more information intended for developers. + If :obj:`None`, inherits from :attr:`App.verbose`, eventually defaulting to :obj:`False`. + end_of_options_delimiter: str | None + All tokens after this delimiter will be force-interpreted as positional arguments. + If :obj:`None`, inherits from :attr:`App.end_of_options_delimiter`, eventually defaulting to POSIX-standard ``"--"``. + Set to an empty string to disable. + + Returns + ------- + command: Callable + Function associated with command action. + + bound: inspect.BoundArguments + Parsed and converted ``args`` and ``kwargs`` to be used when calling ``command``. + + ignored: dict[str, Any] + A mapping of python-variable-name to type-hint of any parameter with annotation ``parse=False``. + :obj:`~typing.Annotated` will be resolved. + Intended to simplify :ref:`meta apps `. + """ + if tokens is None: + _log_framework_warning(_detect_test_framework()) + + tokens = normalize_tokens(tokens) + + # Store overrides for nested calls + overrides = { + k: v + for k, v in { + "_console": console, + "_error_console": error_console, + "print_error": print_error, + "exit_on_error": exit_on_error, + "help_on_error": help_on_error, + "verbose": verbose, + "end_of_options_delimiter": end_of_options_delimiter, + "error_formatter": error_formatter, + }.items() + if v is not None + } + + # overrides isn't being propagated to subcommands because they aren't provided to the context manager here. + with self.app_stack([], overrides=overrides): + try: + command, bound, _, ignored, _ = self._parse_known_args( + tokens, + raise_on_unused_tokens=True, + ) + except CycloptsError as e: + print_error = self.app_stack.resolve("print_error") + exit_on_error = self.app_stack.resolve("exit_on_error") + help_on_error = self.app_stack.resolve("help_on_error") + verbose = self.app_stack.resolve("verbose") + + e.verbose = verbose if verbose is not None else False + e.root_input_tokens = tokens + assert e.console is not None + if help_on_error if help_on_error is not None else False: + self.help_print(tokens, console=e.console) + if print_error if print_error is not None else True: + resolved_error_formatter = self.app_stack.resolve("error_formatter") + if resolved_error_formatter is not None: + e.console.print(resolved_error_formatter(e)) + else: + e.console.print(CycloptsPanel(e)) + if exit_on_error if exit_on_error is not None else True: + sys.exit(1) + raise + + return command, bound, ignored + + def _is_nested_call(self) -> bool: + """Check if this is a nested call (meta app pattern or same-app recursion).""" + return len(self.app_stack.overrides_stack) > 1 or ( + self._meta is not None and len(self._meta.app_stack.overrides_stack) > 1 + ) + + def __call__( + self, + tokens: None | str | Iterable[str] = None, + *, + console: Optional["Console"] = None, + error_console: Optional["Console"] = None, + print_error: bool | None = None, + exit_on_error: bool | None = None, + help_on_error: bool | None = None, + verbose: bool | None = None, + end_of_options_delimiter: str | None = None, + backend: Literal["asyncio", "trio"] | None = None, + result_action: ResultAction | None = None, + error_formatter: Callable[["CycloptsError"], Any] | None = None, + ) -> Any: + """Interprets and executes a command. + + Parameters + ---------- + tokens : None | str | Iterable[str] + Either a string, or a list of strings to launch a command. + Defaults to ``sys.argv[1:]``. + console: ~rich.console.Console + Console to print help and runtime Cyclopts errors. + If not provided, follows the resolution order defined in :attr:`App.console`. + error_console: ~rich.console.Console + Console to print error messages. + If not provided, follows the resolution order defined in :attr:`App.error_console`. + print_error: bool | None + Print a rich-formatted error on error. + If :obj:`None`, inherits from :attr:`App.print_error`, eventually defaulting to :obj:`True`. + exit_on_error: bool | None + If there is an error parsing the CLI tokens invoke ``sys.exit(1)``. + Otherwise, continue to raise the exception. + If :obj:`None`, inherits from :attr:`App.exit_on_error`, eventually defaulting to :obj:`True`. + help_on_error: bool | None + Prints the help-page before printing an error. + If :obj:`None`, inherits from :attr:`App.help_on_error`, eventually defaulting to :obj:`False`. + verbose: bool | None + Populate exception strings with more information intended for developers. + If :obj:`None`, inherits from :attr:`App.verbose`, eventually defaulting to :obj:`False`. + end_of_options_delimiter: str | None + All tokens after this delimiter will be force-interpreted as positional arguments. + If :obj:`None`, inherits from :attr:`App.end_of_options_delimiter`, eventually defaulting to POSIX-standard ``"--"``. + Set to an empty string to disable. + backend: Literal["asyncio", "trio"] | None + Override the async backend to use (if an async command is invoked). + If :obj:`None`, inherits from :attr:`App.backend`, eventually defaulting to "asyncio". + If passing backend="trio", ensure trio is installed via the extra: `cyclopts[trio]`. + result_action: ResultAction | None + Controls how command return values are handled. Can be a predefined literal string + or a custom callable that takes the result and returns a processed value. + If :obj:`None`, inherits from :attr:`App.result_action`, eventually defaulting to "print_non_int_return_int_as_exit_code". + See :attr:`App.result_action` for available modes. + + Returns + ------- + return_value: Any + The value the command function returns. + """ + if tokens is None: + _log_framework_warning(_detect_test_framework()) + + tokens = normalize_tokens(tokens) + + overrides = { + k: v + for k, v in { + "_console": console, + "_error_console": error_console, + "print_error": print_error, + "exit_on_error": exit_on_error, + "help_on_error": help_on_error, + "verbose": verbose, + "backend": backend, + "result_action": result_action, + "error_formatter": error_formatter, + }.items() + if v is not None + } + + if self._is_nested_call(): + overrides.setdefault("result_action", "return_value") + + with self.app_stack(tokens, overrides): + command, bound, _ = self.parse_args( + tokens, + console=console, + end_of_options_delimiter=end_of_options_delimiter, + ) + + resolved_backend = cast(Literal["asyncio", "trio"], self.app_stack.resolve("backend", fallback="asyncio")) + try: + result = _run_maybe_async_command(command, bound, resolved_backend) + return self._handle_result_action(result) + except KeyboardInterrupt: + if self.suppress_keyboard_interrupt: + sys.exit(130) # Use the same exit code as Python's default KeyboardInterrupt handling. + else: + raise + + async def run_async( + self, + tokens: None | str | Iterable[str] = None, + *, + console: Optional["Console"] = None, + error_console: Optional["Console"] = None, + print_error: bool | None = None, + exit_on_error: bool | None = None, + help_on_error: bool | None = None, + verbose: bool | None = None, + end_of_options_delimiter: str | None = None, + backend: Literal["asyncio", "trio"] | None = None, + result_action: ResultAction | None = None, + error_formatter: Callable[["CycloptsError"], Any] | None = None, + ) -> Any: + """Async equivalent of :meth:`__call__` for use within existing event loops. + + This method should be used when you're already in an async context + (e.g., Jupyter notebooks, existing async applications) and need to + execute a Cyclopts command without creating a new event loop. + + Parameters + ---------- + tokens : None | str | Iterable[str] + Either a string, or a list of strings to launch a command. + Defaults to ``sys.argv[1:]``. + console: ~rich.console.Console + Console to print help and runtime Cyclopts errors. + If not provided, follows the resolution order defined in :attr:`App.console`. + error_console: ~rich.console.Console + Console to print error messages. + If not provided, follows the resolution order defined in :attr:`App.error_console`. + print_error: bool | None + Print a rich-formatted error on error. + If :obj:`None`, inherits from :attr:`App.print_error`, eventually defaulting to :obj:`True`. + exit_on_error: bool | None + If there is an error parsing the CLI tokens invoke ``sys.exit(1)``. + Otherwise, continue to raise the exception. + If :obj:`None`, inherits from :attr:`App.exit_on_error`, eventually defaulting to :obj:`True`. + help_on_error: bool | None + Prints the help-page before printing an error. + If :obj:`None`, inherits from :attr:`App.help_on_error`, eventually defaulting to :obj:`False`. + verbose: bool | None + Populate exception strings with more information intended for developers. + If :obj:`None`, inherits from :attr:`App.verbose`, eventually defaulting to :obj:`False`. + end_of_options_delimiter: str | None + All tokens after this delimiter will be force-interpreted as positional arguments. + If :obj:`None`, inherits from :attr:`App.end_of_options_delimiter`, eventually defaulting to POSIX-standard ``"--"``. + Set to an empty string to disable. + backend: Literal["asyncio", "trio"] | None + Override the async backend to use (if an async command is invoked). + If :obj:`None`, inherits from :attr:`App.backend`, eventually defaulting to "asyncio". + If passing backend="trio", ensure trio is installed via the extra: `cyclopts[trio]`. + result_action: ResultAction | None + Controls how command return values are handled. Can be a predefined literal string + or a custom callable that takes the result and returns a processed value. + If :obj:`None`, inherits from :attr:`App.result_action`, eventually defaulting to "print_non_int_return_int_as_exit_code". + See :attr:`App.result_action` for available modes. + + Returns + ------- + return_value: Any + The value the command function returns. + + Examples + -------- + .. code-block:: python + + import asyncio + from cyclopts import App + + app = App() + + + @app.command + async def my_async_command(): + await asyncio.sleep(1) + return "Done!" + + + # In an async context (e.g., Jupyter notebook or existing async app): + async def main(): + result = await app.run_async(["my-async-command"]) + print(result) # Prints: Done! + + + asyncio.run(main()) + """ + if tokens is None: + _log_framework_warning(_detect_test_framework()) + + tokens = normalize_tokens(tokens) + + overrides = { + k: v + for k, v in { + "_console": console, + "_error_console": error_console, + "print_error": print_error, + "exit_on_error": exit_on_error, + "help_on_error": help_on_error, + "verbose": verbose, + "backend": backend, + "result_action": result_action, + "error_formatter": error_formatter, + }.items() + if v is not None + } + + if self._is_nested_call(): + overrides.setdefault("result_action", "return_value") + + with self.app_stack(tokens, overrides): + command, bound, _ = self.parse_args( + tokens, + console=console, + end_of_options_delimiter=end_of_options_delimiter, + ) + + try: + if inspect.iscoroutinefunction(command): + result = await command(*bound.args, **bound.kwargs) + else: + result = command(*bound.args, **bound.kwargs) + + return self._handle_result_action(result) + except KeyboardInterrupt: + if self.suppress_keyboard_interrupt: + sys.exit(130) # Use the same exit code as Python's default KeyboardInterrupt handling. + else: + raise + + def help_print( + self, + tokens: Annotated[None | str | Iterable[str], Parameter(show=False)] = None, + *, + console: Annotated[Optional["Console"], Parameter(parse=False)] = None, + ) -> None: + """Print the help page. + + Parameters + ---------- + tokens: None | str | Iterable[str] + Tokens to interpret for traversing the application command structure. + If not provided, defaults to ``sys.argv``. + console: ~rich.console.Console + Console to print help and runtime Cyclopts errors. + If not provided, follows the resolution order defined in :attr:`App.console`. + """ + from cyclopts.help import format_doc, format_usage + from cyclopts.help.formatters import DefaultFormatter + + tokens = normalize_tokens(tokens) + + command_chain, apps, _ = self.parse_commands(tokens) + executing_app = apps[-1] + overrides = {"_console": console} + with self.app_stack(apps, overrides=overrides): + console = executing_app.console + + # Prepare usage + if executing_app.usage is None: + usage = format_usage(self, command_chain) + elif executing_app.usage: # i.e. skip empty-string. + usage = executing_app.usage + "\n" + else: + usage = None + + # Prepare description + help_format = executing_app.app_stack.resolve("help_format", fallback=DEFAULT_FORMAT) + description = format_doc(executing_app, help_format) + + # Prepare panels with their associated groups + help_panels_with_groups = self._assemble_help_panels(tokens, help_format) + + # Render prologue + if help_prologue := executing_app.app_stack.resolve("help_prologue"): + from cyclopts.help import InlineText + + prologue = InlineText.from_format(help_prologue, format=help_format) + console.print(prologue) + console.print() # Add blank line after prologue + + # Render usage + default_formatter = executing_app.app_stack.resolve("help_formatter", fallback=DefaultFormatter()) + if hasattr(default_formatter, "render_usage"): + default_formatter.render_usage(console, console.options, usage) + elif usage: + console.print(usage) + + # Render description + if hasattr(default_formatter, "render_description"): + default_formatter.render_description(console, console.options, description) + elif description: + console.print(description) + + # Render each panel with its group's formatter (or default) + for group, panel in help_panels_with_groups: + formatter = group.help_formatter if group else None + if formatter is None: + formatter = default_formatter + formatter = cast("HelpFormatter", formatter) + formatter(console, console.options, panel) + + # Render epilogue + if help_epilogue := executing_app.app_stack.resolve("help_epilogue"): + from cyclopts.help import InlineText + + console.print() # Add blank line before epilogue + epilogue = InlineText.from_format(help_epilogue, format=help_format) + console.print(epilogue) + + def _assemble_help_panels( + self, + tokens: None | str | Iterable[str], + help_format, + ) -> list[tuple[Optional["Group"], "HelpPanel"]]: + from rich.console import Group as RichGroup + from rich.console import NewLine + + from cyclopts.help import ( + HelpPanel, + InlineText, + create_parameter_help_panel, + format_command_entries, + ) + + command_chain, execution_path, _ = self.parse_commands(tokens) + command_app = execution_path[-1] + + help_format = command_app.app_stack.resolve("help_format", help_format, DEFAULT_FORMAT) + + panels: dict[str, tuple[Group, HelpPanel]] = {} + # Handle commands first; there's an off chance they may be "upgraded" + # to an argument/parameter panel. + for subapp in _walk_metas(command_app): + for group, apps_with_names in groups_from_app(subapp): + if not group.show: + continue + + # Fetch a group's help-panel, or create it if it does not yet exist. + try: + _, command_panel = panels[group.name] + except KeyError: + command_panel = HelpPanel(title=group.name, format="command") + panels[group.name] = (group, command_panel) + + if group.help: + group_help = InlineText.from_format(group.help, format=help_format, force_empty_end=True) + + if command_panel.description: + command_panel.description = RichGroup(command_panel.description, NewLine(), group_help) + else: + command_panel.description = group_help + + # Add the command to the group's help panel. + command_panel.entries.extend(format_command_entries(apps_with_names, format=help_format)) + + # Handle Arguments/Parameters + # We have to combine all the help-pages of the command-app and it's meta apps. + # Use get_resolution_context to get all apps that contribute parameters + apps_for_params = self._get_resolution_context(execution_path) + + for subapp in apps_for_params: + if not subapp.default_command: + continue + + argument_collection = subapp.assemble_argument_collection(parse_docstring=True) + + # Special-case: add config.Env values to Parameter(env_var=) + configs: tuple[Callable, ...] = subapp.app_stack.resolve("_config") or () + env_configs = tuple(x for x in configs if isinstance(x, Env) and x.show) + for argument in argument_collection: + for env_config in env_configs: + env_var = env_config._convert_argument(command_chain, argument) + assert isinstance(argument.parameter.env_var, tuple) + argument.parameter = Parameter.combine( + argument.parameter, + Parameter(env_var=(*argument.parameter.env_var, env_var)), + ) + + for group in argument_collection.groups: + if not group.show: + continue + group_argument_collection = argument_collection.filter_by(group=group) + if not group_argument_collection: + continue + + _, existing_panel = panels.get(group.name, (None, None)) + new_panel = create_parameter_help_panel(group, group_argument_collection, help_format) + + if existing_panel: + # An imperfect merging process + existing_panel.format = "parameter" + new_panel.entries = new_panel.entries + existing_panel.entries # Commands go last + if new_panel.description: + if existing_panel.description: + new_panel.description = RichGroup( + existing_panel.description, NewLine(), new_panel.description + ) + else: + new_panel.description = existing_panel.description + + panels[group.name] = (group, new_panel) + + groups = [x[0] for x in panels.values()] + help_panels = [x[1] for x in panels.values()] + + out = [] + sorted_groups, sorted_panels = sort_groups(groups, help_panels) + for group, help_panel in zip(sorted_groups, sorted_panels, strict=False): + help_panel._remove_duplicates() + if help_panel.format == "command": + # don't sort format == "parameter" because order may matter there! + help_panel._sort() + out.append((group, help_panel)) + return out + + def generate_docs( + self, + output_format: "DocFormat" = "markdown", + recursive: bool = True, + include_hidden: bool = False, + heading_level: int = 1, + max_heading_level: int = 6, + flatten_commands: bool = False, + usage_name: str | None = None, + ) -> str: + """Generate documentation for this CLI application. + + Parameters + ---------- + output_format : DocFormat + Output format for the documentation. Accepts "markdown"/"md", "html"/"htm", + or "rst"/"rest"/"restructuredtext". Default is "markdown". + recursive : bool + If True, generate documentation for all subcommands recursively. + Default is True. + include_hidden : bool + If True, include hidden commands/parameters in documentation. + Default is False. + heading_level : int + Starting heading level for the main application title. + Default is 1 (single # for markdown, = for RST). + max_heading_level : int + Maximum heading level to use. Headings deeper than this will be capped + at this level. Standard Markdown and HTML support levels 1-6. + Default is 6. + flatten_commands : bool + If True, generate all commands at the same heading level instead of nested. + Default is False. + usage_name : str | None + Optional replacement for the root app name shown in ``Usage:`` lines + of the generated documentation. Useful when the runtime invocation + differs from the app's configured name — for example, an app named + ``"cli"`` that is typically invoked as ``uv run cli``. Only the + ``Usage:`` lines change; document titles, section headings, and + table-of-contents anchors continue to use ``app.name[0]``. + Default is None (use ``app.name[0]``). + + Returns + ------- + str + The generated documentation. + + Raises + ------ + ValueError + If an unsupported output format is specified. + + Examples + -------- + >>> app = App(name="myapp", help="My CLI Application") + >>> docs = app.generate_docs() # Generate markdown as string + >>> html_docs = app.generate_docs(output_format="html") # Generate HTML + >>> rst_docs = app.generate_docs(output_format="rst") # Generate RST + >>> # To write to file, caller can do: + >>> # Path("docs/cli.md").write_text(docs) + >>> # Override the invocation shown in Usage: lines (e.g., uv run cli) + >>> docs = app.generate_docs(usage_name="uv run cli") + """ + from cyclopts.docs import ( + generate_markdown_docs, + generate_rst_docs, + normalize_format, + ) + from cyclopts.docs.html import generate_html_docs + + output_format = normalize_format(output_format) + + if output_format == "markdown": + doc = generate_markdown_docs( + self, + recursive=recursive, + include_hidden=include_hidden, + heading_level=heading_level, + max_heading_level=max_heading_level, + flatten_commands=flatten_commands, + usage_name=usage_name, + ) + elif output_format == "html": + doc = generate_html_docs( + self, + recursive=recursive, + include_hidden=include_hidden, + heading_level=heading_level, + max_heading_level=max_heading_level, + flatten_commands=flatten_commands, + usage_name=usage_name, + ) + elif output_format == "rst": + doc = generate_rst_docs( + self, + recursive=recursive, + include_hidden=include_hidden, + heading_level=heading_level, + max_heading_level=max_heading_level, + flatten_commands=flatten_commands, + no_root_title=False, # Default to False for direct API usage + usage_name=usage_name, + ) + + return doc + + def generate_completion( + self, + *, + prog_name: str | None = None, + shell: Literal["zsh", "bash", "fish"] | None = None, + ) -> str: + """Generate shell completion script for this application. + + Parameters + ---------- + prog_name : str | None + Program name for completion. If None, uses first name from app.name. + shell : Literal["zsh", "bash", "fish"] | None + Shell type. If None, automatically detects current shell. + Supported shells: "zsh", "bash", "fish". + + Returns + ------- + str + Complete shell completion script. + + Examples + -------- + Auto-detect shell and generate completion: + + >>> app = App(name="myapp") + >>> script = app.generate_completion() + >>> Path("_myapp").write_text(script) + + Explicitly specify shell type: + + >>> script = app.generate_completion(shell="zsh") + + Raises + ------ + ValueError + If app has no name or shell type is unsupported. + ShellDetectionError + If shell is None and auto-detection fails. + """ + if prog_name is None: + if not self.name: + raise ValueError("App must have a name to generate completion script") + prog_name = self.name[0] if isinstance(self.name, tuple) else self.name + + if shell is None: + from cyclopts.completion import detect_shell + + shell = detect_shell() + + if shell == "zsh": + from cyclopts.completion.zsh import generate_completion_script + + return generate_completion_script(self, prog_name) + elif shell == "bash": + from cyclopts.completion.bash import generate_completion_script + + return generate_completion_script(self, prog_name) + elif shell == "fish": + from cyclopts.completion.fish import generate_completion_script + + return generate_completion_script(self, prog_name) + else: + raise ValueError(f"Unsupported shell: {shell}") + + def install_completion( + self, + *, + shell: Literal["zsh", "bash", "fish"] | None = None, + output: Path | None = None, + add_to_startup: bool = True, + ) -> Path: + """Install shell completion script to appropriate location. + + Generates and writes the completion script to a shell-specific location. + + Parameters + ---------- + shell : Literal["zsh", "bash", "fish"] | None + Shell type for completion. If not specified, attempts to auto-detect current shell. + output : Path | None + Output path for the completion script. If not specified, uses shell-specific default: + - zsh: ~/.zsh/completions/_ (or $ZSH_CUSTOM/completions/_ with oh-my-zsh) + - bash: ~/.local/share/bash-completion/completions/ + - fish: ~/.config/fish/completions/.fish + add_to_startup : bool + If True (default), adds source line to shell RC file to ensure completion is loaded. + Set to False if completions are already configured to auto-load. + + Returns + ------- + Path + Path where the completion script was installed. + + Examples + -------- + Auto-detect shell and install: + + >>> app = App(name="myapp") + >>> path = app.install_completion() + + Install for specific shell: + + >>> path = app.install_completion(shell="zsh") + + Install to custom path: + + >>> path = app.install_completion(output=Path("/custom/path")) + + Install without modifying RC files: + + >>> path = app.install_completion(shell="bash", add_to_startup=False) + + Raises + ------ + ShellDetectionError + If shell is None and auto-detection fails. + ValueError + If shell type is unsupported. + """ + from cyclopts.completion.detect import detect_shell + + if shell is None: + shell = detect_shell() + + from cyclopts.completion.install import add_to_rc_file, get_default_completion_path + + script_content = self.generate_completion(shell=shell) + + if output is None: + output = get_default_completion_path(shell, self.name[0]) + + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(script_content) + + # Fish does not need any startup script changes. + if add_to_startup and shell in ("bash", "zsh"): + add_to_rc_file(output, self.name[0], shell) + + return output + + def register_install_completion_command( + self, + name: str | Iterable[str] = "--install-completion", + add_to_startup: bool = True, + **kwargs, + ) -> None: + """Register a command for installing shell completion. + + This is a convenience method that creates a command which calls + :meth:`install_completion`. For more control over the command + implementation, users can manually define their own command. + + Parameters + ---------- + name : str | Iterable[str] + Command name(s) for the install completion command. + Defaults to "--install-completion". + add_to_startup : bool + If True (default), adds source line to shell RC file to ensure completion is loaded. + Set to False if completions are already configured to auto-load. + **kwargs + Additional keyword arguments to pass to :meth:`command`. + Can be used to customize the command registration (e.g., `help`, `group`, `help_flags`, `version_flags`). + + Examples + -------- + Register install-completion command: + + >>> app = App(name="myapp") + >>> app.register_install_completion_command() + >>> app() # Now responds to: myapp --install-completion + + Use a custom command name: + + >>> app.register_install_completion_command(name="--setup-completion") + + Customize help text: + + >>> app.register_install_completion_command(help="Install shell completion for myapp.") + + Customize command registration: + + >>> app.register_install_completion_command(group="Setup", help_flags=[]) + + Install without modifying RC files: + + >>> app.register_install_completion_command(add_to_startup=False) + + See Also + -------- + install_completion : The underlying method that performs the installation. + """ + from cyclopts.completion.install import create_install_completion_command + + command_fn = create_install_completion_command(self.install_completion, add_to_startup) + self.command(command_fn, name=name, **kwargs) + + def interactive_shell( + self, + prompt: str = "$ ", + quit: None | str | Iterable[str] = None, + dispatcher: Dispatcher | None = None, + console: "Console | None" = None, + exit_on_error: bool = False, + result_action: ResultAction | None = None, + **kwargs, + ) -> None: + """Create a blocking, interactive shell. + + All registered commands can be executed in the shell. + + Parameters + ---------- + prompt: str + Shell prompt. Defaults to ``"$ "``. + quit: str | Iterable[str] + String or list of strings that will cause the shell to exit and this method to return. + Defaults to ``["q", "quit"]``. + dispatcher: Dispatcher | None + Optional function that subsequently invokes the command. + The ``dispatcher`` function must have signature: + + .. code-block:: python + + def dispatcher(command: Callable, bound: inspect.BoundArguments, ignored: dict[str, Any]) -> Any: + return command(*bound.args, **bound.kwargs) + + The above is the default dispatcher implementation. + console: Console | None + Rich Console to use for output. If :obj:`None`, uses :attr:`App.console`. + exit_on_error: bool + Whether to call ``sys.exit`` on parsing errors. Defaults to :obj:`False`. + result_action: ResultAction | None + How to handle command return values in the interactive shell. + Defaults to ``"print_non_int_return_int_as_exit_code"`` which prints non-int results + and returns int/bool as exit codes without calling sys.exit. + If :obj:`None`, inherits from :attr:`App.result_action`. + `**kwargs` + Get passed along to :meth:`parse_args`. + """ + if os.name == "posix": # pragma: no cover + # Mac/Linux + print("Interactive shell. Press Ctrl-D to exit.") + else: # pragma: no cover + # Windows + print("Interactive shell. Press Ctrl-Z followed by Enter to exit.") + + if quit is None: + quit = ["q", "quit"] + if isinstance(quit, str): + quit = [quit] + + def default_dispatcher(command, bound, _): + return command(*bound.args, **bound.kwargs) + + if dispatcher is None: + dispatcher = default_dispatcher + + overrides = {} + if result_action is not None: + overrides["result_action"] = result_action + if console is not None: + overrides["_console"] = console + + while True: + try: + user_input = input(prompt) + except EOFError: # pragma: no cover + break + + tokens = normalize_tokens(user_input) + if not tokens: + continue + if tokens[0] in quit: + break + + try: + with self.app_stack(tokens, overrides): + command, bound, ignored = self.parse_args( + tokens, console=console, exit_on_error=exit_on_error, **kwargs + ) + result = dispatcher(command, bound, ignored) + self._handle_result_action(result, fallback="print_non_int_return_int_as_exit_code") + except CycloptsError: + # Upstream ``parse_args`` already printed the error + pass + except Exception: + print(traceback.format_exc()) + + def _handle_result_action(self, result: Any, fallback: ResultAction = "print_non_int_sys_exit") -> Any: + """Handle command result based on result_action. + + Parameters + ---------- + result : Any + The command's return value. + fallback : ResultAction + The fallback result_action if none is configured. Defaults to "print_non_int_sys_exit". + + Returns + ------- + Any + Processed result based on action (may call sys.exit() and not return). + """ + from cyclopts._result_action import handle_result_action + + action = cast( + ResultAction, + self.app_stack.resolve("result_action", fallback=fallback), + ) + + return handle_result_action(result, action, lambda x: self.console.print(x)) + + def update(self, app: "App"): + """Copy over all commands from another :class:`App`. + + Commands from the meta app will **not** be copied over. + + Parameters + ---------- + app: cyclopts.App + All commands from this application will be copied over. + """ + self._commands.update(app._commands) + + def __repr__(self): + """Only shows non-default values.""" + non_defaults = {} + for a in self.__attrs_attrs__: # pyright: ignore[reportAttributeAccessIssue] + if not a.init: + continue + v = getattr(self, a.name) + # Compare types first because of some weird attribute issues. + if type(v) != type(a.default) or v != a.default: # noqa: E721 + non_defaults[a.alias] = v + + signature = ", ".join(f"{k}={v!r}" for k, v in non_defaults.items()) + return f"{type(self).__name__}({signature})" + + +def _get_help_flag_index(tokens, help_flags, end_of_options_delimiter) -> int | None: + delimiter_index = None + if end_of_options_delimiter: + with suppress(ValueError): + delimiter_index = tokens.index(end_of_options_delimiter) + + for help_flag in help_flags: + with suppress(ValueError): + index = tokens.index(help_flag) + if delimiter_index is None or index < delimiter_index: + break + else: + index = None + + return index + + +class TestFramework(str, Enum): + UNKNOWN = "" + PYTEST = "pytest" + + +@lru_cache +def _detect_test_framework() -> TestFramework: + """Detects if we are currently being ran in a test framework. + + Returns + ------- + TestFramework + Name of the testing framework. Returns an empty string if not testing + framework discovered. + """ + # Check if pytest is in sys.modules; PYTEST_VERSION can be set if + # a cyclopts script is invoked via subprocess within a pytest unit-test. + if "pytest" in sys.modules and os.environ.get("PYTEST_VERSION") is not None: + # "PYTEST_VERSION" is set as of pytest v8.2.0 (Apr 27, 2024) + return TestFramework.PYTEST + else: + return TestFramework.UNKNOWN + + +@lru_cache # Prevent logging of multiple warnings +def _log_framework_warning(framework: TestFramework) -> None: + """Log a warning message for a given testing framework. + + Intended to catch developers invoking their app during unit-tests + without providing commands and erroneously reading from :obj:`sys.argv`. + + TO ONLY BE CALLED WITHIN A CYCLOPTS.APP METHOD. + """ + if framework == TestFramework.UNKNOWN: + return + import warnings + + for elem in inspect.stack(): + frame = elem.frame + f_back = frame.f_back + calling_module = inspect.getmodule(f_back) + if calling_module is None or f_back is None: + continue + calling_module_name = calling_module.__name__.split(".")[0] + if calling_module_name == "cyclopts": + continue + + # The "self" is within the Cyclopts codebase App.ANY_METHOD_HERE, + # so this is a safe lookup. Skip if self doesn't exist (e.g., standalone functions). + if "self" not in frame.f_locals: + continue + called_cyclopts_app_instance = frame.f_locals["self"] + # Find the variable name in the previous frame that references this object + candidate_variables = {**f_back.f_globals, **f_back.f_locals} + matched_app_variables = [] + for var_name, var_instance in candidate_variables.items(): + if var_instance is called_cyclopts_app_instance: + matched_app_variables.append(var_name) + if len(matched_app_variables) != 1: + # We could not determine the exact variable name; just call it app + var_name = "app" + else: + var_name = matched_app_variables[0] + + message = f'Cyclopts application invoked without tokens under unit-test framework "{framework.value}". Did you mean "{var_name}([])"?' + warnings.warn(UserWarning(message), stacklevel=3) + break diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2316d4d872a8a7f2a8619c61ff10426e5a2f568b --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/__init__.py @@ -0,0 +1,21 @@ +"""Documentation generation for cyclopts CLI applications.""" + +from cyclopts.docs.html import generate_html_docs +from cyclopts.docs.markdown import generate_markdown_docs +from cyclopts.docs.rst import generate_rst_docs +from cyclopts.docs.types import ( + FORMAT_ALIASES, + CanonicalDocFormat, + DocFormat, + normalize_format, +) + +__all__ = [ + "generate_html_docs", + "generate_markdown_docs", + "generate_rst_docs", + "DocFormat", + "CanonicalDocFormat", + "FORMAT_ALIASES", + "normalize_format", +] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/base.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/base.py new file mode 100644 index 0000000000000000000000000000000000000000..63d98f127213e71e304ecc97635e06791aa5316f --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/base.py @@ -0,0 +1,534 @@ +"""Base utilities for documentation generation.""" + +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from cyclopts.core import App + from cyclopts.help import HelpPanel + +from cyclopts.command_spec import CommandSpec +from cyclopts.help import format_doc, format_usage + + +def should_show_usage(app: "App") -> bool: + """Determine if usage should be shown for an app. + + Root apps always show usage (even without default_command, showing "app COMMAND"). + Subcommands only show usage if they have a default_command. + This skips usage for command groups that can't be invoked directly. + + The determination is made by checking the app_stack depth: + - Stack length of 1 means root app (just the initial frame) + - Stack length > 1 means we're in a subcommand context (frames were pushed) + + Parameters + ---------- + app : App + The App instance to check. + + Returns + ------- + bool + True if usage should be shown. + """ + # Check if we're in a subcommand context by examining the stack depth + is_root = len(app.app_stack.stack) == 1 + + if is_root: + # Root app: always show usage + return True + else: + # Subcommand: only show if it has a default_command + return app.default_command is not None + + +def should_show_commands_list(app: "App") -> bool: + """Determine if commands list should be shown for an app. + + Only show commands list for apps with a default_command. + Command groups (apps without default_command) skip the list + since their commands will be documented recursively anyway. + + Parameters + ---------- + app : App + The App instance to check. + + Returns + ------- + bool + True if commands list should be shown. + """ + return app.default_command is not None + + +def _is_builtin_flag(app: "App", name: str) -> bool: + """Check if a flag name is a built-in help or version flag. + + Parameters + ---------- + app : App + The App instance to check against. + name : str + The flag name to check. + + Returns + ------- + bool + True if this is a built-in help or version flag. + """ + help_flags = set(app.app_stack.resolve("help_flags", fallback=())) + version_flags = set(app.app_stack.resolve("version_flags", fallback=())) + builtin_flags = help_flags | version_flags + return name in builtin_flags + + +def is_all_builtin_flags(app: "App", names: Sequence[str]) -> bool: + """Check if all names in the sequence are builtin help or version flags. + + Parameters + ---------- + app : App + The App instance to check against. + names : Sequence[str] + Sequence of flag names to check. + + Returns + ------- + bool + True if all names are builtin flags. + """ + if not names: + return False + return all(_is_builtin_flag(app, name) for name in names) + + +def normalize_command_filters( + commands_filter: list[str] | None = None, + exclude_commands: list[str] | None = None, +) -> tuple[set[str] | None, set[str] | None]: + """Normalize command filter lists by converting underscores to dashes. + + Parameters + ---------- + commands_filter : list[str] | None + List of commands to include. + exclude_commands : list[str] | None + List of commands to exclude. + + Returns + ------- + tuple[set[str] | None, set[str] | None] + Normalized include and exclude sets for O(1) lookup. + """ + normalized_include = None + if commands_filter is not None: + normalized_include = {cmd.replace("_", "-") for cmd in commands_filter} + + normalized_exclude = None + if exclude_commands: + normalized_exclude = {cmd.replace("_", "-") for cmd in exclude_commands} + + return normalized_include, normalized_exclude + + +def should_include_command( + name: str, + parent_path: list[str], + normalized_commands_filter: set[str] | None, + normalized_exclude_commands: set[str] | None, + subapp: "App", +) -> bool: + """Determine if a command should be included based on filters. + + Parameters + ---------- + name : str + The command name. + parent_path : list[str] + Path to parent commands. + normalized_commands_filter : set[str] | None + Set of commands to include (already normalized). + normalized_exclude_commands : set[str] | None + Set of commands to exclude (already normalized). + subapp : App + The subcommand App instance. + + Returns + ------- + bool + True if the command should be included, False otherwise. + """ + full_path = ".".join(parent_path + [name]) if parent_path else name + + if normalized_exclude_commands: + if name in normalized_exclude_commands or full_path in normalized_exclude_commands: + return False + for i in range(len(parent_path)): + parent_segment = ".".join(parent_path[: i + 1]) + if parent_segment in normalized_exclude_commands: + return False + + if normalized_commands_filter is not None: + if name in normalized_commands_filter or full_path in normalized_commands_filter: + return True + + for i in range(len(parent_path)): + parent_segment = ".".join(parent_path[: i + 1]) + if parent_segment in normalized_commands_filter: + return True + + if hasattr(subapp, "_commands") and subapp._commands: + for filter_cmd in normalized_commands_filter: + if filter_cmd.startswith(full_path + "."): + return True + + return False + + return True + + +def adjust_filters_for_subcommand( + name: str, + normalized_commands_filter: set[str] | None, + normalized_exclude_commands: set[str] | None, +) -> tuple[list[str] | None, list[str] | None]: + """Adjust filter lists for subcommand context. + + Parameters + ---------- + name : str + The current command name. + normalized_commands_filter : set[str] | None + Set of commands to include (already normalized). + normalized_exclude_commands : set[str] | None + Set of commands to exclude (already normalized). + + Returns + ------- + tuple[list[str] | None, list[str] | None] + Adjusted commands_filter and exclude_commands lists (denormalized). + """ + sub_commands_filter = None + if normalized_commands_filter is not None: + sub_commands_filter = [] + for filter_cmd in normalized_commands_filter: + if filter_cmd.startswith(name + "."): + sub_filter = filter_cmd[len(name) + 1 :] + sub_commands_filter.append(sub_filter.replace("-", "_")) + elif filter_cmd == name: + sub_commands_filter = None + break + + if sub_commands_filter is not None and not sub_commands_filter: + sub_commands_filter = [] + + sub_exclude_commands = None + if normalized_exclude_commands: + sub_exclude_commands = [] + for exclude_cmd in normalized_exclude_commands: + if exclude_cmd.startswith(name + "."): + sub_exclude = exclude_cmd[len(name) + 1 :] + sub_exclude_commands.append(sub_exclude.replace("-", "_")) + else: + sub_exclude_commands.append(exclude_cmd.replace("-", "_")) + + return sub_commands_filter, sub_exclude_commands + + +def get_app_info(app: "App", command_chain: list[str] | None = None) -> tuple[str, str, str]: + """Get app name, full command path, and title. + + Parameters + ---------- + app : App + The cyclopts App instance. + command_chain : Optional[List[str]] + Chain of parent commands leading to this app. + + Returns + ------- + Tuple[str, str, str] + (app_name, full_command, title) + """ + if not command_chain: + app_name = app.name[0] + full_command = app_name + title = app_name + else: + app_name = command_chain[0] + full_command = " ".join(command_chain) + title = full_command + + return app_name, full_command, title + + +def build_command_chain(command_chain: list[str] | None, command_name: str, app_name: str) -> list[str]: + """Build command chain for a subcommand. + + Parameters + ---------- + command_chain : Optional[List[str]] + Current command chain. + command_name : str + Name of the subcommand. + app_name : str + Name of the root app. + + Returns + ------- + List[str] + Updated command chain. + """ + if command_chain: + return command_chain + [command_name] + else: + return [app_name, command_name] + + +def apply_usage_name(command_chain: list[str], usage_name: str | None) -> list[str]: + """Return a display command chain with the root replaced by ``usage_name``. + + When ``usage_name`` is ``None``, returns ``command_chain`` unchanged so callers + can use this helper unconditionally. When ``usage_name`` is ``""``, the root + token is dropped rather than substituted, so downstream formatters never see + an empty element (which would render as stray leading/internal whitespace). + When the chain is empty and ``usage_name`` is a non-empty string, returns a + single-element list containing ``usage_name``. + + Parameters + ---------- + command_chain : list[str] + The logical command chain (root app name first). + usage_name : str | None + Replacement for the chain's root element used in Usage: lines only. + An empty string drops the root token entirely. + + Returns + ------- + list[str] + A new list with the root replaced/dropped, or the original chain when + ``usage_name`` is ``None``. + """ + if usage_name is None: + return command_chain + if usage_name == "": + return command_chain[1:] + if not command_chain: + return [usage_name] + return [usage_name, *command_chain[1:]] + + +def generate_anchor(command_path: str) -> str: + """Generate a URL-friendly anchor from a command path. + + Converts spaces to hyphens and lowercases the string to match + how markdown/HTML processors generate anchors from headings. + Strips leading dashes to match markdown processor behavior. + + Parameters + ---------- + command_path : str + Full command path (e.g., "myapp files cp"). + + Returns + ------- + str + Anchor string (e.g., "myapp-files-cp"). + + Examples + -------- + >>> generate_anchor("myapp files cp") + 'myapp-files-cp' + >>> generate_anchor("myapp --install-completion") + 'myapp-install-completion' + """ + anchor = command_path.lower().replace(" ", "-") + # Collapse consecutive dashes to single dash (markdown processors do this) + anchor = re.sub(r"-+", "-", anchor) + return anchor + + +def should_skip_command(command_name: str, subapp: "App", parent_app: "App", include_hidden: bool) -> bool: + """Check if a command should be skipped. + + Parameters + ---------- + command_name : str + Name of the command. + subapp : App + The subcommand App instance. + parent_app : App + The parent App instance. + include_hidden : bool + Whether to include hidden commands. + + Returns + ------- + bool + True if command should be skipped. + """ + if _is_builtin_flag(parent_app, command_name): + return True + + if not isinstance(subapp, type(parent_app)): + return True + + if not include_hidden and not subapp.show: + return True + + return False + + +def filter_help_entries(app: "App", panel: "HelpPanel", include_hidden: bool) -> list[Any]: + """Filter help panel entries based on visibility settings. + + Parameters + ---------- + app : App + The App instance to check against. + panel : HelpPanel + The help panel to filter. + include_hidden : bool + Whether to include hidden entries. + + Returns + ------- + List[Any] + Filtered panel entries. + """ + if include_hidden: + return panel.entries + + return [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))] + + +def extract_description(app: "App", help_format: str) -> Any | None: + """Extract app description. + + Parameters + ---------- + app : App + The App instance. + help_format : str + Help format type. + + Returns + ------- + Optional[Any] + The extracted description object, or None. + """ + description = format_doc(app, help_format) + return description + + +def extract_usage(app: "App") -> Any | None: + """Extract usage string. + + Parameters + ---------- + app : App + The App instance. + + Returns + ------- + Optional[Any] + The extracted usage object, or None. + """ + if app.usage is not None: + return app.usage if app.usage else None + + usage = format_usage(app, []) + return usage + + +def format_usage_line(usage_text: str, command_chain: list[str], prefix: str = "") -> str: + """Format usage line with proper command path. + + Parameters + ---------- + usage_text : str + Raw usage text. + command_chain : List[str] + Command chain for the app. + prefix : str + Optional prefix for the usage line (e.g., "$"). + + Returns + ------- + str + Formatted usage line. + """ + if not usage_text: + return "" + + if "Usage:" in usage_text: + usage_text = usage_text.replace("Usage:", "").strip() + + full_command = " ".join(command_chain) if command_chain else "" + + parts = usage_text.split(None, 1) + if len(parts) > 1 and command_chain: + usage_line = f"{prefix} {full_command} {parts[1]}" if prefix else f"{full_command} {parts[1]}" + elif command_chain: + usage_line = f"{prefix} {full_command}" if prefix else full_command + else: + usage_line = f"{prefix} {usage_text}" if prefix else usage_text + + return usage_line.strip() + + +def iterate_commands(app: "App", include_hidden: bool = False, resolve_lazy: bool = True): + """Iterate through app commands, yielding valid resolved subapps. + + Automatically resolves CommandSpec instances to App instances. + Each unique subapp is yielded only once (first occurrence wins). + + Parameters + ---------- + app : App + The App instance. + include_hidden : bool + Whether to include hidden commands. + resolve_lazy : bool + If ``True`` (default), resolve lazy commands (import their modules) to + include them in the output. If ``False``, skip unresolved lazy commands. + Set to ``True`` when generating static artifacts that need all commands, + such as documentation or shell completion scripts. + + Yields + ------ + Tuple[str, App] + (command_name, resolved_subapp) for each valid command. + """ + if not app._commands: + return + + seen: set[int] = set() + + for name, app_or_spec in app._commands.items(): + if _is_builtin_flag(app, name): + continue + + if isinstance(app_or_spec, CommandSpec): + if not app_or_spec.is_resolved and not resolve_lazy: + continue + subapp = app_or_spec.resolve(app) + else: + subapp = app_or_spec + + if not isinstance(subapp, type(app)): + continue + + if not include_hidden and not subapp.show: + continue + + # Skip if we've already yielded this app (alias) + app_id = id(subapp) + if app_id in seen: + continue + seen.add(app_id) + + yield name, subapp diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/html.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/html.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2fd0e23ca1a094882dca44d88ccad258ae4ce0 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/html.py @@ -0,0 +1,623 @@ +"""HTML documentation generation for cyclopts apps.""" + +from typing import TYPE_CHECKING + +from cyclopts._markup import escape_html, extract_text +from cyclopts.docs.base import ( + apply_usage_name, + build_command_chain, + extract_description, + extract_usage, + filter_help_entries, + format_usage_line, + generate_anchor, + iterate_commands, +) + +if TYPE_CHECKING: + from cyclopts.core import App + + +def _generate_html_toc( + lines: list[str], + app: "App", + include_hidden: bool, + app_name: str, + prefix: str, + depth: int = 0, +) -> None: + """Recursively generate HTML table of contents.""" + if not app._commands: + return + + for name, subapp in iterate_commands(app, include_hidden): + display_name = f"{prefix}{name}" if prefix else name + full_path = f"{app_name}-{display_name.replace(' ', '-')}".lower() + + indent = " " * (depth + 1) + lines.append(f'{indent}
  • {name}') + + if subapp._commands: + lines.append(f"{indent}
      ") + _generate_html_toc(lines, subapp, include_hidden, app_name, f"{display_name} ", depth + 1) + lines.append(f"{indent}
    ") + + lines.append(f"{indent}
  • ") + + +# CSS styles embedded as a string - clean, modern design +DEFAULT_CSS = """ +:root { + --bg-color: #ffffff; + --text-color: #333333; + --border-color: #e0e0e0; + --code-bg: #f5f5f5; + --link-color: #0066cc; + --header-bg: #f8f9fa; + --required-color: #d73027; +} + +* { + box-sizing: border-box; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + line-height: 1.6; + color: var(--text-color); + background: var(--bg-color); + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +h1, h2, h3, h4, h5, h6 { + margin-top: 24px; + margin-bottom: 16px; + font-weight: 600; + line-height: 1.25; +} + +h1 { font-size: 2em; border-bottom: 2px solid var(--border-color); padding-bottom: 0.3em; } +h2 { font-size: 1.5em; border-bottom: 1px solid var(--border-color); padding-bottom: 0.3em; } +h3 { font-size: 1.25em; } +h4 { font-size: 1em; } + +code { + background: var(--code-bg); + padding: 2px 6px; + border-radius: 3px; + font-family: 'Courier New', Consolas, monospace; + font-size: 0.9em; +} + +pre { + background: var(--code-bg); + padding: 16px; + border-radius: 6px; + overflow-x: auto; + font-family: 'Courier New', Consolas, monospace; + font-size: 0.9em; +} + +pre code { + background: none; + padding: 0; +} + +.usage-block { + margin: 16px 0; +} + +.usage { + background: #f8f9fa; + border-left: 4px solid #0066cc; +} + +.description, .app-description, .command-description { + margin: 16px 0; + color: var(--text-color); +} + +.panel-description { + margin: 12px 0; + color: #666; +} + +.help-panel { + margin: 24px 0; +} + +/* List styles for commands and parameters */ +.commands-list, .parameters-list { + list-style: none; + padding-left: 0; + margin: 16px 0; +} + +.commands-list li, .parameters-list li { + padding: 8px 0; + border-bottom: 1px solid var(--border-color); +} + +.commands-list li:last-child, .parameters-list li:last-child { + border-bottom: none; +} + +.commands-list code, .parameters-list code { + font-weight: 600; +} + +/* Metadata styling */ +.parameter-metadata { + display: inline-flex; + gap: 8px; + margin-left: 8px; + flex-wrap: wrap; + align-items: center; +} + +.metadata-item { + display: inline-block; + padding: 2px 8px; + font-size: 0.85em; + border-radius: 4px; + background: var(--code-bg); + border: 1px solid var(--border-color); +} + +.metadata-required { + background: #fee; + border-color: #fcc; + color: #c00; + font-weight: 600; +} + +.metadata-default { + background: #f0f8ff; + border-color: #d0e8ff; + color: #0066cc; +} + +.metadata-env { + background: #f0fff0; + border-color: #d0ffd0; + color: #080; +} + +.metadata-choices { + background: #fffaf0; + border-color: #ffd0a0; + color: #840; +} + +.metadata-label { + font-weight: 600; + opacity: 0.8; + text-transform: uppercase; + font-size: 0.9em; +} + +/* Table of Contents */ +.table-of-contents { + background: var(--header-bg); + border-radius: 6px; + padding: 16px; + margin: 24px 0; +} + +.table-of-contents h2 { + margin-top: 0; + border-bottom: none; + padding-bottom: 0; +} + +.table-of-contents ul { + margin: 8px 0; + padding-left: 24px; +} + +.table-of-contents li { + margin: 4px 0; +} + +.table-of-contents a { + color: var(--link-color); + text-decoration: none; +} + +.table-of-contents a:hover { + text-decoration: underline; +} + +/* General link styles */ +a { + color: var(--link-color); + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +.commands-list a code { + color: var(--link-color); +} + +/* Back to top link */ +.back-to-top { + display: inline-block; + margin-top: 8px; + font-size: 0.9em; + opacity: 0.7; +} + +.back-to-top:hover { + opacity: 1; +} + +/* Responsive design */ +@media (max-width: 768px) { + body { + padding: 10px; + } + + .commands-list, .parameters-list { + font-size: 0.9em; + } +} + +/* Dark mode support */ +@media (prefers-color-scheme: dark) { + :root { + --bg-color: #1e1e1e; + --text-color: #e0e0e0; + --border-color: #444; + --code-bg: #2d2d2d; + --link-color: #66b3ff; + --header-bg: #2d2d2d; + } + + .usage { + background: #2d2d2d; + border-left-color: #66b3ff; + } + + .table-of-contents { + background: #2d2d2d; + } + + .metadata-required { + background: #4a2020; + border-color: #6a3030; + color: #ff9999; + } + + .metadata-default { + background: #20304a; + border-color: #304060; + color: #99ccff; + } + + .metadata-env { + background: #204a20; + border-color: #306030; + color: #99ff99; + } + + .metadata-choices { + background: #4a3020; + border-color: #604030; + color: #ffcc99; + } +} + +/* Command sections */ +.command-section { + margin-top: 32px; + padding-top: 16px; + border-top: 2px solid var(--border-color); +} + +.command-section:first-child { + border-top: none; +} +""" + + +def generate_html_docs( + app: "App", + recursive: bool = True, + include_hidden: bool = False, + heading_level: int = 1, + max_heading_level: int = 6, + standalone: bool = True, + custom_css: str | None = None, + command_chain: list[str] | None = None, + generate_toc: bool = True, + flatten_commands: bool = False, + usage_name: str | None = None, +) -> str: + """Generate HTML documentation for a CLI application. + + Parameters + ---------- + app : App + The cyclopts App instance to document. + recursive : bool + If True, generate documentation for all subcommands recursively. + Default is True. + include_hidden : bool + If True, include hidden commands/parameters in documentation. + Default is False. + heading_level : int + Starting heading level for the main application title. + Default is 1. + max_heading_level : int + Maximum heading level to use. Headings deeper than this will be capped + at this level. HTML supports levels 1-6. + Default is 6. + standalone : bool + If True, generate a complete HTML document with , , etc. + If False, generate only the body content. Default is True. + custom_css : str + Custom CSS to use instead of the default styles. + command_chain : list[str] + Internal parameter to track command hierarchy. + Default is None. + generate_toc : bool + If True, generate a table of contents for multi-command apps. + Default is True. + flatten_commands : bool + If True, generate all commands at the same heading level instead of nested. + Default is False. + usage_name : str | None + Optional replacement for the root app name in every ``Usage:`` line + (root and subcommands). Section headings and anchors continue to use + ``app.name[0]``. Default is None. + + Returns + ------- + str + The generated HTML documentation. + """ + from cyclopts.help.formatters.html import HtmlFormatter + + # Initialize command chain if not provided + if command_chain is None: + command_chain = [] + + # Build the main documentation + lines = [] + + # Only add the outer div for standalone documents or root level + if standalone or not command_chain: + lines.append('
    ') + + # Determine the app name and full command path + if not command_chain: + # Root level - use app name or derive from sys.argv + app_name = app.name[0] + full_command = app_name + title = app_name + # Add title for all levels + effective_level = min(heading_level, max_heading_level) + lines.append(f'{title}') + else: + # Nested command - build full path + app_name = command_chain[0] if command_chain else app.name[0] + full_command = " ".join(command_chain) + # Create anchor-friendly ID using shared logic + anchor_id = generate_anchor(full_command) + effective_level = min(heading_level, max_heading_level) + lines.append('
    ') + lines.append( + f'{escape_html(full_command)}' + ) + + # Add application description + help_format = app.app_stack.resolve("help_format", fallback="restructuredtext") + description = extract_description(app, help_format) + if description: + desc_text = extract_text(description, None) + if desc_text: + lines.append(f'
    {escape_html(desc_text)}
    ') + + # Generate table of contents if this is the root level and has commands + if generate_toc and not command_chain and app._commands: + lines.append('
    ') + lines.append("

    Table of Contents

    ") + lines.append("
      ") + _generate_html_toc(lines, app, include_hidden, app_name, "", 0) + lines.append("
    ") + lines.append("
    ") + + # Add usage section if not suppressed + usage = extract_usage(app) + if usage: + usage_level = min(heading_level + 1, max_heading_level) + lines.append(f"Usage") + lines.append('
    ') + if isinstance(usage, str): + usage_text = usage + else: + usage_text = extract_text(usage, None) + display_chain = apply_usage_name(command_chain, usage_name) + usage_text = format_usage_line(usage_text, display_chain, prefix="$") + lines.append(f'
    {escape_html(usage_text)}
    ') + lines.append("
    ") + + # Get help panels for the current app + # Use app_stack context - if caller set up parent context, it will be stacked + with app.app_stack([app]): + help_panels_with_groups = app._assemble_help_panels([], help_format) + + # Render panels + formatter = HtmlFormatter( + heading_level=heading_level + 1, + include_hidden=include_hidden, + app_name=app_name, + command_chain=command_chain, + ) + formatter.reset() + for group, panel in help_panels_with_groups: + if not include_hidden and group and not group.show: + continue + # Filter out entries based on include_hidden + if not include_hidden: + panel.entries = filter_help_entries(app, panel, include_hidden) + if panel.entries: # Only render non-empty panels + formatter(None, None, panel) + + panel_docs = formatter.get_output().strip() + if panel_docs: + lines.append(panel_docs) + + # Handle recursive documentation for subcommands + if app._commands: + # Iterate through registered commands + for name, subapp in iterate_commands(app, include_hidden): + # Build the command chain for this subcommand + sub_command_chain = build_command_chain(command_chain, name, app_name) + + # Determine heading level for subcommand + if flatten_commands: + sub_heading_level = heading_level + else: + sub_heading_level = heading_level + 1 + + # Generate subcommand documentation + lines.append('
    ') + # Create anchor-friendly ID + anchor_id = ( + f"{app_name}-{'-'.join(sub_command_chain[1:])}".lower() + if len(sub_command_chain) > 1 + else f"{app_name}-{name}".lower() + ) + effective_sub_level = min(sub_heading_level, max_heading_level) + lines.append( + f'{escape_html(" ".join(sub_command_chain))}' + ) + + # Get subapp help + # Include parent app in the stack so default_parameter is properly inherited + with subapp.app_stack([app, subapp]): + sub_help_format = subapp.app_stack.resolve("help_format", fallback=help_format) + sub_description = extract_description(subapp, sub_help_format) + if sub_description: + sub_desc_text = extract_text(sub_description, None) + if sub_desc_text: + lines.append(f'
    {escape_html(sub_desc_text)}
    ') + + # Generate usage for subcommand + sub_usage = extract_usage(subapp) + if sub_usage: + if flatten_commands: + usage_heading_level = heading_level + 1 + else: + usage_heading_level = heading_level + 2 + usage_heading_level = min(usage_heading_level, max_heading_level) + lines.append(f"Usage") + lines.append('
    ') + if isinstance(sub_usage, str): + sub_usage_text = sub_usage + else: + sub_usage_text = extract_text(sub_usage, None) + sub_display_chain = apply_usage_name(sub_command_chain, usage_name) + sub_usage_text = format_usage_line(sub_usage_text, sub_display_chain, prefix="$") + lines.append(f'
    {escape_html(sub_usage_text)}
    ') + lines.append("
    ") + + # Only show subcommand panels if we're in recursive mode + if recursive: + # Get help panels for subcommand + sub_panels = subapp._assemble_help_panels([], sub_help_format) + + # Render subcommand panels + if flatten_commands: + panel_heading_level = heading_level + 1 + else: + panel_heading_level = heading_level + 2 + panel_heading_level = min(panel_heading_level, max_heading_level) + sub_formatter = HtmlFormatter( + heading_level=panel_heading_level, + include_hidden=include_hidden, + app_name=app_name, + command_chain=sub_command_chain, + ) + for sub_group, sub_panel in sub_panels: + if not include_hidden and sub_group and not sub_group.show: + continue + if not include_hidden: + sub_panel.entries = filter_help_entries(subapp, sub_panel, include_hidden) + if sub_panel.entries: + sub_formatter(None, None, sub_panel) + + sub_panel_docs = sub_formatter.get_output().strip() + if sub_panel_docs: + lines.append(sub_panel_docs) + + # Recursively handle nested subcommands + if recursive and subapp._commands: + for nested_name, nested_app in iterate_commands(subapp, include_hidden): + # Build nested command chain + nested_chain = build_command_chain(sub_command_chain, nested_name, app_name) + # Determine heading level for nested commands + if flatten_commands: + nested_heading_level = heading_level + else: + nested_heading_level = heading_level + 2 + # Set up context for nested_app, then recurse + # The recursive call's app_stack([app]) will stack on top of this + with nested_app.app_stack([subapp, nested_app]): + nested_docs = generate_html_docs( + nested_app, + recursive=recursive, + include_hidden=include_hidden, + heading_level=nested_heading_level, + max_heading_level=max_heading_level, + standalone=False, # Not standalone for nested + custom_css=None, + command_chain=nested_chain, # Pass the command chain + generate_toc=False, # No TOC for nested commands + flatten_commands=flatten_commands, + usage_name=usage_name, + ) + lines.append(nested_docs) + + # Add back to top link if we're in a nested section + if command_chain: + lines.append('↑ Back to top') + lines.append("
    ") + + # Close section if nested command + if command_chain: + lines.append("
    ") + + # Only close cli-documentation div for standalone or root + if standalone or not command_chain: + lines.append("
    ") # Close cli-documentation div + + # Join all lines into body content + body_content = "\n".join(lines) + + # If standalone, wrap in complete HTML document + if standalone: + css = custom_css if custom_css else DEFAULT_CSS + doc = f""" + + + + + {escape_html(app_name)} - CLI Documentation + + + +{body_content} + +""" + return doc + else: + return body_content diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/markdown.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/markdown.py new file mode 100644 index 0000000000000000000000000000000000000000..a6016f55b1aa3c2593d6a06b70dffeb3dbf997bb --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/markdown.py @@ -0,0 +1,780 @@ +"""Documentation generation functions for cyclopts apps.""" + +from typing import TYPE_CHECKING + +from cyclopts._markup import extract_text +from cyclopts.core import DEFAULT_FORMAT +from cyclopts.docs.base import ( + adjust_filters_for_subcommand, + apply_usage_name, + build_command_chain, + extract_description, + extract_usage, + format_usage_line, + generate_anchor, + get_app_info, + is_all_builtin_flags, + iterate_commands, + normalize_command_filters, + should_include_command, + should_show_commands_list, + should_show_usage, +) + +if TYPE_CHECKING: + from cyclopts.core import App + + +def _collect_commands_for_toc( + app: "App", + include_hidden: bool = False, + prefix: str = "", + commands_filter: list[str] | None = None, + exclude_commands: list[str] | None = None, + parent_path: list[str] | None = None, + skip_filtered_command: bool = False, +) -> list[tuple[str, "App"]]: + """Recursively collect all commands for table of contents. + + Returns a list of (display_name, app) tuples. + """ + commands = [] + + if parent_path is None: + parent_path = [] + + normalized_commands_filter, normalized_exclude_commands = normalize_command_filters( + commands_filter, exclude_commands + ) + + for name, subapp in iterate_commands(app, include_hidden): + if not should_include_command( + name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp + ): + continue + + # Skip the command itself if it's the single filtered command with subcommands + # (we'll include its children directly instead) + skip_this_command = skip_filtered_command and subapp._commands + + if not skip_this_command: + display_name = f"{prefix}{name}" if prefix else name + commands.append((display_name, subapp)) + + # Collect nested commands + nested_path = parent_path + [name] + # Always include parent in prefix for nested commands (for correct paths) + nested_prefix = f"{prefix}{name} " + nested = _collect_commands_for_toc( + subapp, + include_hidden=include_hidden, + prefix=nested_prefix, + commands_filter=commands_filter, + exclude_commands=exclude_commands, + parent_path=nested_path, + skip_filtered_command=False, # Only skip at the top level + ) + commands.extend(nested) + + return commands + + +def _generate_toc_entries(lines: list[str], commands: list[tuple[str, "App"]]) -> None: + """Generate TOC entries with proper indentation. + + Parameters + ---------- + lines : list[str] + List to append TOC entries to. + commands : list[tuple[str, "App"]] + List of (display_name, app) tuples. + """ + anchor_counts: dict[str, int] = {} + + for display_name, _app in commands: + depth = display_name.count(" ") - 1 + indent = " " * depth + + cmd_name = display_name.split()[-1] + anchor = generate_anchor(display_name) + + if anchor in anchor_counts: + anchor_counts[anchor] += 1 + anchor = f"{anchor}_{anchor_counts[anchor]}" + else: + anchor_counts[anchor] = 0 + + lines.append(f"{indent}- [`{cmd_name}`](#{anchor})") + + +def _build_command_map(app: "App", include_hidden: bool = True) -> dict[str, "App"]: + """Build mapping of command names to App objects. + + Parameters + ---------- + app : App + The app to extract commands from. + include_hidden : bool + Whether to include hidden commands. + + Returns + ------- + dict[str, App] + Mapping of command names to App instances. + """ + command_map = {} + if app._commands: + for name, subapp in iterate_commands(app, include_hidden): + command_map[name] = subapp + return command_map + + +def _append_if_present(lines: list[str], content: str, add_blank: bool = True) -> None: + """Append content to lines if present, optionally adding blank line. + + Parameters + ---------- + lines : list[str] + List to append to. + content : str + Content to append (only if non-empty). + add_blank : bool + Whether to add a blank line after content. + """ + if content: + lines.append(content) + if add_blank: + lines.append("") + + +def _render_description_section(app: "App", help_format: str, lines: list[str]) -> None: + """Extract and render app description. + + Parameters + ---------- + app : App + The app to extract description from. + help_format : str + Help format (e.g., "markdown", "rich"). + lines : list[str] + List to append description to. + """ + description = extract_description(app, help_format) + if description: + # Preserve markup when help_format matches output format (markdown) + preserve = help_format in ("markdown", "md") + desc_text = extract_text(description, None, preserve_markup=preserve) + if desc_text: + lines.append(desc_text.strip()) + lines.append("") + + +def _render_usage_section( + app: "App", + command_chain: list[str], + lines: list[str], + usage_name: str | None = None, +) -> None: + """Render usage console block. + + Parameters + ---------- + app : App + The app to extract usage from. + command_chain : list[str] + Command chain for usage line. + lines : list[str] + List to append usage to. + usage_name : str | None + Optional replacement for the chain's root in Usage: lines only. + """ + if should_show_usage(app): + usage = extract_usage(app) + if usage: + lines.append("```console") + if isinstance(usage, str): + usage_text = usage + else: + usage_text = extract_text(usage, None, preserve_markup=False) + display_chain = apply_usage_name(command_chain, usage_name) + usage_line = format_usage_line(usage_text, display_chain) + lines.append(usage_line) + lines.append("```") + lines.append("") + + +def _render_toc( + app: "App", + app_name: str, + include_hidden: bool, + commands_filter: list[str] | None, + exclude_commands: list[str] | None, + skip_filtered_command: bool, + lines: list[str], +) -> None: + """Generate and render table of contents. + + Parameters + ---------- + app : App + The app to generate TOC for. + app_name : str + Application name for TOC prefixes. + include_hidden : bool + Whether to include hidden commands. + commands_filter : list[str] | None + Commands to include. + exclude_commands : list[str] | None + Commands to exclude. + skip_filtered_command : bool + Whether to skip the single filtered command in TOC. + lines : list[str] + List to append TOC to. + """ + # Collect all commands recursively for TOC + toc_commands = _collect_commands_for_toc( + app, + include_hidden=include_hidden, + prefix=f"{app_name} " if app_name else "", + commands_filter=commands_filter, + exclude_commands=exclude_commands, + skip_filtered_command=skip_filtered_command, + ) + if toc_commands: + lines.append("## Table of Contents") + lines.append("") + _generate_toc_entries(lines, toc_commands) + lines.append("") + + +def _render_parameter_panel(panel, formatter, lines: list[str]) -> None: + """Render a parameter panel as-is. + + Parameters + ---------- + panel : HelpPanel + The parameter panel to render. + formatter : MarkdownFormatter + Formatter to use for rendering. + lines : list[str] + List to append rendered content to. + """ + # Render panel content first to check if there's anything + formatter.reset() + panel_copy = panel.copy(title="") + formatter(None, None, panel_copy) + output = formatter.get_output().strip() + + # Only render if there's actual content + if output: + if panel.title: + lines.append(f"**{panel.title}**:\n") + lines.append(output) + lines.append("") + + +def _filter_command_entries( + entries: list, + command_map: dict[str, "App"], + parent_path: list[str], + normalized_filter: set[str] | None, + normalized_exclude: set[str] | None, +) -> list: + """Filter command entries based on inclusion/exclusion rules. + + Parameters + ---------- + entries : list + Command entries to filter. + command_map : dict[str, App] + Mapping of command names to App objects. + parent_path : list[str] + Parent command path. + normalized_filter : set[str] | None + Normalized filter set. + normalized_exclude : set[str] | None + Normalized exclude set. + + Returns + ------- + list + Filtered command entries. + """ + filtered_entries = [] + for entry in entries: + if entry.names: + cmd_name = entry.names[0] + subapp = command_map.get(cmd_name) + if subapp is None: + # If command not in map and no filters, include it + if normalized_filter is None and normalized_exclude is None: + filtered_entries.append(entry) + else: + # Check if command should be included + if should_include_command(cmd_name, parent_path, normalized_filter, normalized_exclude, subapp): + filtered_entries.append(entry) + return filtered_entries + + +def generate_markdown_docs( + app: "App", + recursive: bool = True, + include_hidden: bool = False, + heading_level: int = 1, + max_heading_level: int = 6, + command_chain: list[str] | None = None, + generate_toc: bool = True, + flatten_commands: bool = False, + commands_filter: list[str] | None = None, + exclude_commands: list[str] | None = None, + no_root_title: bool = False, + code_block_title: bool = False, + skip_preamble: bool = False, + usage_name: str | None = None, +) -> str: + """Generate markdown documentation for a CLI application. + + Parameters + ---------- + app : App + The cyclopts App instance to document. + recursive : bool + If True, generate documentation for all subcommands recursively. + Default is True. + include_hidden : bool + If True, include hidden commands/parameters in documentation. + Default is False. + heading_level : int + Starting heading level for the main application title. + Default is 1 (single #). + max_heading_level : int + Maximum heading level to use. Headings deeper than this will be capped + at this level. Standard Markdown supports levels 1-6. + Default is 6. + command_chain : list[str] + Internal parameter to track command hierarchy. + Default is None. + generate_toc : bool + If True, generate a table of contents for multi-command apps. + Default is True. + flatten_commands : bool + If True, generate all commands at the same heading level instead of nested. + Default is False. + commands_filter : list[str] | None + If specified, only include commands in this list. + Supports nested command paths like "db.migrate". + Default is None (include all commands). + exclude_commands : list[str] | None + If specified, exclude commands in this list. + Supports nested command paths like "db.migrate". + Default is None (no exclusions). + no_root_title : bool + If True, skip the root application title. Used for plugin contexts. + Default is False. + skip_preamble : bool + If True, skip the description and usage sections for the target command + when filtering to a single command via ``commands_filter``. + Useful when the user provides their own section introduction. + Default is False. + usage_name : str | None + Optional replacement for the root app name used in ``Usage:`` lines + only. Headings and TOC anchors still use ``app.name[0]``. + Default is None (use ``app.name[0]`` as before). + + Returns + ------- + str + The generated markdown documentation. + """ + from cyclopts.help.formatters.markdown import MarkdownFormatter + + # Build the main documentation + lines = [] + + if command_chain is None: + command_chain = [] + is_root = True + else: + is_root = False + + # Determine if we should skip the current level's content + # When filtering to a single command, skip the root app content + skip_current_level = is_root and commands_filter is not None and len(commands_filter) == 1 + + # Determine the app name and full command path + app_name, full_command, base_title = get_app_info(app, command_chain) + # Always use full command path for nested commands to avoid anchor collisions + # (e.g., "files cp" and "other cp" would both generate #cp without this) + if command_chain: + # Show full command path (same for both hierarchical and flattened modes) + title = f"`{full_command}`" if code_block_title else full_command + else: + # Root app: use base title + title = base_title + + # Add title for all levels (unless skipping root title or skipping current level entirely) + if not skip_current_level and not (no_root_title and is_root): + effective_level = min(heading_level, max_heading_level) + lines.append(f"{'#' * effective_level} {title}") + lines.append("") + + # Get help format (needed for both current level and recursive docs) + help_format = app.app_stack.resolve("help_format", fallback=DEFAULT_FORMAT) + + # Add usage section first (skip if skipping current level or skip_preamble is True) + if not skip_current_level and not skip_preamble: + _render_usage_section(app, command_chain, lines, usage_name=usage_name) + + # Add application description (skip if skipping current level or skip_preamble is True) + if not skip_current_level and not skip_preamble: + _render_description_section(app, help_format, lines) + + # Generate table of contents if this is the root level and has commands + if generate_toc and not command_chain and app._commands: + _render_toc(app, app_name, include_hidden, commands_filter, exclude_commands, skip_current_level, lines) + + # Get help panels for the current app (skip if skipping current level) + # Use app_stack context - if caller set up parent context, it will be stacked + if not skip_current_level: + with app.app_stack([app]): + help_panels_with_groups = app._assemble_help_panels([], help_format) + + # Set up command filtering (used for command panels only) + normalized_commands_filter, normalized_exclude_commands = normalize_command_filters( + commands_filter, exclude_commands + ) + parent_path = [] + + # Build a mapping of command names to App objects for filtering + command_map = _build_command_map(app, include_hidden=True) + + # Create formatter + formatter = MarkdownFormatter( + heading_level=heading_level + 1, + include_hidden=include_hidden, + table_style="list", + ) + + # Iterate through panels in the order provided by _assemble_help_panels (already sorted) + for group, panel in help_panels_with_groups: + # Skip hidden groups + if not include_hidden and group and not group.show: + continue + + if panel.format == "command": + # Always filter out built-in flags (--help, --version) from command panels + # These are standard CLI flags, not commands, and shouldn't appear here + command_entries = [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))] + + if not command_entries: + continue # Skip empty panel + + # Apply command filtering + filtered_entries = _filter_command_entries( + command_entries, command_map, parent_path, normalized_commands_filter, normalized_exclude_commands + ) + + # Only render if there are filtered entries + if filtered_entries: + if panel.title: + lines.append(f"**{panel.title}**:\n") + + # Render command entries with hyperlinks to their sections + for entry in filtered_entries: + if entry.names: + cmd_name = entry.names[0] + # Generate anchor for the full command path + # Use full_command (not app_name) to include the complete path for nested apps + full_cmd_path = f"{full_command} {cmd_name}" + anchor = generate_anchor(full_cmd_path) + desc_text = ( + extract_text(entry.description, None, preserve_markup=True) if entry.description else "" + ) + if desc_text: + lines.append(f"* [`{cmd_name}`](#{anchor}): {desc_text}") + else: + lines.append(f"* [`{cmd_name}`](#{anchor})") + lines.append("") + elif panel.format == "parameter": + # Handle parameter panels - split into arguments and options if needed + _render_parameter_panel(panel, formatter, lines) + else: + # When skipping current level, still need to set up filter variables for recursive docs + normalized_commands_filter, normalized_exclude_commands = normalize_command_filters( + commands_filter, exclude_commands + ) + parent_path = [] + + # Handle recursive documentation for subcommands + if app._commands: + # Iterate through registered commands using iterate_commands helper + # This automatically resolves CommandSpec instances + for name, subapp in iterate_commands(app, include_hidden): + if not should_include_command( + name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp + ): + continue + + # Build the command chain for this subcommand + sub_command_chain = build_command_chain(command_chain, name, app_name) + + # Determine heading level for subcommand + if flatten_commands: + sub_heading_level = heading_level + elif no_root_title and not command_chain: + # When root title is skipped, subcommands "take over" the root heading level + sub_heading_level = heading_level + else: + sub_heading_level = heading_level + 1 + + # Check if we should skip this command's title heading + # Skip title when: root was skipped (single command filter) AND this is the direct target + # OR this is an intermediate command on the path to a nested target + # This allows the markdown author's section title to serve as the heading + is_single_filter = commands_filter is not None and len(commands_filter) == 1 + is_exact_target = is_single_filter and commands_filter is not None and name == commands_filter[0] + is_intermediate_path = ( + is_single_filter and commands_filter is not None and commands_filter[0].startswith(name + ".") + ) + + skip_this_command_title = skip_current_level and is_exact_target + # Also skip intermediate commands entirely when skip_preamble is set + skip_intermediate = skip_preamble and skip_current_level and is_intermediate_path + # Skip preamble for the exact target when skip_preamble is set (even in recursive calls) + skip_target_preamble = skip_preamble and is_exact_target + + # Generate subcommand title (skip if this is the single filtered command at root level, + # or if this is an intermediate command and skip_preamble is set) + if not skip_this_command_title and not skip_intermediate: + # Always use full command path to avoid anchor collisions + display_name = " ".join(sub_command_chain) + display_fmt = f"`{display_name}`" if code_block_title else display_name + effective_sub_level = min(sub_heading_level, max_heading_level) + lines.append(f"{'#' * effective_sub_level} {display_fmt}") + lines.append("") + + # Get subapp help - show description, usage, and panels for included commands + # Skip preamble (description + usage) if: + # - skip_preamble is True and this is the exact target (even in recursive calls) + # - or this is an intermediate command on the path to a nested target + skip_this_preamble = skip_target_preamble or skip_intermediate + + # Include parent app in the stack so default_parameter is properly inherited + with subapp.app_stack([app, subapp]): + sub_help_format = subapp.app_stack.resolve("help_format", fallback=help_format) + # Preserve markup when sub_help_format matches output format (markdown) + preserve_sub = sub_help_format in ("markdown", "md") + + if not skip_this_preamble: + # Generate usage first for subcommand + _render_usage_section(subapp, sub_command_chain, lines, usage_name=usage_name) + _render_description_section(subapp, sub_help_format, lines) + + # Only show subcommand panels if we're in recursive mode + # (Otherwise we just show the basic info about this command) + if recursive: + # Get help panels for subcommand (already sorted) + sub_panels = subapp._assemble_help_panels([], sub_help_format) + + # Set up command filtering for this subcommand + sub_commands_filter_for_panel, sub_exclude_commands_for_panel = adjust_filters_for_subcommand( + name, normalized_commands_filter, normalized_exclude_commands + ) + normalized_sub_filter_panel, normalized_sub_exclude_panel = normalize_command_filters( + sub_commands_filter_for_panel, sub_exclude_commands_for_panel + ) + + # Build a map of command names to App objects for filtering + sub_command_map = _build_command_map(subapp, include_hidden=True) + + # Build parent path for nested commands + # Use empty path since filter was already adjusted to strip current level's prefix + nested_parent_path_for_panel = [] + + # Create formatter + if flatten_commands: + panel_heading_level = heading_level + 1 + else: + panel_heading_level = heading_level + 2 + sub_formatter = MarkdownFormatter( + heading_level=panel_heading_level, include_hidden=include_hidden, table_style="list" + ) + + # Check if we'll be recursively documenting commands + will_recurse = recursive and subapp._commands + + # Iterate through panels in order + for group, panel in sub_panels: + # Skip hidden groups + if not include_hidden and group and not group.show: + continue + + if panel.format == "command" and should_show_commands_list(subapp): + # Always filter out built-in flags (--help, --version) from command panels + command_entries_list = [ + e for e in panel.entries if not (e.names and is_all_builtin_flags(subapp, e.names)) + ] + + if not command_entries_list: + continue # Skip empty panel + + # Apply command filtering for command panels + if will_recurse: + # Show simple command list + command_entries = [] + for entry in command_entries_list: + if entry.names: + cmd_name = entry.names[0] + sub_cmd_app = sub_command_map.get(cmd_name) + if sub_cmd_app and not should_include_command( + cmd_name, + nested_parent_path_for_panel, + normalized_sub_filter_panel, + normalized_sub_exclude_panel, + sub_cmd_app, + ): + continue + + desc_text = ( + extract_text(entry.description, None, preserve_markup=preserve_sub) + if entry.description + else "" + ) + # Generate anchor for the full command path + full_cmd_path = " ".join(sub_command_chain + [cmd_name]) + anchor = generate_anchor(full_cmd_path) + if desc_text: + command_entries.append(f"* [`{cmd_name}`](#{anchor}): {desc_text}") + else: + command_entries.append(f"* [`{cmd_name}`](#{anchor})") + + if command_entries: + if panel.title: + lines.append(f"**{panel.title}**:\n") + lines.extend(command_entries) + lines.append("") + else: + # Show full command panel + filtered_entries = [] + for entry in command_entries_list: + if entry.names: + cmd_name = entry.names[0] + sub_cmd_app = sub_command_map.get(cmd_name) + if sub_cmd_app and not should_include_command( + cmd_name, + nested_parent_path_for_panel, + normalized_sub_filter_panel, + normalized_sub_exclude_panel, + sub_cmd_app, + ): + continue + filtered_entries.append(entry) + + if filtered_entries: + if panel.title: + lines.append(f"**{panel.title}**:\n") + + sub_formatter.reset() + filtered_panel = panel.__class__( + title="", + entries=filtered_entries, + format=panel.format, + description=panel.description, + ) + sub_formatter(None, None, filtered_panel) + output = sub_formatter.get_output().strip() + if output: + lines.append(output) + lines.append("") + elif panel.format == "parameter": + # Handle parameter panels - split into arguments and options if needed + _render_parameter_panel(panel, sub_formatter, lines) + + # Process nested commands INSIDE the with block so context is preserved + if recursive and subapp._commands: + sub_commands_filter, sub_exclude_commands = adjust_filters_for_subcommand( + name, normalized_commands_filter, normalized_exclude_commands + ) + + normalized_sub_filter, normalized_sub_exclude = normalize_command_filters( + sub_commands_filter, sub_exclude_commands + ) + + # Build parent path for nested commands + # Use empty path since filter was already adjusted to strip current level's prefix + nested_parent_path = [] + + for nested_name, nested_app in iterate_commands(subapp, include_hidden): + if not should_include_command( + nested_name, nested_parent_path, normalized_sub_filter, normalized_sub_exclude, nested_app + ): + continue + + # Build nested command chain (always use full path for correct usage) + nested_command_chain = build_command_chain(sub_command_chain, nested_name, app_name) + # Determine heading level for nested commands + if flatten_commands: + nested_heading_level = heading_level + elif skip_this_command_title: + # When parent command's title was skipped, promote nested commands to parent's level + nested_heading_level = sub_heading_level + else: + nested_heading_level = sub_heading_level + 1 + # Determine commands_filter for the recursive call + # Adjust filter to strip current command's prefix for the nested level + if normalized_sub_filter: + nested_commands_filter, _ = adjust_filters_for_subcommand( + nested_name, normalized_sub_filter, normalized_sub_exclude + ) + else: + nested_commands_filter = None + + # Check if this nested command is the target for skip_preamble purposes + # This handles nested paths like "parent.child" where "child" is the target + nested_is_target = ( + skip_preamble + and sub_commands_filter is not None + and len(sub_commands_filter) == 1 + and nested_name == sub_commands_filter[0] + ) + # Also check if this is an intermediate on a deeper path + nested_is_intermediate = ( + skip_preamble + and sub_commands_filter is not None + and len(sub_commands_filter) == 1 + and sub_commands_filter[0].startswith(nested_name + ".") + ) + + # Set up context for nested_app, then recurse + # The recursive call's app_stack([app]) will stack on top of this + with nested_app.app_stack([subapp, nested_app]): + nested_docs = generate_markdown_docs( + nested_app, + recursive=recursive, + include_hidden=include_hidden, + heading_level=nested_heading_level, + max_heading_level=max_heading_level, + command_chain=nested_command_chain, + generate_toc=False, # Don't generate TOC for nested commands + flatten_commands=flatten_commands, + commands_filter=nested_commands_filter, + exclude_commands=sub_exclude_commands, + no_root_title=nested_is_intermediate, # Skip title for intermediate paths + code_block_title=code_block_title, + skip_preamble=nested_is_target or nested_is_intermediate, + usage_name=usage_name, + ) + # Just append the generated docs - no title replacement + lines.append(nested_docs) + lines.append("") + + # Join all lines into final document + doc = "\n".join(lines).rstrip() + "\n" + + # Normalize multiple consecutive blank lines to a single blank line + # This ensures consistent spacing regardless of how content was assembled + import re + + doc = re.sub(r"\n{3,}", "\n\n", doc) + + return doc diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/rst.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/rst.py new file mode 100644 index 0000000000000000000000000000000000000000..b66169c9b65567859425189a525c8b9a9df59078 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/rst.py @@ -0,0 +1,483 @@ +"""RST documentation generation functions for cyclopts apps.""" + +from typing import TYPE_CHECKING + +from cyclopts._markup import extract_text +from cyclopts.docs.base import ( + adjust_filters_for_subcommand, + apply_usage_name, + extract_description, + extract_usage, + generate_anchor, + get_app_info, + is_all_builtin_flags, + iterate_commands, + normalize_command_filters, + should_include_command, + should_show_usage, +) + +if TYPE_CHECKING: + from cyclopts.core import App + + +def make_rst_code_block_title(title: str) -> list[str]: + """Create an RST code block containing the title. + + Parameters + ---------- + title : str + Title text to display in code block. + + Returns + ------- + list[str] + RST formatted code block lines. + """ + return [ + ".. code-block:: text", + "", + f" {title}", + ] + + +def make_rst_section_header(title: str, level: int) -> list[str]: + """Create an RST section header. + + Parameters + ---------- + title : str + Section title. + level : int + Heading level (1-6). + + Returns + ------- + list[str] + RST formatted section header lines. + """ + markers = { + 1: "=", + 2: "-", + 3: "^", + 4: '"', + 5: "'", + 6: "~", + } + + if level < 1: + level = 1 + elif level > 6: + level = 6 + + marker = markers[level] + underline = marker * len(title) + + if level == 1: + return [underline, title, underline] + else: + return [title, underline] + + +def _build_command_map(app: "App", include_hidden: bool = True) -> dict[str, "App"]: + """Build mapping of command names to App objects. + + Parameters + ---------- + app : App + The app to extract commands from. + include_hidden : bool + Whether to include hidden commands. + + Returns + ------- + dict[str, App] + Mapping of command names to App instances. + """ + command_map = {} + if app._commands: + for name, subapp in iterate_commands(app, include_hidden): + command_map[name] = subapp + return command_map + + +def _filter_command_entries( + entries: list, + command_map: dict[str, "App"], + parent_path: list[str], + normalized_filter: set[str] | None, + normalized_exclude: set[str] | None, +) -> list: + """Filter command entries based on inclusion/exclusion rules. + + Parameters + ---------- + entries : list + Command entries to filter. + command_map : dict[str, App] + Mapping of command names to App objects. + parent_path : list[str] + Parent command path. + normalized_filter : set[str] | None + Normalized filter set. + normalized_exclude : set[str] | None + Normalized exclude set. + + Returns + ------- + list + Filtered command entries. + """ + filtered_entries = [] + for entry in entries: + if entry.names: + cmd_name = entry.names[0] + subapp = command_map.get(cmd_name) + if subapp is None: + # If command not in map and no filters, include it + if normalized_filter is None and normalized_exclude is None: + filtered_entries.append(entry) + else: + # Check if command should be included + if should_include_command(cmd_name, parent_path, normalized_filter, normalized_exclude, subapp): + filtered_entries.append(entry) + return filtered_entries + + +def _generate_toc(lines: list[str]) -> None: + """Generate table of contents using RST contents directive. + + The `.. contents::` directive automatically generates a TOC from + section headings, which is the idiomatic approach for RST/Sphinx. + """ + lines.append(".. contents:: Table of Contents") + lines.append(" :local:") + lines.append(" :depth: 6") + lines.append("") + + +def generate_rst_docs( + app: "App", + recursive: bool = True, + include_hidden: bool = False, + heading_level: int = 1, + max_heading_level: int = 6, + command_chain: list[str] | None = None, + generate_toc: bool = True, + flatten_commands: bool = False, + commands_filter: list[str] | None = None, + exclude_commands: list[str] | None = None, + no_root_title: bool = False, + code_block_title: bool = False, + skip_preamble: bool = False, + usage_name: str | None = None, +) -> str: + """Generate reStructuredText documentation for a CLI application. + + Parameters + ---------- + app : App + The cyclopts App instance to document. + recursive : bool + If True, generate documentation for all subcommands recursively. + Default is True. + include_hidden : bool + If True, include hidden commands/parameters in documentation. + Default is False. + heading_level : int + Starting heading level for the main application title. + Default is 1 (uses '=' markers). + max_heading_level : int + Maximum heading level to use. Headings deeper than this will be capped + at this level. RST uses different underline characters for each level. + Default is 6. + command_chain : list[str] + Internal parameter to track command hierarchy. + Default is None. + generate_toc : bool + If True, generate a table of contents for multi-command apps. + Default is True. + flatten_commands : bool + If True, generate all commands at the same heading level instead of nested. + Default is False. + commands_filter : list[str], optional + If specified, only include commands in this list. + Supports nested command paths like "db.migrate". + Default is None (include all commands). + exclude_commands : list[str], optional + If specified, exclude commands in this list. + Supports nested command paths like "db.migrate". + Default is None (no exclusions). + no_root_title : bool + If True, skip generating the root application title. + Useful when embedding in existing documentation with its own title. + Default is False. + skip_preamble : bool + If True, skip the description and usage sections for the target command + when filtering to a single command via ``commands_filter``. + Useful when the user provides their own section introduction. + Default is False. + usage_name : str | None + Optional replacement for the root app name used in ``Usage:`` lines + only. Section headings, anchors, and TOC continue to use ``app.name[0]``. + Default is None. + + Returns + ------- + str + The generated RST documentation. + """ + from cyclopts.help.formatters.rst import RstFormatter + + lines = [] + + if command_chain is None: + command_chain = [] + + app_name, full_command, base_title = get_app_info(app, command_chain) + # Title logic: match markdown behavior for consistency + # - Hierarchical mode: show just command name (last part of chain) + # - Flattened mode: show full command path + # - Root: use base title + if command_chain and not flatten_commands: + # Hierarchical: show just the command name (last part of chain) + title = command_chain[-1] + elif command_chain: + # Flattened: show full command path + title = full_command + else: + # Root app: use base title + title = base_title + + # Always generate RST anchor/label with improved namespacing + # RST uses a "cyclopts-" prefix for namespacing + anchor_parts = ["cyclopts"] + if command_chain: + anchor_parts.extend(command_chain) + else: + anchor_parts.append(app_name) + # Use shared anchor generation logic, then add RST-specific slash replacement + anchor_name = generate_anchor(" ".join(anchor_parts)).replace("/", "-") + lines.append(f".. _{anchor_name}:") + lines.append("") + + # Determine effective heading level for this command + if no_root_title and not command_chain: + # Skip title entirely for root when no_root_title is True + effective_heading_level = heading_level + elif flatten_commands and command_chain: + # When flattening, all commands use the same heading level + effective_heading_level = heading_level + else: + # Normal hierarchical: increment level for nested commands + effective_heading_level = heading_level + len(command_chain) - 1 if command_chain else heading_level + + # Cap at max_heading_level + effective_heading_level = min(effective_heading_level, max_heading_level) + + if not (no_root_title and not command_chain): + if code_block_title: + header_lines = make_rst_code_block_title(title) + else: + header_lines = make_rst_section_header(title, effective_heading_level) + lines.extend(header_lines) + lines.append("") + + help_format = app.app_stack.resolve("help_format", fallback="restructuredtext") + + # Add usage section first if appropriate (skip if skip_preamble is True) + if not skip_preamble and should_show_usage(app): + # Generate usage line - only if we're documenting a specific command. + # When no_root_title is set at the root (e.g., in Sphinx contexts), the + # root Usage: line is intentionally suppressed; usage_name still applies + # to every subcommand usage block below. + if not (no_root_title and not command_chain): + # Extract usage from app + usage = extract_usage(app) + usage_text = None + if usage: + if isinstance(usage, str): + usage_text = usage + else: + usage_text = extract_text(usage, None, preserve_markup=False) + + # Apply usage_name override to the display chain (only for the Usage: line) + display_chain = apply_usage_name(command_chain, usage_name) + + # Format usage with the display chain when one is present + if display_chain: + parts = usage_text.split(None, 1) + if len(parts) > 1: + usage_text = f"{' '.join(display_chain)} {parts[1]}" + else: + usage_text = " ".join(display_chain) + + if usage_text: + # Use literal block with double colon + lines.append("::") + lines.append("") + # Indent usage text with 4 spaces for literal block + for line in usage_text.split("\n"): + lines.append(f" {line}") + lines.append("") + + # Add description (skip if skip_preamble is True) + if not skip_preamble: + description = extract_description(app, help_format) + if description: + # Extract plain text from description + # Preserve markup when help_format matches output format (RST) + preserve = help_format in ("restructuredtext", "rst") + desc_text = extract_text(description, None, preserve_markup=preserve) + if desc_text: + lines.append(desc_text.strip()) + lines.append("") + + # Generate table of contents at root level only + if generate_toc and not command_chain and app._commands: + _generate_toc(lines) + + # Get help panels for the current app + # Use app_stack context - if caller set up parent context, it will be stacked + with app.app_stack([app]): + help_panels_with_groups = app._assemble_help_panels([], help_format) + + # Set up command filtering + normalized_commands_filter, normalized_exclude_commands = normalize_command_filters( + commands_filter, exclude_commands + ) + parent_path: list[str] = [] + + # Build a mapping of command names to App objects for filtering + command_map = _build_command_map(app, include_hidden=True) + + # Create formatter for help panels + formatter = RstFormatter(heading_level=heading_level + 1, include_hidden=include_hidden) + + # Render panels as-is without categorization + for group, panel in help_panels_with_groups: + # Skip hidden panels unless include_hidden is True + if not include_hidden and group and not group.show: + continue + + # Skip if no_root_title and we're at root + if no_root_title and not command_chain: + continue + + # Render command panels as grouped command lists + if panel.format == "command": + # Filter out built-in flags (--help, --version) from command panels + command_entries = [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))] + + if not command_entries: + continue # Skip empty panel + + # Apply command filtering + filtered_entries = _filter_command_entries( + command_entries, command_map, parent_path, normalized_commands_filter, normalized_exclude_commands + ) + + if not filtered_entries: + continue # Skip if nothing after filtering + + # Render group title + if panel.title: + lines.append(f"**{panel.title}:**") + lines.append("") + + # Render commands as RST definition list + for entry in filtered_entries: + primary_name = entry.names[0] if entry.names else "" + desc = extract_text(entry.description, None) + lines.append(f"``{primary_name}``") + if desc: + lines.append(f" {desc}") + lines.append("") + + # Render parameter panels as-is + elif panel.format == "parameter": + # Render content first to check if there's anything + formatter.reset() + panel_copy = panel.copy(title="") + formatter(None, None, panel_copy) + output = formatter.get_output().strip() + + # Only render if there's actual content + if output: + if panel.title: + lines.append(f"**{panel.title}:**") + lines.append("") + lines.append(output) + lines.append("") + + if recursive and app._commands: + normalized_commands_filter, normalized_exclude_commands = normalize_command_filters( + commands_filter, exclude_commands + ) + parent_path = [] + + for name, subapp in iterate_commands(app, include_hidden): + if not should_include_command( + name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp + ): + continue + + lines.append("") + + subcommand_chain = command_chain + [name] if command_chain else [app_name, name] + if flatten_commands: + next_heading_level = heading_level + elif no_root_title and not command_chain: + next_heading_level = heading_level - 1 + else: + next_heading_level = heading_level + + sub_commands_filter, sub_exclude_commands = adjust_filters_for_subcommand( + name, normalized_commands_filter, normalized_exclude_commands + ) + + # Determine if this subcommand should skip its preamble + # Skip preamble when: we're at root, skip_preamble is True, and this is the single target command + # OR this is an intermediate command on the path to a nested target + is_single_target = ( + not command_chain + and skip_preamble + and commands_filter is not None + and len(commands_filter) == 1 + and name == commands_filter[0] + ) + is_intermediate_path = ( + not command_chain + and skip_preamble + and commands_filter is not None + and len(commands_filter) == 1 + and commands_filter[0].startswith(name + ".") + ) + + # Push subapp onto app_stack - context will stack with recursive call's app_stack([app]) + with subapp.app_stack([app, subapp]): + subdocs = generate_rst_docs( + subapp, + recursive=recursive, + include_hidden=include_hidden, + heading_level=next_heading_level, + max_heading_level=max_heading_level, + command_chain=subcommand_chain, + generate_toc=False, # Only generate TOC at root level + flatten_commands=flatten_commands, + commands_filter=sub_commands_filter, + exclude_commands=sub_exclude_commands, + no_root_title=is_intermediate_path, # Skip title for intermediate path commands + code_block_title=code_block_title, + skip_preamble=is_single_target or is_intermediate_path, # Skip preamble for target or intermediate + usage_name=usage_name, + ) + lines.append(subdocs) + + # Join and normalize multiple consecutive blank lines to a single blank line + import re + + doc = "\n".join(lines) + doc = re.sub(r"\n{3,}", "\n\n", doc) + + return doc diff --git a/.venv/lib/python3.10/site-packages/cyclopts/docs/types.py b/.venv/lib/python3.10/site-packages/cyclopts/docs/types.py new file mode 100644 index 0000000000000000000000000000000000000000..e32746803984f62986b856d522b72af39644f84d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/docs/types.py @@ -0,0 +1,50 @@ +"""Type definitions and utilities for documentation generation.""" + +from typing import Literal + +# All accepted format values (canonical and aliases) +DocFormat = Literal["markdown", "md", "html", "htm", "rst", "rest", "restructuredtext"] + +# Canonical format values only +CanonicalDocFormat = Literal["markdown", "html", "rst"] + +# Map all aliases to their canonical format +# Also used for suffix lookups by stripping the leading period +FORMAT_ALIASES: dict[str, CanonicalDocFormat] = { + "md": "markdown", + "markdown": "markdown", + "html": "html", + "htm": "html", + "rst": "rst", + "rest": "rst", + "restructuredtext": "rst", +} + + +def normalize_format(format_value: str) -> CanonicalDocFormat: + """Normalize format aliases to standard format names. + + Parameters + ---------- + format_value : str + The format string to normalize (case-insensitive). + + Returns + ------- + CanonicalDocFormat + The canonical format name. + + Raises + ------ + ValueError + If the format is not recognized. + """ + format_lower = format_value.lower() + canonical_format = FORMAT_ALIASES.get(format_lower) + + if canonical_format is None: + raise ValueError( + f'Unsupported format "{format_value}". Supported formats: {", ".join(sorted(FORMAT_ALIASES.keys()))}' + ) + + return canonical_format diff --git a/.venv/lib/python3.10/site-packages/cyclopts/exceptions.py b/.venv/lib/python3.10/site-packages/cyclopts/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..8983470900da1f303f9206983faa88fa1f78722e --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/exceptions.py @@ -0,0 +1,470 @@ +import inspect +import json +from collections.abc import Callable, Sequence +from enum import Enum +from itertools import chain +from typing import TYPE_CHECKING, Any, Literal, Optional, get_args, get_origin + +from attrs import define, field + +import cyclopts.utils +from cyclopts.annotations import get_hint_name +from cyclopts.command_spec import CommandSpec +from cyclopts.group import Group +from cyclopts.token import Token +from cyclopts.utils import is_option_like, json_decode_error_verbosifier + +if TYPE_CHECKING: + from rich.console import Console + + from cyclopts.argument import Argument, ArgumentCollection + from cyclopts.core import App + + +__all__ = [ + "CoercionError", + "CommandCollisionError", + "CycloptsError", + "DocstringError", + "UnknownCommandError", + "MissingArgumentError", + "ConsumeMultipleError", + "MixedArgumentError", + "RepeatArgumentError", + "RequiresEqualsError", + "UnknownOptionError", + "UnusedCliTokensError", + "ValidationError", + "CombinedShortOptionError", +] + + +def _get_function_info(func): + return inspect.getsourcefile(func), inspect.getsourcelines(func)[1] + + +class CommandCollisionError(Exception): + """A command with the same name has already been registered to the app.""" + + # This doesn't derive from CycloptsError since this is a developer error + # rather than a runtime error. + + +class DocstringError(Exception): + """The docstring either has a syntax error, or inconsistency with the function signature.""" + + +@define # (kw_only=True) +class CycloptsError(Exception): + """Root exception for runtime errors. + + As CycloptsErrors bubble up the Cyclopts call-stack, more information is added to it. + """ + + msg: str | None = None + """ + If set, override automatic message generation. + """ + + verbose: bool = True + """ + More verbose error messages; aimed towards developers debugging their Cyclopts app. + Defaults to ``False``. + """ + + root_input_tokens: list[str] | None = None + """ + The parsed CLI tokens that were initially fed into the :class:`App`. + """ + + unused_tokens: list[str] | None = None + """ + Leftover tokens after parsing is complete. + """ + + target: Callable | None = None + """ + The python function associated with the command being parsed. + """ + + argument: Optional["Argument"] = None + """ + :class:`Argument` that was matched. + """ + + command_chain: Sequence[str] | None = None + """ + List of command that lead to ``target``. + """ + + app: Optional["App"] = None + """ + The Cyclopts application itself. + """ + + console: Optional["Console"] = field(default=None, kw_only=True) + """:class:`~rich.console.Console` to display runtime errors.""" + + def __str__(self): + if self.msg is not None: + return self.msg + + strings = [] + if self.verbose: + strings.append(type(self).__name__) + if self.target: + file, lineno = _get_function_info(self.target) + strings.append(f'Function defined in file "{file}", line {lineno}:') + strings.append(f" {self.target.__name__}{inspect.signature(self.target)}") + if self.root_input_tokens is not None: + strings.append(f"Root Input Tokens: {self.root_input_tokens}") + else: + pass + + if strings: + return "\n".join(strings) + "\n" + else: + return "" + + +@define(kw_only=True) +class CombinedShortOptionError(CycloptsError): + """Cannot combine short, token-consuming options with short flags.""" + + +@define(kw_only=True) +class ValidationError(CycloptsError): + """Validator function raised an exception.""" + + exception_message: str = "" + """Parenting Assertion/Value/Type Error message.""" + + group: Group | None = None + """If a group validator caused the exception.""" + + value: Any = cyclopts.utils.UNSET + """Converted value that failed validation.""" + + def __str__(self): + message = "" + if self.argument: + value = self.argument.value if self.value is cyclopts.utils.UNSET else self.value + try: + token = self.argument.tokens[0] + except IndexError: + pass + else: + provided_by = "" if not token.source or token.source == "cli" else f' provided by "{token.source}"' + name = token.keyword if token.keyword else self.argument.name.lstrip("-").upper() + message = f'Invalid value "{value}" for "{name}"{provided_by}.' + elif self.group: + if self.group.name: + message = f'Invalid values for group "{self.group.name}".' + elif self.command_chain: + message = f"Invalid values for command {self.command_chain[-1]!r}." + else: + raise NotImplementedError + + cyclopts_message = f"{super().__str__()}{message}" + if self.exception_message: + if cyclopts_message: + return f"{cyclopts_message} {self.exception_message}" + else: + return self.exception_message + else: + return cyclopts_message + + +@define(kw_only=True) +class UnknownOptionError(CycloptsError): + """Unknown/unregistered option provided by the cli. + + A nearest-neighbor parameter suggestion may be printed. + """ + + token: Token + """Token without a matching parameter.""" + + argument_collection: "ArgumentCollection" + """Argument collection of plausible options.""" + + def __str__(self): + value = self.token.keyword or self.token.value + if self.token.source == "cli": + response = f'Unknown option: "{value}".' + else: + response = f'Unknown option: "{value}" from "{self.token.source}".' + + if keyword := self.token.keyword or self.token.value: + import difflib + + candidates = list(chain.from_iterable(x.names for x in self.argument_collection if x.parse)) + + close_matches = difflib.get_close_matches(keyword, candidates, n=1, cutoff=0.6) + if close_matches: + response += f' Did you mean "{close_matches[0]}"?' + + return super().__str__() + response + + +@define(kw_only=True) +class CoercionError(CycloptsError): + """There was an error performing automatic type coercion.""" + + token: Optional["Token"] = None + """ + Input token that couldn't be coerced. + """ + + target_type: type | None = None + """ + Intended type to coerce into. + """ + + def __str__(self): + if self.msg is not None: + if not self.token or self.token.keyword is None: + return self.msg + else: + return f"Invalid value for {self.token.keyword}: {self.msg}" + else: + # If a JsonDecodeError, try and verbosify it. + if isinstance(self.__cause__, json.JSONDecodeError): + msg = json_decode_error_verbosifier(self.__cause__) # pyright: ignore[reportArgumentType] + if not self.token or self.token.keyword is None: + return msg + else: + return f"Invalid value for {self.token.keyword}: {msg}" + + assert self.argument is not None + assert self.target_type is not None + + msg = super().__str__() + + if get_origin(self.target_type) is Literal: + choices = "{" + ", ".join(repr(x) for x in get_args(self.target_type)) + "}" + target_type_name = f"one of {choices}" + elif isinstance(self.target_type, type) and issubclass(self.target_type, Enum): + nt = self.argument.parameter.name_transform + choices = "{" + ", ".join(repr(nt(x)) for x in self.target_type.__members__) + "}" + target_type_name = f"one of {choices}" + else: + target_type_name = get_hint_name(self.target_type) + + if not self.token: + msg += f'Invalid value for "{self.argument.name}": unable to convert value to {target_type_name}.' + elif self.token.keyword is None: + positional_name = self.argument.name.lstrip("-").upper() + if self.token.source == "" or self.token.source == "cli": + msg += f'Invalid value for "{positional_name}": unable to convert "{self.token.value}" into {target_type_name}.' + else: + msg += f'Invalid value for "{positional_name}" from {self.token.source}: unable to convert "{self.token.value}" into {target_type_name}.' + else: + if self.token.source == "" or self.token.source == "cli": + msg += f'Invalid value for "{self.token.keyword}": unable to convert "{self.token.value}" into {target_type_name}.' + else: + msg += f'Invalid value for "{self.token.keyword}" from {self.token.source}: unable to convert "{self.token.value}" into {target_type_name}.' + + return msg + + +class UnknownCommandError(CycloptsError): + """CLI token combination did not yield a valid command.""" + + def __str__(self): + assert self.unused_tokens + token = self.unused_tokens[0] + response = f'Unknown command "{token}".' + + if self.app and self.app._commands: + import difflib + + # Resolve CommandSpec and filter visible commands + visible_commands = [] + for name, app_or_spec in self.app._commands.items(): + if name in self.app._help_flags or name in self.app._version_flags: + continue + + # Resolve CommandSpec to App + subapp = app_or_spec.resolve(self.app) if isinstance(app_or_spec, CommandSpec) else app_or_spec + + if not isinstance(subapp, type(self.app)): + continue + + if subapp.show: + visible_commands.append(name) + + close_matches = difflib.get_close_matches( + token, + visible_commands, + n=1, + cutoff=0.6, + ) + if close_matches: + response += f' Did you mean "{close_matches[0]}"?' + + # The following is a heuristic to be "maximally helpful" to someone who may have + # forgotten a command in their CLI call. + max_commands = 8 + available_commands = [name for name in visible_commands if not name.startswith("-")] + if available_commands: + if len(available_commands) > max_commands: + response += f" Available commands: {', '.join(available_commands[:max_commands])}, ..." + else: + response += f" Available commands: {', '.join(available_commands)}." + + return super().__str__() + response + + +@define(kw_only=True) +class UnusedCliTokensError(CycloptsError): + """Not all CLI tokens were used as expected.""" + + def __str__(self): + assert self.unused_tokens is not None + return super().__str__() + f"Unused Tokens: {self.unused_tokens}." + + +@define(kw_only=True) +class MissingArgumentError(CycloptsError): + """A required argument was not provided.""" + + tokens_so_far: list[str] = field(factory=list) + """If the matched parameter requires multiple tokens, these are the ones we have parsed so far.""" + + keyword: str | None = None + """The keyword that was used when the error was raised (e.g., '-o' instead of '--option').""" + + def __str__(self): + assert self.argument is not None + strings = [] + count, _ = self.argument.token_count() + if count == 0: + required_string = "flag required" + only_got_string = "" + elif count == 1: + required_string = "requires an argument" + only_got_string = "" + else: + required_string = f"requires {count} positional arguments" + received_count = len(self.tokens_so_far) % count + only_got_string = f" Only got {received_count}." if received_count else "" + + close_match_string = "" + if self.unused_tokens and self.argument.field_info.is_keyword: + import difflib + + candidates = [x for x in self.unused_tokens if is_option_like(x)] + + close_matches = difflib.get_close_matches(self.argument.name, candidates, n=1, cutoff=0.6) + if close_matches and close_matches[0] not in self.argument.names: + close_match_string = f'Did you mean "{self.argument.name}" instead of "{close_matches[0]}"?' + + param_name = self.argument.name + if self.keyword is not None: + param_name = self.keyword + elif self.argument.tokens: + for token in reversed(self.argument.tokens): + if token.keyword is not None: + param_name = token.keyword + break + + if self.command_chain: + strings.append( + f'Command "{" ".join(self.command_chain)}" parameter "{param_name}" {required_string}.{only_got_string}' + ) + else: + strings.append(f'Parameter "{param_name}" {required_string}.{only_got_string}') + + if close_match_string: + strings.append(close_match_string) + + if self.verbose: + strings.append(f" Parsed: {self.tokens_so_far}.") + + return super().__str__() + " ".join(strings) + + +@define(kw_only=True) +class ConsumeMultipleError(MissingArgumentError): + """The number of values provided doesn't meet consume_multiple constraints.""" + + min_required: int = 0 + max_allowed: int | None = None + actual_count: int = 0 + + def __str__(self): + assert self.argument is not None + param_name = self.keyword or self.argument.name + + if self.actual_count < self.min_required: + constraint = f"requires at least {self.min_required}" + else: + constraint = f"accepts at most {self.max_allowed}" + + if self.command_chain: + base = f'Command "{" ".join(self.command_chain)}" parameter "{param_name}" {constraint} elements. Got {self.actual_count}.' + else: + base = f'Parameter "{param_name}" {constraint} elements. Got {self.actual_count}.' + + return CycloptsError.__str__(self) + base + + +@define(kw_only=True) +class RequiresEqualsError(CycloptsError): + """A long option requires ``=`` to assign a value (e.g., ``--option=value``).""" + + keyword: str | None = None + """The keyword that was used (e.g., '--name').""" + + def __str__(self): + assert self.argument is not None + param_name = self.keyword or self.argument.name + return ( + super().__str__() + + f'Parameter "{param_name}" requires a value assigned with "=". Use "{param_name}=VALUE".' + ) + + +@define(kw_only=True) +class RepeatArgumentError(CycloptsError): + """The same parameter has erroneously been specified multiple times.""" + + token: "Token" + """The repeated token.""" + + def __str__(self): + return super().__str__() + f"Parameter {self.token.keyword} specified multiple times." + + +@define(kw_only=True) +class ArgumentOrderError(CycloptsError): + """Cannot supply a POSITIONAL_OR_KEYWORD argument with a keyword, and then a later POSITIONAL_OR_KEYWORD argument positionally.""" + + token: str + prior_positional_or_keyword_supplied_as_keyword_arguments: list["Argument"] + + def __str__(self): + assert self.argument is not None + plural = len(self.prior_positional_or_keyword_supplied_as_keyword_arguments) > 1 + display_name = next((x.keyword for x in self.argument.tokens if x.keyword), self.argument.name).lstrip("-") + prior_display_names = [ + x.tokens[0].keyword for x in self.prior_positional_or_keyword_supplied_as_keyword_arguments + ] + if len(prior_display_names) == 1: + prior_display_names = prior_display_names[0] + + return ( + super().__str__() + + f"Cannot specify token {self.token!r} positionally for parameter {display_name!r} due to previously specified keyword{'s' if plural else ''} {prior_display_names!r}. {prior_display_names!r} must either be passed positionally, or {self.token!r} must be passed as a keyword to {self.argument.name!r}." + ) + + +@define(kw_only=True) +class MixedArgumentError(CycloptsError): + """Cannot supply keywords and non-keywords to the same argument.""" + + def __str__(self): + assert self.argument is not None + display_name = next((x.keyword for x in self.argument.tokens if x.keyword), self.argument.name) + return super().__str__() + f'Cannot supply keyword & non-keyword arguments to "{display_name}".' diff --git a/.venv/lib/python3.10/site-packages/cyclopts/ext/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/ext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.10/site-packages/cyclopts/ext/mkdocs.py b/.venv/lib/python3.10/site-packages/cyclopts/ext/mkdocs.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc5ee2caa696f0daba9a8b78f0b354648497a3e --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/ext/mkdocs.py @@ -0,0 +1,256 @@ +"""MkDocs plugin for automatic Cyclopts CLI documentation.""" + +import re +from typing import TYPE_CHECKING, Any + +import yaml +from attrs import define, field, validators + +from cyclopts.docs.markdown import generate_markdown_docs +from cyclopts.utils import import_app + +if TYPE_CHECKING: + from mkdocs.config.defaults import MkDocsConfig + from mkdocs.structure.files import Files + from mkdocs.structure.pages import Page + +from mkdocs.config import base +from mkdocs.config import config_options as c +from mkdocs.exceptions import PluginError +from mkdocs.plugins import BasePlugin, get_plugin_logger + +logger = get_plugin_logger(__name__) + + +@define(kw_only=True) +class DirectiveOptions: + """Configuration for the ::: cyclopts directive.""" + + module: str = field(validator=validators.instance_of(str)) + heading_level: int = field(default=2, validator=validators.instance_of(int)) + max_heading_level: int = field(default=6, validator=validators.instance_of(int)) + commands: list[str] | None = field(default=None, validator=validators.optional(validators.instance_of(list))) + exclude_commands: list[str] | None = field( + default=None, validator=validators.optional(validators.instance_of(list)) + ) + recursive: bool = field(default=True, validator=validators.instance_of(bool)) + include_hidden: bool = field(default=False, validator=validators.instance_of(bool)) + flatten_commands: bool = field(default=False, validator=validators.instance_of(bool)) + generate_toc: bool = field(default=True, validator=validators.instance_of(bool)) + code_block_title: bool = field(default=False, validator=validators.instance_of(bool)) + skip_preamble: bool = field(default=False, validator=validators.instance_of(bool)) + usage_name: str | None = field(default=None, validator=validators.optional(validators.instance_of(str))) + + @classmethod + def from_directive_block( + cls, + directive_text: str, + *, + default_heading_level: int | None = None, + default_max_heading_level: int | None = None, + ) -> "DirectiveOptions": + """Parse options from a ::: cyclopts directive block. + + Expected format: + ::: cyclopts + module: myapp.cli:app + heading_level: 2 + max_heading_level: 6 + recursive: true + commands: + - cmd1 + - cmd2 + + Parameters + ---------- + directive_text : str + The directive text to parse. + default_heading_level : int | None + Default heading level from plugin config. Used if :heading-level: not specified. + default_max_heading_level : int | None + Default max heading level from plugin config. Used if :max-heading-level: not specified. + """ + lines = directive_text.strip().split("\n") + + # Remove the ::: cyclopts line + if lines and lines[0].strip().startswith("::: cyclopts"): + lines = lines[1:] + + yaml_content = "\n".join(lines) + options = yaml.safe_load(yaml_content) or {} + + if not isinstance(options, dict): + raise TypeError("Invalid YAML in ::: cyclopts directive: expected a dictionary") + + if "module" not in options: + raise ValueError('The "module" option is required for ::: cyclopts directive') + + if default_heading_level is not None: + options.setdefault("heading_level", default_heading_level) + + if default_max_heading_level is not None: + options.setdefault("max_heading_level", default_max_heading_level) + + # Convert keys with dashes to underscores + normalized_options = {key.replace("-", "_"): value for key, value in options.items()} + + try: + return cls(**normalized_options) + except TypeError as e: + raise ValueError(f"Error creating DirectiveOptions: {e}") from e + + +# Regex to match ::: cyclopts directive blocks +# The pattern matches: +# - "^::: cyclopts\n" - the directive start on its own line +# - "(?:[ \t]+.*\n?)*" - zero or more indented YAML lines (with optional trailing newline for EOF) +DIRECTIVE_PATTERN = re.compile( + r"^::: cyclopts\n(?:[ \t]+.*\n?)*", + re.MULTILINE, +) + + +def process_cyclopts_directives(markdown: str, plugin_config: Any) -> str: + """Process all ::: cyclopts directives in markdown content. + + Parameters + ---------- + markdown : str + The markdown content containing ::: cyclopts directives. + plugin_config : CycloptsPluginConfig + The plugin configuration with default values. If None, uses DirectiveOptions defaults. + + Returns + ------- + str + The markdown content with directives replaced by generated documentation. + """ + # Find all code blocks to exclude from processing + code_blocks = [] + + # Find fenced code blocks (triple backticks or tildes) + fenced_pattern = re.compile(r"^[`~]{3,}.*?^[`~]{3,}", re.MULTILINE | re.DOTALL) + for match in fenced_pattern.finditer(markdown): + code_blocks.append((match.start(), match.end())) + + # Find indented code blocks (lines starting with 4 spaces or tab) + # Indented code blocks are preceded by a blank line and consist of lines starting with 4 spaces/tab + lines = markdown.split("\n") + in_indented_block = False + block_start = 0 + current_pos = 0 + + for i, line in enumerate(lines): + line_len = len(line) + 1 # +1 for the newline + + # Check if this line starts an indented code block + if not in_indented_block: + # Previous line must be blank (or be the first line) + prev_blank = i == 0 or not lines[i - 1].strip() + # Current line must start with 4 spaces or a tab and have content + is_indented = (line.startswith(" ") or line.startswith("\t")) and line.strip() + + if prev_blank and is_indented: + in_indented_block = True + block_start = current_pos + else: + # Check if we're still in the indented block + is_indented = (line.startswith(" ") or line.startswith("\t")) and line.strip() + is_blank = not line.strip() + + # End block if we hit a non-indented, non-blank line + if not is_indented and not is_blank: + code_blocks.append((block_start, current_pos)) + in_indented_block = False + + current_pos += line_len + + # If we ended while still in an indented block, add it + if in_indented_block: + code_blocks.append((block_start, current_pos)) + + def is_in_code_block(pos: int) -> bool: + """Check if a position is inside a code block.""" + for start, end in code_blocks: + if start <= pos < end: + return True + return False + + def replace_directive(match: re.Match) -> str: + # Skip if this match is inside a code block + if is_in_code_block(match.start()): + return match.group(0) + + directive_text = match.group(0) + + try: + default_heading = plugin_config.default_heading_level if plugin_config else None + default_max_heading = plugin_config.default_max_heading_level if plugin_config else None + options = DirectiveOptions.from_directive_block( + directive_text, + default_heading_level=default_heading, + default_max_heading_level=default_max_heading, + ) + + app = import_app(options.module) + + markdown_docs = generate_markdown_docs( + app, + recursive=options.recursive, + include_hidden=options.include_hidden, + heading_level=options.heading_level, + max_heading_level=options.max_heading_level, + generate_toc=options.generate_toc, + flatten_commands=options.flatten_commands, + commands_filter=options.commands, + exclude_commands=options.exclude_commands, + no_root_title=True, # Skip root title in plugin context + code_block_title=options.code_block_title, + skip_preamble=options.skip_preamble, + usage_name=options.usage_name, + ) + + return markdown_docs + + except Exception as e: + raise PluginError(f"Error processing ::: cyclopts directive: {e}") from e + + # Replace all directives in the markdown + processed = DIRECTIVE_PATTERN.sub(replace_directive, markdown) + return processed + + +class CycloptsPluginConfig(base.Config): # type: ignore[misc] + """Configuration schema for the Cyclopts MkDocs plugin.""" + + default_heading_level = c.Type(int, default=2) # type: ignore[attr-defined] + default_max_heading_level = c.Type(int, default=6) # type: ignore[attr-defined] + + +class CycloptsPlugin(BasePlugin[CycloptsPluginConfig]): # type: ignore[misc] + """MkDocs plugin to generate Cyclopts CLI documentation. + + Usage in mkdocs.yml: + plugins: + - cyclopts: + default_heading_level: 2 + + Usage in Markdown files: + ::: cyclopts + :module: myapp.cli:app + :heading-level: 2 + :recursive: true + :commands: init, build + :exclude-commands: debug + """ + + def on_page_markdown(self, markdown: str, *, page: "Page", config: "MkDocsConfig", files: "Files", **kwargs) -> str: + """Process ::: cyclopts directives in markdown content. + + This event is called after the page's markdown is loaded from file + but before it's converted to HTML. + """ + if "::: cyclopts" not in markdown: + return markdown + + return process_cyclopts_directives(markdown, self.config) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/ext/sphinx.py b/.venv/lib/python3.10/site-packages/cyclopts/ext/sphinx.py new file mode 100644 index 0000000000000000000000000000000000000000..b5f2fea5103a49190fcb08f1ee1c6eec0f466e71 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/ext/sphinx.py @@ -0,0 +1,385 @@ +"""Sphinx extension for automatic Cyclopts CLI documentation.""" + +from typing import TYPE_CHECKING, Any + +import attrs + +from cyclopts import __version__ +from cyclopts.utils import import_app + +if TYPE_CHECKING: + from sphinx.application import Sphinx + +from docutils import nodes +from sphinx.application import Sphinx +from sphinx.util import logging +from sphinx.util.docutils import SphinxDirective + +logger = logging.getLogger(__name__) + + +@attrs.define(kw_only=True) +class DirectiveOptions: + """Configuration for the Cyclopts directive.""" + + heading_level: int = 2 + max_heading_level: int = 6 + commands: list[str] | None = None + exclude_commands: list[str] | None = None + usage_name: str | None = None + + # All booleans must have ``False`` default. + no_recursive: bool = False + include_hidden: bool = False + flatten_commands: bool = False + code_block_title: bool = False + skip_preamble: bool = False + + @classmethod + def from_dict(cls, options: dict) -> "DirectiveOptions": + """Create options from directive options dictionary.""" + kwargs = {} + for field in attrs.fields(cls): + # Convert underscore to dash for looking up in options + option_name = field.name.replace("_", "-") + + if field.type is bool: + # For boolean fields using directives.flag, presence means True + # The value is None when present, absent from dict when not specified + if option_name in options: + kwargs[field.name] = True + # Use default value if not specified + elif option_name in options: + value = options[option_name] + # Handle comma-separated lists for commands and exclude-commands + if field.name in ("commands", "exclude_commands"): + # Parse comma-separated list and strip whitespace + if value: + kwargs[field.name] = [cmd.strip() for cmd in value.split(",") if cmd.strip()] + else: + # Empty string means empty list + kwargs[field.name] = [] + else: + kwargs[field.name] = value + # If not specified, the dataclass default will be used + + return cls(**kwargs) + + @staticmethod + def spec() -> dict[str, Any]: + """Generate Sphinx option_spec from DirectiveOptions fields.""" + from docutils.parsers.rst import directives + + type_mapping = { + bool: directives.flag, + int: directives.nonnegative_int, + str: directives.unchanged, + } + + option_spec = {} + for field in attrs.fields(DirectiveOptions): + option_name = field.name.replace("_", "-") + # Handle List[str] fields (commands, exclude-commands) + if field.name in ("commands", "exclude_commands"): + validator = directives.unchanged # Will be parsed as comma-separated in from_dict + else: + validator = type_mapping.get(field.type, directives.unchanged) + option_spec[option_name] = validator + + return option_spec + + +def _should_include_command( + command_name: str, + command_path: list[str], + commands_filter: list[str] | None, + exclude_commands: list[str] | None, +) -> bool: + """Check if a command should be included in documentation. + + Parameters + ---------- + command_name : str + The name of the command. + command_path : list[str] + The full path to the command (including parent commands). + commands_filter : list[str] | None + If specified, only include commands in this list. + exclude_commands : list[str] | None + If specified, exclude commands in this list. + + Returns + ------- + bool + True if the command should be included. + """ + # Build the full command path for nested commands + full_path = ".".join(command_path + [command_name]) + + # Check exclusion list first + if exclude_commands: + # Check both the command name and full path + if command_name in exclude_commands or full_path in exclude_commands: + return False + # Check if any parent path is excluded + for i in range(len(command_path)): + parent_path = ".".join(command_path[: i + 1]) + if parent_path in exclude_commands: + return False + + # Check inclusion list + if commands_filter is not None: + # If a filter is specified, only include if explicitly listed + # Check if command name or full path is in the filter + if command_name in commands_filter or full_path in commands_filter: + return True + # Check if any parent path is included (to include all subcommands) + for i in range(len(command_path)): + parent_path = ".".join(command_path[: i + 1]) + if parent_path in commands_filter: + return True + # Also check if just the base command name matches for top-level commands + if not command_path and command_name in commands_filter: + return True + return False + + # No filter specified, include by default + return True + + +def _filter_commands( + commands: dict, + commands_filter: list[str] | None, + exclude_commands: list[str] | None, + parent_path: list[str] | None = None, +) -> dict: + """Filter commands based on inclusion/exclusion lists. + + Parameters + ---------- + commands : dict + Dictionary mapping command names to App instances. + commands_filter : Optional[List[str]] + If specified, only include commands in this list. + exclude_commands : Optional[List[str]] + If specified, exclude commands in this list. + parent_path : List[str] + Path to the parent command for nested commands. + + Returns + ------- + dict + Filtered commands dictionary. + """ + if parent_path is None: + parent_path = [] + + filtered = {} + for name, app in commands.items(): + if _should_include_command(name, parent_path, commands_filter, exclude_commands): + filtered[name] = app + + return filtered + + +def _process_rst_content(content: str, skip_title: bool = False) -> list[str]: + """Process RST content to remove problematic elements.""" + lines = content.splitlines() + processed = [] + i = 0 + + while i < len(lines): + line = lines[i] + + # Skip title and underline if requested + if skip_title and i == 0 and line.strip() and i + 1 < len(lines): + next_line = lines[i + 1].strip() + if next_line and set(next_line) <= {"-", "=", "^", "~", '"'}: + i += 2 + continue + + # Skip .. contents:: directive + if line.strip().startswith(".. contents::"): + i += 1 + while i < len(lines) and lines[i].strip() and lines[i][0] in " \t": + i += 1 + if i < len(lines) and not lines[i].strip(): + i += 1 + continue + + processed.append(line) + i += 1 + + return processed + + +def _create_section_nodes(lines: list[str], state: Any) -> list["nodes.Node"]: + """Create section nodes from RST lines.""" + from docutils.statemachine import StringList + + result = [] + i = 0 + + while i < len(lines): + line = lines[i] + + # Check for section header + if i + 1 < len(lines): + next_line = lines[i + 1].strip() + if next_line and all(c == "-" for c in next_line): + # Create section + section = nodes.section() + title_text = line.strip() + section["ids"] = [title_text.lower().replace(" ", "-").replace("cyclopts-", "cli-cyclopts-")] + + section += nodes.title(text=title_text) + + # Collect section content + content_lines = [] + i += 2 # Skip title and underline + + while i < len(lines): + next_line_stripped = lines[i + 1].strip() if i + 1 < len(lines) else "" + if next_line_stripped and all(c == "-" for c in next_line_stripped): + break + content_lines.append(lines[i]) + i += 1 + + if content_lines: + state.nested_parse(StringList(content_lines), 0, section) + + result.append(section) + continue + + # Check for literal block (::) + if line.strip() == "::": + # Skip the :: line + i += 1 + + # Skip blank line after :: + if i < len(lines) and not lines[i].strip(): + i += 1 + + # Collect indented content for the literal block + literal_content = [] + while i < len(lines) and lines[i].startswith(" "): + # Remove the 4-space indentation + literal_content.append(lines[i][4:]) + i += 1 + + # Create a literal block node directly + if literal_content: + literal_block = nodes.literal_block() + literal_block.rawsource = "\n".join(literal_content) + literal_block.append(nodes.Text("\n".join(literal_content))) + result.append(literal_block) + + # Skip any trailing blank line + if i < len(lines) and not lines[i].strip(): + i += 1 + + continue + + # Regular content - accumulate consecutive lines + if line.strip(): + content_lines = [line] + i += 1 + + # Collect consecutive non-empty lines that aren't section headers or literal blocks + while i < len(lines): + # Check if this is a section header + next_line = lines[i + 1].strip() if i + 1 < len(lines) else "" + if next_line and all(c == "-" for c in next_line): + break + + # Check if this is a literal block + if lines[i].strip() == "::": + break + + # Check if this is a blank line + if not lines[i].strip(): + # Include the blank line and continue to see if there's more content + content_lines.append(lines[i]) + i += 1 + # If the next line is also blank or we're at the end, stop + if i >= len(lines) or not lines[i].strip(): + break + else: + # Add non-empty line + content_lines.append(lines[i]) + i += 1 + + # Parse all accumulated lines together + para = nodes.paragraph() + state.nested_parse(StringList(content_lines), 0, para) + if para.children: + result.extend(para.children) + else: + i += 1 + + return result + + +class CycloptsDirective(SphinxDirective): # type: ignore[misc,valid-type] + """Sphinx directive for documenting Cyclopts CLI applications.""" + + has_content = False + required_arguments = 1 + optional_arguments = 0 + final_argument_whitespace = False + option_spec = DirectiveOptions.spec() + + def run(self) -> list["nodes.Node"]: + """Generate documentation nodes for the Cyclopts app.""" + module_path = self.arguments[0] + opts = DirectiveOptions.from_dict(self.options) + + try: + rst_content = self._generate_documentation(module_path, opts) + return self._create_nodes(rst_content, opts) + except Exception as e: + return self._error_node(f"Error generating Cyclopts documentation: {e}") + + def _generate_documentation(self, module_path: str, opts: DirectiveOptions) -> str: + """Generate RST documentation for the app.""" + from cyclopts.docs.rst import generate_rst_docs + + app = import_app(module_path) + + # Call generate_rst_docs directly to access internal no_root_title parameter + return generate_rst_docs( + app, + recursive=not opts.no_recursive, + include_hidden=opts.include_hidden, + heading_level=opts.heading_level, + max_heading_level=opts.max_heading_level, + flatten_commands=opts.flatten_commands, + commands_filter=opts.commands, + exclude_commands=opts.exclude_commands, + no_root_title=True, # Always skip root title in Sphinx context + code_block_title=opts.code_block_title, + skip_preamble=opts.skip_preamble, + usage_name=opts.usage_name, + ) + + def _create_nodes(self, rst_content: str, opts: DirectiveOptions) -> list["nodes.Node"]: + """Create docutils nodes from RST content.""" + lines = _process_rst_content(rst_content, skip_title=False) # Title already skipped in generate_docs + + # Always use section nodes for better Sphinx integration + return _create_section_nodes(lines, self.state) + + def _error_node(self, message: str) -> list["nodes.Node"]: + """Create an error node with the given message.""" + logger.error(message) + return [nodes.error("", nodes.paragraph(text=message))] + + +def setup(app: "Sphinx") -> dict[str, Any]: + """Setup function for the Sphinx extension.""" + app.add_directive("cyclopts", CycloptsDirective) + return { + "version": __version__, + "parallel_read_safe": True, + "parallel_write_safe": True, + } diff --git a/.venv/lib/python3.10/site-packages/cyclopts/field_info.py b/.venv/lib/python3.10/site-packages/cyclopts/field_info.py new file mode 100644 index 0000000000000000000000000000000000000000..de3bd52b8cdd3eb552dad9d01958feab98aa7772 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/field_info.py @@ -0,0 +1,363 @@ +import inspect +import sys +from typing import ( # noqa: F401 + Annotated, + Any, + ClassVar, + Optional, + get_args, + get_origin, + get_type_hints, +) + +import attrs +from attrs import field + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from cyclopts.annotations import ( + NotRequired, + Required, + is_annotated, + is_attrs, + is_dataclass, + is_enum_flag, + is_namedtuple, + is_pydantic, + is_pydantic_secret, + is_typeddict, + resolve, + resolve_annotated, + resolve_optional, +) +from cyclopts.utils import UNSET, is_builtin + +POSITIONAL_OR_KEYWORD = inspect.Parameter.POSITIONAL_OR_KEYWORD +POSITIONAL_ONLY = inspect.Parameter.POSITIONAL_ONLY +KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY +VAR_POSITIONAL = inspect.Parameter.VAR_POSITIONAL +VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD + + +def _replace_annotated_type(src_type, dst_type): + if not is_annotated(src_type): + return dst_type + return Annotated[(dst_type,) + get_args(src_type)[1:]] # pyright: ignore + + +@attrs.define +class FieldInfo: + """Extension of :class:`inspect.Parameter`.""" + + names: tuple[str, ...] = () + kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD + + required: bool = field(kw_only=True, default=False) + default: Any = field(default=inspect.Parameter.empty, kw_only=True) + annotation: Any = field(default=inspect.Parameter.empty, kw_only=True) + + help: str | None = field(default=None, kw_only=True) + """Can be populated by additional metadata from another library; e.g. ``pydantic.FieldInfo.description``.""" + + ################### + # Class Variables # + ################### + empty: ClassVar = inspect.Parameter.empty + POSITIONAL_OR_KEYWORD: ClassVar = inspect.Parameter.POSITIONAL_OR_KEYWORD + POSITIONAL_ONLY: ClassVar = inspect.Parameter.POSITIONAL_ONLY + KEYWORD_ONLY: ClassVar = inspect.Parameter.KEYWORD_ONLY + VAR_POSITIONAL: ClassVar = inspect.Parameter.VAR_POSITIONAL + VAR_KEYWORD: ClassVar = inspect.Parameter.VAR_KEYWORD + POSITIONAL: ClassVar[frozenset[inspect._ParameterKind]] = frozenset( + {POSITIONAL_OR_KEYWORD, POSITIONAL_ONLY, VAR_POSITIONAL} + ) + KEYWORD: ClassVar[frozenset[inspect._ParameterKind]] = frozenset({POSITIONAL_OR_KEYWORD, KEYWORD_ONLY, VAR_KEYWORD}) + + @classmethod + def from_iparam(cls, iparam: inspect.Parameter, *, annotation: Any = UNSET, required: bool | None = None) -> Self: + if required is None: + required = ( + iparam.default is iparam.empty + and iparam.kind != iparam.VAR_KEYWORD + and iparam.kind != iparam.VAR_POSITIONAL + ) + + return cls( + names=(iparam.name,), + annotation=iparam.annotation if annotation is UNSET else annotation, + kind=iparam.kind, + default=iparam.default, + required=required, + ) + + @property + def hint(self): + """Annotation with Optional-removed and cyclopts type-inferring.""" + hint = self.annotation + if hint is inspect.Parameter.empty or resolve(hint) is Any: + hint = _replace_annotated_type( + hint, str if self.default is inspect.Parameter.empty or self.default is None else type(self.default) + ) + hint = resolve_optional(hint) + return hint + + @property + def name(self): + """The **first** provided name.""" + return self.names[0] + + @property + def is_positional(self) -> bool: + return self.kind in self.POSITIONAL + + @property + def is_positional_only(self) -> bool: + return self.kind in (POSITIONAL_ONLY, VAR_POSITIONAL) + + @property + def is_keyword(self) -> bool: + return self.kind in self.KEYWORD + + @property + def is_keyword_only(self) -> bool: + return self.kind in (KEYWORD_ONLY, VAR_KEYWORD) + + def evolve(self, **kwargs): + return attrs.evolve(self, **kwargs) + + +def _typed_dict_field_infos(typeddict) -> dict[str, FieldInfo]: + # The ``__required_keys__`` and ``__optional_keys__`` attributes of TypedDict are kind of broken in dict[str, FieldInfo]: + out = {} + for name, field_info in signature_parameters(f.__init__).items(): + if field_info.name == "self": + continue + if not include_var_positional and field_info.kind is field_info.VAR_POSITIONAL: + continue + if not include_var_keyword and field_info.kind is field_info.VAR_KEYWORD: + continue + out[name] = field_info + return out + + +def _pydantic_field_infos(model) -> dict[str, FieldInfo]: + from pydantic_core import PydanticUndefined + + out = {} + for python_name, pydantic_field in model.model_fields.items(): + names = [] + if pydantic_field.alias: + if model.model_config.get("populate_by_name", False): + names.append(python_name) + names.append(pydantic_field.alias) + + # Add legacy-compatible CLI form if not already present. + # This allows both "user-name" (new) and "username" (legacy) to work as CLI options. + # Old transform behavior: alias.lower() (no pascal_to_snake) + # New transform behavior: _pascal_to_snake(alias).lower() + legacy_form = pydantic_field.alias.lower() + if legacy_form not in names: + names.append(legacy_form) + else: + names.append(python_name) + + # Extract Field with description from metadata + help = pydantic_field.description or None + for meta in pydantic_field.metadata: + if hasattr(meta, "description") and meta.description: + help = meta.description + + # Pydantic places ``Annotated`` data into pydantic.FieldInfo.metadata, while + # pydantic.FieldInfo.annotation contains the "real" resolved type-hint. + # We have to re-combine them into a single Annotated hint. + # For discriminated unions, pydantic stores discriminator separately (not in metadata), + # so include pydantic_field itself to preserve the discriminator attribute. + if pydantic_field.discriminator: + annotation = Annotated[(pydantic_field.annotation, pydantic_field) + tuple(pydantic_field.metadata)] # pyright: ignore + elif pydantic_field.metadata: + annotation = Annotated[(pydantic_field.annotation,) + tuple(pydantic_field.metadata)] # pyright: ignore + else: + annotation = pydantic_field.annotation + + out[python_name] = FieldInfo( + names=tuple(names), + kind=inspect.Parameter.KEYWORD_ONLY if pydantic_field.kw_only else inspect.Parameter.POSITIONAL_OR_KEYWORD, + annotation=annotation, + default=FieldInfo.empty if pydantic_field.default is PydanticUndefined else pydantic_field.default, + required=pydantic_field.is_required(), + help=help, + ) + return out + + +def _namedtuple_field_infos(hint) -> dict[str, FieldInfo]: + out = {} + type_hints = get_type_hints(hint) + for name in hint._fields: + out[name] = FieldInfo( + names=(name,), + kind=FieldInfo.POSITIONAL_OR_KEYWORD, + annotation=type_hints.get(name, str), + default=hint._field_defaults.get(name, FieldInfo.empty), + required=name not in hint._field_defaults, + ) + return out + + +def _attrs_field_infos(hint) -> dict[str, FieldInfo]: + out = {} + field_infos = signature_parameters(hint.__init__) + for attribute in hint.__attrs_attrs__: + if not attribute.init: + continue + + field_info = field_infos[attribute.alias] + + if isinstance(attribute.default, attrs.Factory): # pyright: ignore + required = False + default = None # Not strictly True, but we don't want to invoke factory + elif attribute.default is attrs.NOTHING: + required = True + default = FieldInfo.empty + else: + required = False + default = attribute.default + + help = attribute.metadata.get("help") if attribute.metadata else None + + out[field_info.name] = field_info.evolve( + names=(attribute.alias,), required=required, default=default, help=help + ) + return out + + +def _dataclass_field_infos(hint) -> dict[str, FieldInfo]: + import dataclasses + + out = {} + fields = dataclasses.fields(hint) + type_hints = get_type_hints(hint, include_extras=True) # resolves stringified type hints + for f in fields: + if f.default_factory is not dataclasses.MISSING: + default = f.default_factory() + required = False + elif f.default is not dataclasses.MISSING: + default = f.default + required = False + else: + default = FieldInfo.empty + required = True + + annotation = type_hints.get(f.name, FieldInfo.empty) + + kind = FieldInfo.KEYWORD_ONLY if f.kw_only else FieldInfo.POSITIONAL_OR_KEYWORD + + # Extract help text with precedence order: + # 1. metadata["help"] - explicit help in metadata + # 2. metadata["doc"] - doc stored in metadata + # 3. f.doc - Python 3.14+ field(doc=...) parameter + help = None + if f.metadata: + help = f.metadata.get("help") or f.metadata.get("doc") + if not help and hasattr(f, "doc"): + help = f.doc # type: ignore[attr-defined] + + out[f.name] = FieldInfo( + names=(f.name,), + kind=kind, + required=required, + annotation=annotation, + default=default, + help=help, + ) + return out + + +def _enum_flag_field_infos(enum_flag) -> dict[str, FieldInfo]: + """Extract field infos from a Flag enum, treating each member as a boolean field.""" + out = {} + for member_name in enum_flag.__members__: + out[member_name] = FieldInfo( + names=(member_name,), + kind=FieldInfo.KEYWORD_ONLY, + # The Enum member should NEVER have a type-annotation. + # Thusly, it by definition cannot have an Annotated[...]. + # see: https://typing.python.org/en/latest/spec/enums.html#defining-members + annotation=bool, # Each flag acts as a boolean + default=False, # Default to False (not included in combination) + required=False, # All flags are optional + ) + return out + + +def get_field_infos(hint) -> dict[str, FieldInfo]: + # Early return for builtin types (int, str, etc.) to avoid expensive introspection. + # Provides ~5-6x speedup for argument parsing by skipping signature_parameters() calls. + if is_builtin(hint): + return {} + + # Pydantic secret types (SecretStr, SecretBytes) should be treated as simple types + if is_pydantic_secret(hint): + return {} + + # NewType is a runtime identity function that returns its argument unchanged. + # Use the field_infos of the underlying supertype instead of NewType's misleading __init__. + if hasattr(hint, "__supertype__"): + return get_field_infos(hint.__supertype__) + + if is_dataclass(hint): + # This must be before ``is_pydantic`` check so that we + # can handle pydantic dataclasses as vanilla dataclasses. + return _dataclass_field_infos(hint) + elif is_pydantic(hint): + return _pydantic_field_infos(hint) + elif is_namedtuple(hint): + return _namedtuple_field_infos(hint) + elif is_typeddict(hint): + return _typed_dict_field_infos(hint) + elif is_attrs(hint): + return _attrs_field_infos(hint) + elif is_enum_flag(hint): + return _enum_flag_field_infos(hint) + else: + return _generic_class_field_infos(hint) + + +def signature_parameters(f: Any) -> dict[str, FieldInfo]: + if "functools" in sys.modules: + from functools import partial + + func = f.func if isinstance(f, partial) else f + else: + func = f + + type_hints = get_type_hints(func, include_extras=True) + + out = {} + for name, iparam in inspect.signature(f).parameters.items(): + annotation = type_hints.get(name, iparam.annotation) + out[name] = FieldInfo.from_iparam(iparam, annotation=annotation) + return out diff --git a/.venv/lib/python3.10/site-packages/cyclopts/group.py b/.venv/lib/python3.10/site-packages/cyclopts/group.py new file mode 100644 index 0000000000000000000000000000000000000000..b275c9719413d5e2ece1154a5988de3f3fa99132 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/group.py @@ -0,0 +1,222 @@ +import inspect +import itertools +import sys +from collections.abc import Callable, Iterable +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Optional, + Union, +) + +from attrs import field + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +from cyclopts.utils import ( + UNSET, + Sentinel, + SortHelper, + frozen, + help_formatter_converter, + is_iterable, + resolve_callables, + sort_key_converter, + to_tuple_converter, +) + +if TYPE_CHECKING: + from cyclopts.argument import ArgumentCollection + from cyclopts.help.protocols import HelpFormatter + from cyclopts.parameter import Parameter + + +def _group_default_parameter_must_be_none(instance, attribute, value: Optional["Parameter"]): + if value is None: + return + + if value.group: + raise ValueError("Group default_parameter cannot have a group.") + + +# Used for Group.sorted +_sort_key_counter = itertools.count() + + +# Special sort markers that get specially handled by :meth:`SortHelper.sort` +class DEFAULT_COMMANDS_GROUP_SORT_MARKER(Sentinel): # noqa: N801 + pass + + +class DEFAULT_ARGUMENTS_GROUP_SORT_MARKER(Sentinel): # noqa: N801 + pass + + +class DEFAULT_PARAMETERS_GROUP_SORT_MARKER(Sentinel): # noqa: N801 + pass + + +def _group_validator_converter( + value: "None | Callable[[ArgumentCollection], Any] | Iterable[Callable[[ArgumentCollection], Any]]", +) -> "tuple[Callable[[ArgumentCollection], Any], ...]": + return to_tuple_converter(value) # type: ignore[return-value] + + +def _group_name_converter(val: str): + return val if val else object() + + +@frozen +class Group: + _name: str = field(default="", alias="name", converter=_group_name_converter) # pyright: ignore reportAssignmentType + """ + Name of the group. + + For anonymous groups (groups with no name that shouldn't appear on the help-page), + we create a unique sentinel object. + + We cannot just use a static default value like :obj:`None` because python will + resolve multiple independent, identically configured anonymous groups to the same underlying object. + """ + + help: str = "" + + # All below parameters are keyword-only + _show: bool | None = field(default=None, alias="show", kw_only=True) + + _sort_key: Any = field( + default=None, + alias="sort_key", + converter=sort_key_converter, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[Callable, ...] + validator: None | Callable[["ArgumentCollection"], Any] | Iterable[Callable[["ArgumentCollection"], Any]] = field( + default=None, + converter=_group_validator_converter, + kw_only=True, + ) + + default_parameter: Optional["Parameter"] = field( + default=None, + validator=_group_default_parameter_must_be_none, + kw_only=True, + ) + + help_formatter: Union[None, Literal["default", "plain"], "HelpFormatter"] = field( + default=None, converter=help_formatter_converter, kw_only=True + ) + + @property + def name(self) -> str: + return "" if type(self._name) is object else self._name + + @property + def show(self): + return bool(self.name) if self._show is None else self._show + + @property + def sort_key(self): + return None if self._sort_key is UNSET else self._sort_key + + @classmethod + def create_default_arguments(cls, name="Arguments") -> Self: + return cls(name, sort_key=DEFAULT_ARGUMENTS_GROUP_SORT_MARKER) + + @classmethod + def create_default_parameters(cls, name="Parameters") -> Self: + return cls(name, sort_key=DEFAULT_PARAMETERS_GROUP_SORT_MARKER) + + @classmethod + def create_default_commands(cls, name="Commands") -> Self: + return cls(name, sort_key=DEFAULT_COMMANDS_GROUP_SORT_MARKER) + + @classmethod + def create_ordered( + cls, + name="", + help="", + *, + show=None, + sort_key=None, + validator=None, + default_parameter=None, + help_formatter=None, + ) -> Self: + """Create a group with a globally incrementing :attr:`~Group.sort_key`. + + Used to create a group that will be displayed **after** a previously instantiated :meth:`Group.create_ordered` group on the help-page. + + Parameters + ---------- + name: str + Group name used for the help-page and for group-referenced-by-string. + This is a title, so the first character should be capitalized. + If a name is not specified, it will not be shown on the help-page. + help: str + Additional documentation shown on the help-page. + This will be displayed inside the group's panel, above the parameters/commands. + show: bool | None + Show this group on the help-page. + Defaults to :obj:`None`, which will only show the group if a ``name`` is provided. + sort_key: Any + If provided, **prepended** to the globally incremented counter value (i.e. has priority during sorting). + + validator: None | Callable[[ArgumentCollection], Any] | Iterable[Callable[[ArgumentCollection], Any]] + Group validator to collectively apply. + default_parameter: cyclopts.Parameter | None + Default parameter for elements within the group. + help_formatter: cyclopts.help.protocols.HelpFormatter | None + Custom help formatter for this group's help display. + """ + count = next(_sort_key_counter) + if inspect.isgenerator(sort_key): + sort_key = next(sort_key) + if sort_key is None: + sort_key = (UNSET, count) + elif is_iterable(sort_key): + sort_key = (tuple(sort_key), count) + else: + sort_key = (sort_key, count) + return cls( + name, + help, + show=show, + sort_key=sort_key, + validator=validator, + default_parameter=default_parameter, + help_formatter=help_formatter, + ) + + +def sort_groups(groups: list[Group], attributes: list[Any]) -> tuple[list[Group], list[Any]]: + """Sort groups for the help-page. + + Note, much logic is similar to here and ``HelpPanel.sort``, so any changes here should probably be reflected over there as well. + + Parameters + ---------- + groups: list[Group] + List of groups to sort by their ``sort_key``. + attributes: list[Any] + A list of equal length to ``groups``. + Remains consistent with ``groups`` via argsort. + """ + assert len(groups) == len(attributes) + + if not groups: + return groups, attributes + + sorted_entries = SortHelper.sort( + [ + SortHelper(resolve_callables(group._sort_key, group), group.name, (group, attribute)) + for group, attribute in zip(groups, attributes, strict=False) + ] + ) + out_groups, out_attributes = zip(*[x.value for x in sorted_entries], strict=False) + return list(out_groups), list(out_attributes) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/group_extractors.py b/.venv/lib/python3.10/site-packages/cyclopts/group_extractors.py new file mode 100644 index 0000000000000000000000000000000000000000..0fce4ef440ca90c02b5c0add2999703fee28ac43 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/group_extractors.py @@ -0,0 +1,181 @@ +from typing import TYPE_CHECKING, Any + +from cyclopts.command_spec import CommandSpec +from cyclopts.group import Group +from cyclopts.utils import frozen + +if TYPE_CHECKING: + from cyclopts.core import App + + +@frozen +class RegisteredCommand: + """A command with the names it was registered under. + + Parameters + ---------- + names : tuple[str, ...] + All names (including aliases) this command is registered under. + app : App | CommandSpec + The command's App or unresolved CommandSpec instance. + """ + + names: tuple[str, ...] + app: "App | CommandSpec" + + +def _create_or_append( + group_mapping: list[tuple[Group, list[Any]]], + group: str | Group, + element: Any, +): + # updates group_mapping inplace. + if isinstance(group, str): + group = Group(group) + elif isinstance(group, Group): + pass + else: + raise TypeError + + for mapping in group_mapping: + if mapping[0].name == group.name: + mapping[1].append(element) + break + else: + group_mapping.append((group, [element])) + + +def groups_from_app(app: "App", resolve_lazy: bool = False) -> list[tuple[Group, list[RegisteredCommand]]]: + """Extract Group/App association from all commands of ``app``. + + Parameters + ---------- + app : App + The application to extract groups from. + resolve_lazy : bool + If ``True``, resolve lazy commands (import their modules) to include them + in the output. If ``False`` (default), skip unresolved lazy commands. + Set to ``True`` when generating static artifacts that need all commands, + such as shell completion scripts. + + Returns + ------- + list + List of items where each item is a tuple containing: + + * :class:`.Group` - The group + + * ``list[RegisteredCommand]`` - List of RegisteredCommand tuples containing + the registered names and app instance for each command. + """ + assert not isinstance(app.group_commands, str) + group_commands = app.group_commands or Group.create_default_commands() + + # First pass: collect all registered names and unique apps + # Use __iter__ and __getitem__ to properly handle meta parents + # + # Skip unresolved lazy commands to avoid importing modules unnecessarily. + # Group assignment for unresolved commands uses the group= field from + # CommandSpec (set at registration time). Groups defined only inside + # lazy modules won't be available until those modules are imported. + app_names: dict[int, list[str]] = {} + unique_apps: dict[int, App] = {} + lazy_names: dict[int, list[str]] = {} + unique_lazy: dict[int, CommandSpec] = {} + for name in app: + cmd = app._get_item(name, recurse_meta=True) + if isinstance(cmd, CommandSpec) and not cmd.is_resolved: + if not resolve_lazy: + # Skip hidden lazy commands early to avoid keeping + # an otherwise-empty group alive. + if not cmd.show: + continue + cmd_id = id(cmd) + lazy_names.setdefault(cmd_id, []).append(name) + if cmd_id not in unique_lazy: + unique_lazy[cmd_id] = cmd + continue + subapp = app[name] + app_id = id(subapp) + app_names.setdefault(app_id, []).append(name) + if app_id not in unique_apps: + unique_apps[app_id] = subapp + + group_mapping: list[tuple[Group, list[RegisteredCommand]]] = [ + (group_commands, []), + ] + + # Extract Group objects from resolved apps + for subapp in unique_apps.values(): + assert isinstance(subapp.group, tuple) + for group in subapp.group: + if isinstance(group, Group): + for mapping in group_mapping: + if mapping[0] is group: + break + elif mapping[0].name == group.name: + raise ValueError(f'Command Group "{group.name}" already exists.') + else: + group_mapping.append((group, [])) + + # Assign resolved apps to groups with their registered names + for app_id, subapp in unique_apps.items(): + names = tuple(app_names[app_id]) + registered_command = RegisteredCommand(names, subapp) + if subapp.group: + assert isinstance(subapp.group, tuple) + for group in subapp.group: + _create_or_append(group_mapping, group, registered_command) + else: + _create_or_append(group_mapping, group_commands, registered_command) + + # Extract Group objects from unresolved lazy commands + for cmd in unique_lazy.values(): + if cmd.group is not None: + groups = cmd.group if isinstance(cmd.group, tuple) else (cmd.group,) + for group in groups: + if isinstance(group, Group): + for mapping in group_mapping: + if mapping[0] is group: + break + elif mapping[0].name == group.name: + raise ValueError(f'Command Group "{group.name}" already exists.') + else: + group_mapping.append((group, [])) + + # Assign unresolved lazy commands to their group (or default) + for cmd_id, cmd in unique_lazy.items(): + names = tuple(lazy_names[cmd_id]) + registered_command = RegisteredCommand(names, cmd) + if cmd.group is not None: + groups = cmd.group if isinstance(cmd.group, tuple) else (cmd.group,) + for group in groups: + _create_or_append(group_mapping, group, registered_command) + else: + _create_or_append(group_mapping, group_commands, registered_command) + + # Remove empty groups + group_mapping = [x for x in group_mapping if x[1]] + + # Sort alphabetically by name + group_mapping.sort(key=lambda x: x[0].name) + + return group_mapping + + +def inverse_groups_from_app(input_app: "App", resolve_lazy: bool = False) -> list[tuple["App", list[Group]]]: + out = [] + seen_apps = [] + for group, registered_commands in groups_from_app(input_app, resolve_lazy=resolve_lazy): + for registered_command in registered_commands: + app = registered_command.app + if isinstance(app, CommandSpec): + continue + try: + index = seen_apps.index(app) + except ValueError: + index = len(out) + out.append((app, [])) + seen_apps.append(app) + out[index][1].append(group) + return out diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/help/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..30247814d18e02b121705df1e1f79f29560839e3 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/__init__.py @@ -0,0 +1,39 @@ +__all__ = [ + "Renderer", + "HelpEntry", + "TableSpec", + "PanelSpec", + "ColumnSpec", + "HelpPanel", + "create_parameter_help_panel", + "format_command_entries", + "format_doc", + "format_usage", + "InlineText", + "DefaultFormatter", + "MarkdownFormatter", + "PlainFormatter", + "NameRenderer", + "DescriptionRenderer", + "AsteriskRenderer", +] + +from .formatters import DefaultFormatter, MarkdownFormatter, PlainFormatter +from .help import ( + HelpEntry, + HelpPanel, + create_parameter_help_panel, + format_command_entries, + format_doc, + format_usage, +) +from .inline_text import InlineText +from .protocols import Renderer +from .specs import ( + AsteriskRenderer, + ColumnSpec, + DescriptionRenderer, + NameRenderer, + PanelSpec, + TableSpec, +) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a470e337ea8ccfcadb549809a1f8bea5f8841cb3 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/__init__.py @@ -0,0 +1,13 @@ +"""Help formatters for Cyclopts.""" + +from .default import DefaultFormatter +from .html import HtmlFormatter +from .markdown import MarkdownFormatter +from .plain import PlainFormatter + +__all__ = [ + "DefaultFormatter", + "HtmlFormatter", + "MarkdownFormatter", + "PlainFormatter", +] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/default.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/default.py new file mode 100644 index 0000000000000000000000000000000000000000..438f79031eb77afa47b4fe01c71410b9d00ed7df --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/default.py @@ -0,0 +1,231 @@ +"""Default Rich-based help formatter.""" + +from typing import TYPE_CHECKING, Any, Optional, Union + +from attrs import define + +from cyclopts.help.silent import SILENT + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions, RenderableType + + from cyclopts.help import HelpPanel + from cyclopts.help.protocols import ColumnSpecBuilder + from cyclopts.help.specs import ColumnSpec, PanelSpec, TableSpec + + +@define(kw_only=True) +class DefaultFormatter: + """Default help formatter using Rich library with customizable specs. + + Parameters + ---------- + panel_spec : Optional[PanelSpec] + Panel specification for the outer box/panel styling. + table_spec : Optional[TableSpec] + Table specification for table styling (borders, padding, etc). + column_specs : Optional[Union[tuple[ColumnSpec, ...], ColumnSpecBuilder]] + Column specifications or builder function for table columns. + + Notes + ----- + The relationship between these specs can be visualized as: + + :: + + ╭─ Commands ───────────────────────────────────────────────────────╮ ← panel_spec + │ serve Start the development server │ (border, title) + │ --help Display this message and exit. │ + ╰──────────────────────────────────────────────────────────────────╯ + ↑ ↑ + col[0] col[1] + (name) (description) + + ╭─ Parameters ─────────────────────────────────────────────────────╮ ← panel_spec + │ * PORT --port Server port number [required] │ + │ VERBOSE --verbose Enable verbose output [default: False] │ + ╰──────────────────────────────────────────────────────────────────╯ + ↑ ↑ ↑ + │ col[1] col[2] + │ (name/flags) (description) + │ + col[0] + (required marker) + + Where: + + - ``panel_spec`` controls the outer panel appearance (border, title, etc.) + - ``table_spec`` controls the inner table styling (no visible borders by default) + - ``column_specs`` defines individual columns (width, style, alignment, etc.) + """ + + panel_spec: Optional["PanelSpec"] = None + """Panel specification for the outer box/panel styling (border, title, padding, etc).""" + + table_spec: Optional["TableSpec"] = None + """Table specification for table styling (borders, padding, column separation, etc).""" + + column_specs: Union[tuple["ColumnSpec", ...], "ColumnSpecBuilder"] | None = None + """Column specifications or builder function for table columns (width, style, alignment, etc).""" + + @classmethod + def with_newline_metadata(cls, **kwargs): + """Create formatter with metadata on separate lines. + + Returns a DefaultFormatter configured to display parameter metadata + (choices, env vars, defaults) on separate indented lines rather + than inline with descriptions. + + Parameters + ---------- + **kwargs + Additional keyword arguments to pass to DefaultFormatter constructor. + + Returns + ------- + DefaultFormatter + Configured formatter instance with newline metadata display. + + Examples + -------- + >>> from cyclopts import App + >>> from cyclopts.help import DefaultFormatter + >>> app = App(help_formatter=DefaultFormatter.with_newline_metadata()) + """ + + def column_builder(console, options, entries): + import math + + from cyclopts.help.specs import ( + AsteriskColumn, + ColumnSpec, + DescriptionRenderer, + NameRenderer, + ) + + max_width = math.ceil(console.width * 0.35) + name_column = ColumnSpec( + renderer=NameRenderer(max_width=max_width), + header="Option", + style="cyan", + max_width=max_width, + ) + + description_column = ColumnSpec( + renderer=DescriptionRenderer(newline_metadata=True), header="Description", overflow="fold" + ) + + if any(x.required for x in entries): + return (AsteriskColumn, name_column, description_column) + return (name_column, description_column) + + return cls(column_specs=column_builder, **kwargs) + + def __call__(self, console: "Console", options: "ConsoleOptions", panel: "HelpPanel") -> None: + """Format and render a single help panel using Rich. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + panel : HelpPanel + Help panel to render. + """ + rendered = self._render_panel(panel, console, options) + console.print(rendered) + + def render_usage(self, console: "Console", options: "ConsoleOptions", usage: Any) -> None: + """Render the usage line. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + usage : Any + The usage line (Text or str). + """ + if usage: + from rich.text import Text + + # Add "Usage:" prefix if not already present (for custom usage strings) + usage_str = str(usage) + if not usage_str.strip().startswith("Usage:"): + if isinstance(usage, Text): + usage_with_label = Text("Usage: ", style="bold") + usage + else: + usage_with_label = Text(f"Usage: {usage}", style="bold") + else: + # Custom usage already has "Usage:", use as-is + usage_with_label = usage if isinstance(usage, Text) else Text(str(usage), style="bold") + console.print(usage_with_label) + + def render_description(self, console: "Console", options: "ConsoleOptions", description: Any) -> None: + """Render the description. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + description : Any + The description (can be various Rich renderables). + """ + if description: + console.print(description) + + def _render_panel(self, help_panel: "HelpPanel", console: "Console", options: "ConsoleOptions") -> "RenderableType": + """Render a single help panel.""" + if not help_panel.entries: + return SILENT + + from rich.console import Group as RichGroup + from rich.console import NewLine + from rich.text import Text + + from cyclopts.help.specs import ( + PanelSpec, + TableSpec, + get_default_command_columns, + get_default_parameter_columns, + ) + + panel_description = help_panel.description + if isinstance(panel_description, Text): + panel_description.end = "" + + if panel_description.plain: + panel_description = RichGroup(panel_description, NewLine(2)) + + # Get table spec (styling only) + table_spec = self.table_spec or TableSpec() + panel_spec = self.panel_spec or PanelSpec() + + # Determine/Resolve column specs + columns = self.column_specs + if columns is None: + # Use default columns based on panel format + if help_panel.format == "command": + columns = get_default_command_columns + else: + columns = get_default_parameter_columns + + if callable(columns): + # It's a column builder + columns = columns(console, options, help_panel.entries) + + # Build table with columns and entries + table = table_spec.build(columns, help_panel.entries) + + # Build the panel + assert panel_description is not None # Always true due to attrs converter + if panel_spec.title is None: + panel = panel_spec.build(RichGroup(panel_description, table), title=help_panel.title) + else: + panel = panel_spec.build(RichGroup(panel_description, table)) + + return panel diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/html.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/html.py new file mode 100644 index 0000000000000000000000000000000000000000..d5bc434d59e13bf0f12f0bc34f19773097edad08 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/html.py @@ -0,0 +1,263 @@ +"""HTML documentation formatter.""" + +import io +from typing import TYPE_CHECKING, Any, Optional + +from cyclopts._markup import escape_html, extract_text + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions + + from cyclopts.help import HelpEntry, HelpPanel + + +class HtmlFormatter: + """HTML documentation formatter. + + Parameters + ---------- + heading_level : int + Starting heading level for panels (default: 2). + E.g., 2 produces "

    Commands

    ", 3 produces "

    Commands

    ". + include_hidden : bool + Include hidden commands/parameters in documentation (default: False). + app_name : str + The root application name for generating anchor IDs. + command_chain : list[str] + The current command chain for generating anchor IDs. + """ + + def __init__( + self, + heading_level: int = 2, + include_hidden: bool = False, + app_name: str | None = None, + command_chain: list[str] | None = None, + ): + self.heading_level = heading_level + self.include_hidden = include_hidden + self.app_name = app_name + self.command_chain = command_chain or [] + self._output = io.StringIO() + + def reset(self) -> None: + """Reset the internal output buffer.""" + self._output = io.StringIO() + + def get_output(self) -> str: + """Get the accumulated HTML output. + + Returns + ------- + str + The HTML documentation string. + """ + return self._output.getvalue() + + def __call__( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + panel: "HelpPanel", + ) -> None: + """Format and render a help panel as HTML. + + Parameters + ---------- + console : Optional[Console] + Console for rendering (used for extracting plain text). + options : Optional[ConsoleOptions] + Console rendering options (unused for HTML). + panel : HelpPanel + Help panel to render. + """ + if not panel.entries: + return + + # Write panel as a section + self._output.write('
    \n') + + # Write panel title as heading + if panel.title: + title_text = escape_html(extract_text(panel.title, console)) + self._output.write(f'{title_text}\n') + + # Write panel description if present + if panel.description: + desc_text = escape_html(extract_text(panel.description, console)) + if desc_text: + self._output.write(f'
    {desc_text}
    \n') + + # Format entries based on panel type + if panel.format == "command": + self._format_command_panel(panel.entries, console) + elif panel.format == "parameter": + self._format_parameter_panel(panel.entries, console) + + self._output.write("
    \n") + + def _format_command_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format command entries as HTML. + + Parameters + ---------- + entries : list[HelpEntry] + Command entries to format. + console : Optional[Console] + Console for text extraction. + """ + if not entries: + return + + # Use list format instead of table + self._output.write('
      \n') + + for entry in entries: + names = entry.all_options + if not names: + name_html = "" + elif self.app_name: + # Generate anchor link + primary_name, aliases = names[0], names[1:] + if self.command_chain: + full_chain = self.command_chain + [primary_name] + anchor_id = f"{self.app_name}-{'-'.join(full_chain[1:])}".lower() + else: + anchor_id = f"{self.app_name}-{primary_name}".lower() + name_html = f'{escape_html(primary_name)}' + if aliases: + aliases_str = ", ".join(escape_html(n) for n in aliases) + name_html = f"{name_html} ({aliases_str})" + else: + # Non-linked format with aliases in parentheses + primary_name, aliases = names[0], names[1:] + name_html = f"{escape_html(primary_name)}" + if aliases: + aliases_str = ", ".join(escape_html(n) for n in aliases) + name_html = f"{name_html} ({aliases_str})" + + desc_html = escape_html(extract_text(entry.description, console)) + + self._output.write(f"
    • {name_html}") + if desc_html: + self._output.write(f": {desc_html}") + self._output.write("
    • \n") + + self._output.write("
    \n") + + def _format_parameter_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format parameter entries as HTML. + + Parameters + ---------- + entries : list[HelpEntry] + Parameter entries to format. + console : Optional[Console] + Console for text extraction. + """ + if not entries: + return + + # Use list format instead of table + self._output.write('
      \n') + + for entry in entries: + # Format name with code tags + if names := entry.all_options: + name_html = ", ".join(f"{escape_html(n)}" for n in names) + else: + name_html = "" + + # Start list item (no type display) + self._output.write(f"
    • {name_html}") + + # Add description + desc = extract_text(entry.description, console) + if desc: + self._output.write(f": {escape_html(desc)}") + + # Add metadata as styled badges + metadata_items = [] + + # Add required marker + if entry.required: + metadata_items.append('') + + # Add choices + if entry.choices: + choices_str = ", ".join(f"{escape_html(str(c))}" for c in entry.choices) + metadata_items.append( + f'' + ) + + # Add default + if entry.default is not None: + default_str = extract_text(entry.default, console) + metadata_items.append( + f'' + ) + + # Add environment variable + if entry.env_var: + env_html = ", ".join(f"{escape_html(e)}" for e in entry.env_var) + metadata_items.append( + f'' + ) + + # Write metadata + if metadata_items: + self._output.write(f'') + + self._output.write("
    • \n") + + self._output.write("
    \n") + + def render_usage( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + usage: Any, + ) -> None: + """Render the usage line as HTML. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + usage : Any + The usage line content. + """ + if usage: + usage_text = escape_html(extract_text(usage, console)) + if usage_text: + self._output.write('
    \n') + # Add "Usage:" prefix if not already present (for custom usage strings) + if not usage_text.strip().startswith("Usage:"): + self._output.write(f'
    Usage: {usage_text}
    \n') + else: + self._output.write(f'
    {usage_text}
    \n') + self._output.write("
    \n") + + def render_description( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + description: Any, + ) -> None: + """Render the description as HTML. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + description : Any + The description content. + """ + if description: + desc_text = escape_html(extract_text(description, console)) + if desc_text: + self._output.write(f'
    {desc_text}
    \n') diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/markdown.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/markdown.py new file mode 100644 index 0000000000000000000000000000000000000000..73160933becf4686b8c4e76c865e22a6ba5ef453 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/markdown.py @@ -0,0 +1,279 @@ +"""Markdown documentation formatter.""" + +import io +from typing import TYPE_CHECKING, Any, Optional + +from cyclopts._markup import extract_text + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions + + from cyclopts.help import HelpEntry, HelpPanel + + +class MarkdownFormatter: + """Markdown documentation formatter. + + Parameters + ---------- + heading_level : int + Starting heading level for panels (default: 2). + E.g., 2 produces "## Commands", 3 produces "### Commands". + table_style : str + Style for parameter/command tables: "table" or "list" (default: "table"). + include_hidden : bool + Include hidden commands/parameters in documentation (default: False). + """ + + def __init__( + self, + heading_level: int = 2, + table_style: str = "table", + include_hidden: bool = False, + ): + self.heading_level = heading_level + self.table_style = table_style + self.include_hidden = include_hidden + self._output = io.StringIO() + + def reset(self) -> None: + """Reset the internal output buffer.""" + self._output = io.StringIO() + + def get_output(self) -> str: + """Get the accumulated markdown output. + + Returns + ------- + str + The markdown documentation string. + """ + return self._output.getvalue() + + def __call__( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + panel: "HelpPanel", + ) -> None: + """Format and render a help panel as markdown. + + Parameters + ---------- + console : Optional[Console] + Console for rendering (used for extracting plain text). + options : Optional[ConsoleOptions] + Console rendering options (unused for markdown). + panel : HelpPanel + Help panel to render. + """ + if not panel.entries: + return + + # Write panel title as heading + if panel.title: + title_text = extract_text(panel.title, console) + heading = "#" * self.heading_level + self._output.write(f"{heading} {title_text}\n\n") + + # Write panel description if present + if panel.description: + desc_text = extract_text(panel.description, console) + if desc_text: + self._output.write(f"{desc_text}\n\n") + + # Format entries based on panel type + if panel.format == "command": + self._format_command_panel(panel.entries, console) + elif panel.format == "parameter": + self._format_parameter_panel(panel.entries, console) + + self._output.write("\n") + + def _format_command_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format command entries as markdown. + + Parameters + ---------- + entries : list[HelpEntry] + Command entries to format. + console : Optional[Console] + Console for text extraction. + """ + # Always use list style for Typer-like output + for entry in entries: + if names := entry.all_options: + # Use first name as primary, show aliases in parentheses + primary_name, aliases = names[0], names[1:] + if aliases: + name_display = f"{primary_name} ({', '.join(aliases)})" + else: + name_display = primary_name + desc = extract_text(entry.description, console, preserve_markup=True) + + if desc: + self._output.write(f"* `{name_display}`: {desc}") + else: + self._output.write(f"* `{name_display}`:") + + self._output.write("\n") + + def _format_parameter_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format parameter entries as markdown in Typer style. + + Parameters + ---------- + entries : list[HelpEntry] + Parameter entries to format. + console : Optional[Console] + Console for text extraction. + """ + # Always use list style for Typer-like output + for entry in entries: + if names := entry.all_options: + # Separate positional names from option names + positional_names = [n for n in names if not n.startswith("-")] + short_opts = [n for n in names if n.startswith("-") and not n.startswith("--")] + long_opts = [n for n in names if n.startswith("--")] + + # Determine if this is a positional argument (required, no default) + is_positional = entry.required and entry.default is None + + if is_positional and positional_names: + # Show uppercase positional name first, then any option names + parts = [positional_names[0].upper()] + parts.extend(long_opts) + name_str = ", ".join(parts) + else: + # For options, show long opts first, then short opts + if short_opts: + name_str = ", ".join(long_opts + short_opts) + elif positional_names: + # Has positional name but not required - show all + parts = [positional_names[0].upper()] + parts.extend(long_opts) + name_str = ", ".join(parts) + else: + name_str = ", ".join(long_opts) + + # Start the entry (no type display) + self._output.write(f"* `{name_str}`: ") + + # Add description with proper indentation for nested content + desc = extract_text(entry.description, console, preserve_markup=True) + if desc: + import re + + # Split into lines and indent continuation lines to nest under the bullet + lines = desc.split("\n") + self._output.write(lines[0]) # First line on same line as bullet + + # Track what type of list context we're in for proper nesting + in_numbered_list = False + + for line in lines[1:]: + if not line.strip(): # Blank line + self._output.write("\n") + else: + stripped = line.lstrip() + existing_indent = len(line) - len(stripped) + + # Check if this line starts a numbered list + if re.match(r"^\d+\.", stripped): + in_numbered_list = True + # Numbered lists need 4 spaces base indentation minimum + indent = max(existing_indent + 4, 4) + # Check if this is a bullet under a numbered list + elif re.match(r"^\-", stripped) and in_numbered_list: + # Bullets nested under numbered items need extra indentation + # At least 10 spaces (4 base + 3 for "N. " + 3 more for nesting) + indent = max(existing_indent + 4, 10) + elif re.match(r"^\-", stripped): + # Top-level bullets just need base indentation + indent = max(existing_indent + 4, 4) + else: + # Regular content preserves relative indentation + indent = existing_indent + 4 + + self._output.write("\n" + " " * indent + stripped) + + # Add metadata in brackets + # Handle required separately for bold formatting + is_required = False + if entry.required and not is_positional: + # Only show required for options, arguments show it differently + is_required = True + elif is_positional and entry.required: + # For positional args, add [required] at the end + is_required = True + + metadata = [] + if entry.choices: + choices_str = ", ".join(entry.choices) + metadata.append(f"choices: {choices_str}") + + if entry.env_var: + env_str = ", ".join(entry.env_var) + metadata.append(f"env: {env_str}") + + if entry.default is not None: + default_str = extract_text(entry.default, console) + metadata.append(f"default: {default_str}") + + # Write required in bold and separate brackets first + if is_required: + self._output.write(" **[required]**") + + # Write each metadata item in its own brackets with italics + for item in metadata: + self._output.write(f" *[{item}]*") + + self._output.write("\n") + + def render_usage( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + usage: Any, + ) -> None: + """Render the usage line as markdown. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + usage : Any + The usage line content. + """ + if usage: + usage_text = extract_text(usage, console) + if usage_text: + # Add "Usage:" prefix if not already present (for custom usage strings) + if not usage_text.strip().startswith("Usage:"): + self._output.write(f"```\nUsage: {usage_text}\n```\n\n") + else: + self._output.write(f"```\n{usage_text}\n```\n\n") + + def render_description( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + description: Any, + ) -> None: + """Render the description as markdown. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + description : Any + The description content. + """ + if description: + desc_text = extract_text(description, console) + if desc_text: + self._output.write(f"{desc_text}\n\n") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/plain.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/plain.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd29d0da9834d95cea7ba2eb2250b81388f8329 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/plain.py @@ -0,0 +1,273 @@ +"""Plain text help formatter for improved accessibility.""" + +import io +import textwrap +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions + + from cyclopts.help import HelpEntry, HelpPanel + + +def _to_plain_text(obj: Any, console: "Console") -> str: + """Extract plain text from Rich renderables. + + Parameters + ---------- + obj : Any + Object to convert to plain text. + console : ~rich.console.Console + Console for rendering Rich objects. + + Returns + ------- + str + Plain text representation. + """ + if obj is None: + return "" + + # Rich Text objects have a .plain property for plain text + if hasattr(obj, "plain"): + return obj.plain.rstrip() + + # For any Rich renderable, render without styles + if hasattr(obj, "__rich_console__"): + # Create a plain console that preserves layout but removes styling + from rich.console import Console + + plain_console = Console( + file=io.StringIO(), + width=console.width, + height=console.height, + tab_size=console.tab_size, + legacy_windows=console.legacy_windows, + safe_box=console.safe_box, + # Disable all styling + force_terminal=False, + no_color=True, + highlight=False, + markup=False, + emoji=False, + ) + with plain_console.capture() as capture: + plain_console.print(obj, end="") + return capture.get().rstrip() + + # Fallback for non-Rich objects + return str(obj).rstrip() + + +class PlainFormatter: + """Plain text formatter for improved accessibility. + + Parameters + ---------- + indent_width : int + Number of spaces to indent entries (default: 2). + max_width : Optional[int] + Maximum line width for wrapping text. + """ + + def __init__( + self, + indent_width: int = 2, + max_width: int | None = None, + ): + self.indent_width = indent_width + self.max_width = max_width + self.indent = " " * indent_width + + def _print_plain(self, console: "Console", text: str) -> None: + """Print text without any highlighting or markup.""" + console.print(text, highlight=False, markup=False) + + def __call__( + self, + console: "Console", + options: "ConsoleOptions", + panel: "HelpPanel", + ) -> None: + """Format and render a single help panel as plain text. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + panel : HelpPanel + Help panel to render. + """ + if not panel.entries: + return + + # Print panel title with appropriate formatting + if panel.title: + self._print_plain(console, f"{panel.title}:") + + # Print each entry in the panel + for entry in panel.entries: + desc = _to_plain_text(entry.description, console) + + # Format the entry line + if entry.all_options: + if panel.format == "parameter": + self._format_parameter_entry(entry.all_options, desc, console, entry) + else: + # Command formatter needs separate longs/shorts for its specific layout + self._format_command_entry(entry.positive_names, entry.positive_shorts, desc, console) + + # Add trailing newline for visual separation between panels + console.print() + + def render_usage( + self, + console: "Console", + options: "ConsoleOptions", + usage: Any, + ) -> None: + """Render the usage line. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + usage : Any + The usage line (Text or str). + """ + if usage: + usage_text = _to_plain_text(usage, console) + if usage_text: + # Add "Usage:" prefix if not already present (for custom usage strings) + if not usage_text.strip().startswith("Usage:"): + self._print_plain(console, f"Usage: {usage_text}") + else: + self._print_plain(console, usage_text) + console.print() + + def render_description( + self, + console: "Console", + options: "ConsoleOptions", + description: Any, + ) -> None: + """Render the description. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + description : Any + The description (can be various Rich renderables). + """ + if description: + desc_text = _to_plain_text(description, console) + if desc_text: + self._print_plain(console, desc_text) + console.print() + + def _format_parameter_entry( + self, + options: tuple[str, ...], + desc: str, + console: "Console", + entry: "HelpEntry", + ) -> None: + """Format and print a parameter entry. + + Parameters + ---------- + options : tuple[str, ...] + All parameter options in display order. + desc : str + Parameter description. + console : ~rich.console.Console + Console to print to. + entry : HelpEntry + The full help entry with metadata fields. + """ + if not options: + return + + # Build the description with metadata + desc_parts = [] + if desc: + desc_parts.append(desc) + + # Add metadata fields from entry + if entry.choices: + choices_str = ", ".join(entry.choices) + desc_parts.append(f"[choices: {choices_str}]") + + if entry.env_var: + env_vars_str = ", ".join(entry.env_var) + desc_parts.append(f"[env var: {env_vars_str}]") + + if entry.default is not None: + desc_parts.append(f"[default: {entry.default}]") + + if entry.required: + desc_parts.append("[required]") + + full_desc = " ".join(desc_parts) + + # Format: "option1, option2, ...: description" + options_str = ", ".join(options) + if full_desc: + text = f"{options_str}: {full_desc}" + else: + text = options_str + self._print_plain(console, textwrap.indent(text, self.indent)) + + def _format_command_entry( + self, + names: tuple[str, ...], + shorts: tuple[str, ...], + desc: str, + console: "Console", + ) -> None: + """Format and print a command entry. + + Parameters + ---------- + names : tuple[str, ...] + Command long names. + shorts : tuple[str, ...] + Short forms of the command. + desc : str + Command description. + console : ~rich.console.Console + Console to print to. + """ + # For commands, we typically want to show long names on separate lines + # and shorts together + if names: + for i, name in enumerate(names): + if i == 0: + # First name gets the shorts and description + parts = [name] + if shorts: + parts.append(", " + " ".join(shorts)) + entry_name = "".join(parts) + if desc: + text = f"{entry_name}: {desc}" + else: + text = entry_name + self._print_plain(console, textwrap.indent(text, self.indent)) + else: + # Additional names on separate lines + self._print_plain(console, textwrap.indent(name, self.indent)) + elif shorts: + # Only short names + shorts_str = " ".join(shorts) + if desc: + text = f"{shorts_str}: {desc}" + else: + text = shorts_str + self._print_plain(console, textwrap.indent(text, self.indent)) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/rst.py b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/rst.py new file mode 100644 index 0000000000000000000000000000000000000000..d91e609fd2a3f931db14d52a3251a847341fd72b --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/formatters/rst.py @@ -0,0 +1,246 @@ +"""reStructuredText documentation formatter.""" + +import io +from typing import TYPE_CHECKING, Any, Optional + +from cyclopts._markup import extract_text +from cyclopts.docs.rst import make_rst_section_header + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions + + from cyclopts.help import HelpEntry, HelpPanel + + +class RstFormatter: + """reStructuredText documentation formatter. + + Parameters + ---------- + heading_level : int + Starting heading level for panels (default: 2). + include_hidden : bool + Include hidden commands/parameters in documentation (default: False). + """ + + def __init__( + self, + heading_level: int = 2, + include_hidden: bool = False, + ): + self.heading_level = heading_level + self.include_hidden = include_hidden + self._output = io.StringIO() + + def reset(self) -> None: + """Reset the internal output buffer.""" + self._output = io.StringIO() + + def get_output(self) -> str: + """Get the accumulated RST output. + + Returns + ------- + str + The RST documentation string. + """ + return self._output.getvalue() + + def __call__( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + panel: "HelpPanel", + ) -> None: + """Format and render a help panel as RST. + + Parameters + ---------- + console : Optional[Console] + Console for rendering (used for extracting plain text). + options : Optional[ConsoleOptions] + Console rendering options (unused for RST). + panel : HelpPanel + Help panel to render. + """ + if not panel.entries: + return + + # Write panel title as heading + if panel.title: + title_text = extract_text(panel.title, console) + header = "\n".join(make_rst_section_header(title_text, self.heading_level)) + self._output.write(f"{header}\n\n") + + # Write panel description if present + if panel.description: + desc_text = extract_text(panel.description, console) + if desc_text: + self._output.write(f"{desc_text}\n\n") + + # Format entries based on panel type + if panel.format == "command": + self._format_command_panel(panel.entries, console) + elif panel.format == "parameter": + self._format_parameter_panel(panel.entries, console) + + self._output.write("\n") + + def _format_command_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format command entries as RST. + + Parameters + ---------- + entries : list[HelpEntry] + Command entries to format. + console : Optional[Console] + Console for text extraction. + """ + for entry in entries: + if names := entry.all_options: + # Use first name as primary, show aliases in parentheses + primary_name, aliases = names[0], names[1:] + if aliases: + name_display = f"{primary_name} ({', '.join(aliases)})" + else: + name_display = primary_name + + # Use definition list format + self._output.write(f"``{name_display}``\n") + + # Check if the description has RST markup to preserve + preserve_rst_markup = ( + hasattr(entry.description, "primary_renderable") + and hasattr(entry.description.primary_renderable, "__class__") + and "RestructuredText" in entry.description.primary_renderable.__class__.__name__ + ) + desc = extract_text(entry.description, console, preserve_markup=preserve_rst_markup) + if desc: + # Join multi-line descriptions into a single paragraph for proper RST formatting + # This prevents each line from being interpreted as a separate blockquote + desc_text = " ".join(line.strip() for line in desc.split("\n") if line.strip()) + self._output.write(f" {desc_text}\n\n") + + def _format_parameter_panel(self, entries: list["HelpEntry"], console: Optional["Console"]) -> None: + """Format parameter entries as RST. + + Parameters + ---------- + entries : list[HelpEntry] + Parameter entries to format. + console : Optional[Console] + Console for text extraction. + """ + for entry in entries: + if names := entry.all_options: + # Determine if we should display as positional based on requirement and default + is_positional = entry.required and entry.default is None and not any(n.startswith("-") for n in names) + + if is_positional: + # For positional arguments, show in uppercase + positional_names = [n for n in names if not n.startswith("-")] + name_str = positional_names[0].upper() if positional_names else names[0].upper() + else: + # For options, format with all forms + name_str = ", ".join(names) + + # Use definition list format + self._output.write(f"``{name_str}``\n") + + # Build description with metadata + desc_parts = [] + + # Add main description + # Check if the description has RST markup to preserve + preserve_rst_markup = ( + hasattr(entry.description, "primary_renderable") + and hasattr(entry.description.primary_renderable, "__class__") + and "RestructuredText" in entry.description.primary_renderable.__class__.__name__ + ) + desc = extract_text(entry.description, console, preserve_markup=preserve_rst_markup) + if desc: + desc_parts.append(desc) + + # Add metadata + metadata = [] + + if is_positional and entry.required: + metadata.append("**Required**") + elif entry.required and not is_positional: + metadata.append("**Required**") + + if entry.choices: + choices_str = ", ".join(f"``{c}``" for c in entry.choices) + metadata.append(f"Choices: {choices_str}") + + if entry.default is not None: + default_str = extract_text(entry.default, console, preserve_markup=False) + metadata.append(f"Default: ``{default_str}``") + + if entry.env_var: + env_str = ", ".join(f"``{e}``" for e in entry.env_var) + metadata.append(f"Environment variable: {env_str}") + + # Combine description and metadata - handle multi-line descriptions + if desc_parts: + # Join multi-line descriptions into a single paragraph for proper RST formatting + # This prevents each line from being interpreted as a separate blockquote + desc_text = " ".join(line.strip() for line in desc_parts[0].split("\n") if line.strip()) + self._output.write(f" {desc_text}") + + if metadata: + self._output.write(f" [{', '.join(metadata)}]") + self._output.write("\n\n") + elif metadata: + self._output.write(f" {', '.join(metadata)}\n\n") + + def render_usage( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + usage: Any, + ) -> None: + """Render the usage line as RST. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + usage : Any + The usage line content. + """ + if usage: + usage_text = extract_text(usage, console) + if usage_text: + # Use literal block for usage + self._output.write("::\n\n") + # Add "Usage:" prefix if not already present (for custom usage strings) + if not usage_text.strip().startswith("Usage:"): + self._output.write(f" Usage: {usage_text}\n") + else: + self._output.write(f" {usage_text}\n") + self._output.write("\n") + + def render_description( + self, + console: Optional["Console"], + options: Optional["ConsoleOptions"], + description: Any, + ) -> None: + """Render the description as RST. + + Parameters + ---------- + console : Optional[Console] + Console for text extraction. + options : Optional[ConsoleOptions] + Console rendering options (unused). + description : Any + The description content. + """ + if description: + desc_text = extract_text(description, console) + if desc_text: + self._output.write(f"{desc_text}\n\n") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/help.py b/.venv/lib/python3.10/site-packages/cyclopts/help/help.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea20ab96e29c068bbfa92ecb0fb61237c6c38e7 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/help.py @@ -0,0 +1,597 @@ +import inspect +import sys +from collections.abc import Iterable, Sequence +from enum import Enum +from functools import lru_cache +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + ForwardRef, + Literal, +) + +from attrs import define, evolve, field + +from cyclopts.annotations import resolve_annotated +from cyclopts.core import _get_root_module_name +from cyclopts.field_info import get_field_infos +from cyclopts.group import Group +from cyclopts.help.inline_text import InlineText +from cyclopts.help.silent import SILENT, SilentRich +from cyclopts.utils import SortHelper, frozen, is_class_and_subclass, resolve_callables + +if TYPE_CHECKING: + from rich.console import RenderableType + + from cyclopts.argument import Argument, ArgumentCollection + from cyclopts.core import App + + +@lru_cache(maxsize=16) +def docstring_parse(doc: str | None, format: str): + """Addon to :func:`docstring_parser.parse` that supports multi-line `short_description`.""" + import docstring_parser + + if not doc: + return docstring_parser.parse("") + + cleaned_doc = inspect.cleandoc(doc) + short_description_and_maybe_remainder = cleaned_doc.split("\n\n", 1) + + # Place multi-line summary into a single line. + # This kind of goes against PEP-0257, but any reasonable CLI command will + # have either no description, or it will have both a short and long description. + short = short_description_and_maybe_remainder[0].replace("\n", " ") + if len(short_description_and_maybe_remainder) == 1: + cleaned_doc = short + else: + cleaned_doc = short + "\n\n" + short_description_and_maybe_remainder[1] + + res = docstring_parser.parse(cleaned_doc) + + # Ensure a short description exists if there's a long description + assert not res.long_description or res.short_description + + return res + + +def _text_factory(): + from rich.text import Text + + return Text() + + +def _description_converter(value: Any | None) -> Any: + if value is None: + return _text_factory() + return value + + +@frozen(kw_only=True) +class HelpEntry: + """Container for help table entry data.""" + + positive_names: tuple[str, ...] = () + """Positive long option names (e.g., "--verbose", "--dry-run").""" + + positive_shorts: tuple[str, ...] = () + """Positive short option names (e.g., "-v", "-n").""" + + negative_names: tuple[str, ...] = () + """Negative long option names (e.g., "--no-verbose", "--no-dry-run").""" + + negative_shorts: tuple[str, ...] = () + """Negative short option names (e.g., "-N"). Rarely used.""" + + @property + def names(self) -> tuple[str, ...]: + """All long option names (positive + negative). For backward compatibility.""" + return self.positive_names + self.negative_names + + @property + def shorts(self) -> tuple[str, ...]: + """All short option names (positive + negative). For backward compatibility.""" + return self.positive_shorts + self.negative_shorts + + @property + def all_options(self) -> tuple[str, ...]: + """All options in display order: positive longs, positive shorts, negative longs, negative shorts.""" + return self.positive_names + self.positive_shorts + self.negative_names + self.negative_shorts + + description: Any = None + """Help text description for this entry. + + Typically a :class:`str` or a :obj:`~rich.console.RenderableType` + """ + + required: bool = False + """Whether this parameter/command is required.""" + + sort_key: Any = None + """Custom sorting key for ordering entries.""" + + type: Any | None = None + """Type annotation of the parameter.""" + + choices: tuple[str, ...] | None = None + """Available choices for this parameter.""" + + env_var: tuple[str, ...] | None = None + """Environment variable names that can set this parameter.""" + + default: str | None = None + """Default value for this parameter to display. None means no default to show.""" + + def copy(self, **kwargs): + return evolve(self, **kwargs) + + +@define +class HelpPanel: + """Data container for help panel information.""" + + format: Literal["command", "parameter"] + """Panel format type.""" + + title: "RenderableType" + """The title text displayed at the top of the help panel.""" + + description: Any = field( + default=None, + converter=_description_converter, + ) + """Optional description text displayed below the title. + + Typically a :class:`str` or a :obj:`~rich.console.RenderableType` + """ + + entries: list[HelpEntry] = field(factory=list) + """List of help entries to display (in order) in the panel.""" + + def copy(self, **kwargs): + return evolve(self, **kwargs) + + def _remove_duplicates(self): + seen, out = set(), [] + for item in self.entries: + hashable = (item.names, item.shorts) + if hashable not in seen: + seen.add(hashable) + out.append(item) + self.entries = out + + def _sort(self): + """Sort entries in-place.""" + if not self.entries: + return + + if self.format == "command": + sorted_sort_helper = SortHelper.sort( + [ + SortHelper( + entry.sort_key, + ( + entry.names[0].startswith("-") if entry.names else False, + entry.names[0] if entry.names else "", + ), + entry, + ) + for entry in self.entries + ] + ) + self.entries = [x.value for x in sorted_sort_helper] + else: + raise NotImplementedError + + +def _is_short(s): + return not s.startswith("--") and s.startswith("-") + + +def _categorize_keyword_arguments(argument_collection: "ArgumentCollection") -> tuple[list, list]: + """Categorize keyword arguments by requirement status for usage string formatting. + + Parameters + ---------- + argument_collection : ArgumentCollection + Collection of arguments to categorize. + + Returns + ------- + tuple[list, list] + (required_keyword, optional_keyword) where: + - required_keyword: Required keyword-only parameters + - optional_keyword: Optional keyword-only parameters and VAR_KEYWORD + """ + required, optional = [], [] + + for argument in argument_collection: + if not argument.show: + continue + + if argument.field_info.kind in (argument.field_info.VAR_KEYWORD,): + optional.append(argument) + elif argument.field_info.is_keyword_only: + if argument.required: + required.append(argument) + else: + optional.append(argument) + + return required, optional + + +def _categorize_positional_arguments(argument_collection: "ArgumentCollection") -> tuple[list, list]: + """Categorize positional arguments by requirement status for usage string formatting. + + Parameters + ---------- + argument_collection : ArgumentCollection + Collection of arguments to categorize. + + Returns + ------- + tuple[list, list] + (required_positional, optional_positional) where: + - required_positional: Required positional and VAR_POSITIONAL parameters + - optional_positional: Optional positional and VAR_POSITIONAL parameters + """ + required, optional = [], [] + + for argument in argument_collection: + if not argument.show: + continue + + if argument.field_info.kind == argument.field_info.VAR_POSITIONAL: + if argument.required: + required.append(argument) + else: + optional.append(argument) + elif argument.field_info.is_positional: + if argument.required: + required.append(argument) + else: + optional.append(argument) + + return required, optional + + +def format_usage( + app: "App", + command_chain: Iterable[str], +): + from rich.text import Text + + from cyclopts.annotations import get_hint_name + + usage = [] + + # If we're at the root level (no command chain), the app has a default_command, + # and no explicit name was set, derive a better name from sys.argv[0] + if not command_chain and app.default_command and not app._name: + # Use the same logic as in App.name property for apps without default_command + name = Path(sys.argv[0]).name + if name == "__main__.py": + name = _get_root_module_name() + app_name = name + else: + app_name = app.name[0] + + usage.append(app_name) + usage.extend(command_chain) + + for command in command_chain: + app = app[command] + + # Check for visible non-help/version commands without resolving lazy CommandSpecs. + help_version_flags = {*app.help_flags, *app.version_flags} + if any(x not in help_version_flags and app._get_item(x, recurse_meta=True).show for x in app): + usage.append("COMMAND") + + if app.default_command: + argument_collection = app.assemble_argument_collection(parse_docstring=False) + + required_keyword_params, optional_keyword_params = _categorize_keyword_arguments(argument_collection) + required_positional_args, optional_positional_args = _categorize_positional_arguments(argument_collection) + + for argument in required_keyword_params: + param_name = argument.name + type_name = get_hint_name(argument.hint).upper() + usage.append(f"{param_name} {type_name}") + + if optional_keyword_params: + usage.append("[OPTIONS]") + + for argument in required_positional_args: + if argument.field_info.kind == argument.field_info.VAR_POSITIONAL: + arg_name = argument.name.lstrip("-").upper() + usage.append(f"{arg_name}...") + else: + arg_name = argument.name.lstrip("-").upper() + usage.append(arg_name) + + if optional_positional_args: + has_var_positional = any( + arg.field_info.kind == arg.field_info.VAR_POSITIONAL for arg in optional_positional_args + ) + if has_var_positional: + usage.append("[ARGS...]") + else: + usage.append("[ARGS]") + + return Text(" ".join(usage) + "\n", style="bold") + + +def _smart_join(strings: Sequence[str]) -> str: + """Joins strings with a space, unless the previous string ended in a newline.""" + if not strings: + return "" + + result = [strings[0]] + for s in strings[1:]: + if result[-1].endswith("\n"): + result.append(s) + else: + result.append(" " + s) + + return "".join(result) + + +def format_doc(app: "App", format: str) -> InlineText | SilentRich: + raw_doc_string = app.help + + if not raw_doc_string: + return SILENT + + parsed = docstring_parse(raw_doc_string, format) + + components: list[str] = [] + if parsed.short_description: + components.append(parsed.short_description + "\n") + + if parsed.long_description: + if parsed.short_description: + components.append("\n") + components.append(parsed.long_description + "\n") + return InlineText.from_format(_smart_join(components), format=format, force_empty_end=True) + + +def _is_dynamic_structured_dict(argument: "Argument") -> bool: + """True if ``argument`` is ``dict[str, StructuredType]`` eligible for help expansion. + + Covers pydantic, dataclass, attrs, TypedDict, NamedTuple via the shared + ``get_field_infos`` dispatcher. Uses the same indicators as the parser's + dict branch in ``Argument.__attrs_post_init__``: ``_accepts_keywords`` is + set, ``_lookup`` is empty (no pre-built children — keys are dynamic), and + ``_default`` is the value type with structured fields. + + Also matches when ``_default`` is a string/``ForwardRef`` — an unresolved + self-reference from something like ``dict[str, "Node"]``. We can't walk + into it, but we treat it as assumed-structured so the expansion still + renders a ``.{NAME}`` layer before terminating. + """ + default = argument._default + if not (argument._accepts_keywords and not argument._lookup and default is not None): + return False + if isinstance(default, (str, ForwardRef)): + return True + try: + return bool(get_field_infos(default)) + except Exception: + return False + + +def _expand_structured_dict_for_help( + argument: "Argument", + format: str, + *, + seen: frozenset[int] = frozenset(), +) -> Iterable[HelpEntry]: + """Yield help entries for every leaf field of a ``dict[str, StructuredType]``. + + Reuses :meth:`ArgumentCollection._from_type_preview` so synthesized entries + carry the full metadata (choices, defaults, env_var, required propagation, + ``Parameter.help`` precedence, ``name_transform``) that the normal + per-argument path produces. + """ + # NOTE: help output uses cyclopts' name_transform (e.g. ``my_field`` → + # ``--models.{NAME}.my-field``). The parser currently only accepts the raw + # snake_case form for dict-nested paths; harmonizing the two is a separate + # follow-up (touches ``_argument.py`` token routing). + from cyclopts.argument import ArgumentCollection + from cyclopts.field_info import FieldInfo + from cyclopts.parameter import Parameter + + value_type = argument._default + + negatives = set(argument.negatives) + outer_long_names = tuple(o for o in argument.names if o not in negatives and not _is_short(o)) + + is_unresolvable = isinstance(value_type, (str, ForwardRef)) + is_cycle = id(value_type) in seen + + if is_cycle or is_unresolvable or not outer_long_names: + # Cycle or unresolved forward-ref — stop expanding, but still indicate + # the next level is another ``{NAME}`` layer by appending ``.{{NAME}}`` + # to the names. + base = _make_help_entry(argument, format) + if outer_long_names: + suffixed_names = tuple(f"{n}.{{NAME}}" for n in base.positive_names) + yield evolve(base, positive_names=suffixed_names) + else: + yield base + return + + new_seen = seen | {id(value_type)} + synthetic = FieldInfo( + names=("_preview",), + kind=FieldInfo.KEYWORD_ONLY, + annotation=value_type, + default=FieldInfo.empty, + required=argument.required, + ) + for outer in outer_long_names: + preview = ArgumentCollection._from_type( + synthetic, + (), + Parameter(name=(f"{outer}.{{NAME}}",)), + group_lookup={}, + group_arguments=Group.create_default_arguments(), + group_parameters=Group.create_default_parameters(), + _resolve_groups=False, + ) + for leaf in preview.filter_by(show=True): + if _is_dynamic_structured_dict(leaf): + yield from _expand_structured_dict_for_help(leaf, format, seen=new_seen) + else: + yield _make_help_entry(leaf, format) + + +def _make_help_entry(argument: "Argument", format: str) -> HelpEntry: + """Build a single ``HelpEntry`` for one ``Argument``. + + Extracted from ``create_parameter_help_panel`` so it can also be applied + to synthetic preview arguments (see ``_expand_structured_dict_for_help``). + """ + assert argument.parameter.name_transform + + options = list(argument.names) + + seen: set[str] = set() + options = [x for x in options if x not in seen and not seen.add(x)] + + if argument.index is not None: + label_source = next((o for o in options if o.startswith("--")), options[0]) + arg_name = label_source.lstrip("-").upper() + if arg_name != options[0]: + options = [arg_name, *options] + + negatives = set(argument.negatives) + positive_names = [o for o in options if o not in negatives and not _is_short(o)] + positive_shorts = [o for o in options if o not in negatives and _is_short(o)] + negative_names = [o for o in options if o in negatives and not _is_short(o)] + negative_shorts = [o for o in options if o in negatives and _is_short(o)] + + help_description = InlineText.from_format(argument.parameter.help, format=format) + + choices = argument.get_choices() + + env_var = None + if argument.parameter.show_env_var and argument.parameter.env_var: + env_var = tuple(argument.parameter.env_var) + + default = None + if argument.show_default: + default_val = argument.field_info.default + if is_class_and_subclass(argument.hint, Enum): + default = argument.parameter.name_transform(default_val.name) + elif isinstance(default_val, (list, tuple, set, frozenset)): + formatted_items = [] + for item in default_val: + if isinstance(item, Enum): + formatted_items.append(argument.parameter.name_transform(item.name)) + elif isinstance(item, str): + formatted_items.append(f"'{item}'") + else: + formatted_items.append(str(item)) + if isinstance(default_val, tuple): + if len(formatted_items) == 1: + default = "(" + formatted_items[0] + ",)" + else: + default = "(" + ", ".join(formatted_items) + ")" + elif isinstance(default_val, list): + default = "[" + ", ".join(formatted_items) + "]" + else: + default = "{" + ", ".join(formatted_items) + "}" + elif default_val == "": + default = '""' + else: + default = str(default_val) + if callable(argument.show_default): + default = argument.show_default(default_val) + + return HelpEntry( + positive_names=tuple(positive_names), + positive_shorts=tuple(positive_shorts), + negative_names=tuple(negative_names), + negative_shorts=tuple(negative_shorts), + description=help_description, + required=argument.required, + type=resolve_annotated(argument.field_info.annotation), + choices=choices, + env_var=env_var, + default=default, + ) + + +def create_parameter_help_panel( + group: "Group", + argument_collection: "ArgumentCollection", + format: str, +) -> HelpPanel: + from rich.text import Text + + kwargs = { + "format": "parameter", + "title": group.name, + "description": InlineText.from_format(group.help, format=format, force_empty_end=True) + if group.help + else Text(), + } + + help_panel = HelpPanel(**kwargs) + + entries_positional, entries_kw = [], [] + for argument in argument_collection.filter_by(show=True): + if _is_dynamic_structured_dict(argument): + entries_kw.extend(_expand_structured_dict_for_help(argument, format)) + continue + entry = _make_help_entry(argument, format) + if argument.field_info.is_positional: + entries_positional.append(entry) + else: + entries_kw.append(entry) + + help_panel.entries.extend(entries_positional) + help_panel.entries.extend(entries_kw) + + return help_panel + + +def format_command_entries(apps_with_names: Iterable, format: str) -> list[HelpEntry]: + """Format command entries for help display. + + Parameters + ---------- + apps_with_names : Iterable[RegisteredCommand] + Iterable of RegisteredCommand tuples. + format : str + Help text format. + + Returns + ------- + list[HelpEntry] + List of formatted help entries. + """ + entries = [] + for registered_command in apps_with_names: + app = registered_command.app + if not app.show: + continue + names = registered_command.names + # Commands don't have negative variants, so all names are "positive" + short_names, long_names = [], [] + for name in names: + short_names.append(name) if _is_short(name) else long_names.append(name) + + sort_key = resolve_callables(app.sort_key, app) + + entry = HelpEntry( + positive_names=tuple(long_names), + positive_shorts=tuple(short_names), + description=InlineText.from_format(docstring_parse(app.help, format).short_description, format=format), + sort_key=sort_key, + ) + if entry not in entries: + entries.append(entry) + return entries diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/inline_text.py b/.venv/lib/python3.10/site-packages/cyclopts/help/inline_text.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb5421d3e0bc6db1384a4d4a61cdf6415276cfc --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/inline_text.py @@ -0,0 +1,136 @@ +"""InlineText class for rich text rendering with appended metadata.""" + +import sys +from typing import TYPE_CHECKING + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +if TYPE_CHECKING: + from rich.console import RenderableType + from rich.text import Text + + +class InlineText: + def __init__(self, primary_renderable: "RenderableType", *, force_empty_end=False): + self.primary_renderable = primary_renderable + self.texts = [] + self.force_empty_end = force_empty_end + + @classmethod + def from_format( + cls, + content: str | None, + format: str, + *, + force_empty_end: bool = False, + show_errors: bool = False, + ) -> Self: + if content is None: + from rich.text import Text + + primary_renderable = Text(end="") + elif format == "plaintext": + from rich.text import Text + + primary_renderable = Text(content.rstrip()) + elif format in ("markdown", "md"): + from rich.markdown import Markdown + + primary_renderable = Markdown(content) + elif format in ("restructuredtext", "rst"): + from rich_rst import RestructuredText + + from cyclopts.help.rst_preprocessor import process_sphinx_directives + + processed_content = process_sphinx_directives(content) + primary_renderable = RestructuredText(processed_content, show_errors=show_errors) + elif format == "rich": + from rich.text import Text + + primary_renderable = Text.from_markup(content) + else: + raise ValueError(f'Unknown help_format "{format}"') + + return cls(primary_renderable, force_empty_end=force_empty_end) + + def append(self, text: "Text"): + self.texts.append(text) + + def __rich_console__(self, console, options): + from rich.segment import Segment + from rich.text import Text + + if not self.primary_renderable and not self.texts: + return + + # Group segments by line + lines_of_segments, current_line = [], [] + for segment in console.render(self.primary_renderable, options): + if segment.text == "\n": + lines_of_segments.append(current_line + [segment]) + current_line = [] + else: + current_line.append(segment) + + if current_line: + lines_of_segments.append(current_line) + + # If no content, just yield the additional texts + if not lines_of_segments: + if self.texts: + combined_text = Text.assemble(*self.texts) + yield from console.render(combined_text, options) + return + + # Yield all but the last line unchanged + for line in lines_of_segments[:-1]: + for segment in line: + yield segment + + # For the last line, concatenate all of our additional texts; + # We have to re-render to properly handle textwrapping. + if lines_of_segments: + last_line = lines_of_segments[-1] + + # Check for newline at end + has_newline = last_line and last_line[-1].text == "\n" + newline_segment = last_line.pop() if has_newline else None + + # rstrip the last segment + if last_line: + last_segment = last_line[-1] + last_segment = Segment( + last_segment.text.rstrip(), + style=last_segment.style, + control=last_segment.control, + ) + last_line[-1] = last_segment + + # Convert last line segments to text and combine with additional text + last_line_text = Text("", end="") + for segment in last_line: + if segment.text: + last_line_text.append(segment.text, segment.style) + + separator = Text(" ") + for text in self.texts: + if last_line_text: + last_line_text += separator + last_line_text += text + + # Re-render with proper wrapping + wrapped_segments = list(console.render(last_line_text, options)) + + if self.force_empty_end: + last_segment = wrapped_segments[-1] + if last_segment and not last_segment.text.endswith("\n"): + wrapped_segments.append(Segment("\n")) + + # Add back newline if it was present + if newline_segment: + wrapped_segments.append(newline_segment) + + yield from wrapped_segments diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/protocols.py b/.venv/lib/python3.10/site-packages/cyclopts/help/protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..3f974351673962d6d0e8fc5d99ce1770a8b76ae6 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/protocols.py @@ -0,0 +1,79 @@ +from typing import TYPE_CHECKING, Protocol, runtime_checkable + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions, RenderableType + + from .help import HelpEntry, HelpPanel + from .specs import ColumnSpec + + +@runtime_checkable +class Renderer(Protocol): + """Protocol for column renderers that transform HelpEntry to display content.""" + + def __call__(self, entry: "HelpEntry") -> "RenderableType": ... + + +@runtime_checkable +class ColumnSpecBuilder(Protocol): + """Protocol for ColumnSpecBuilders.""" + + def __call__( + self, console: "Console", options: "ConsoleOptions", entries: list["HelpEntry"] + ) -> tuple["ColumnSpec", ...]: + """Build column specifications based on console settings and entries. + + Parameters + ---------- + console : ~rich.console.Console + The Rich console instance. + options : ~rich.console.ConsoleOptions + Console rendering options. + entries : list[HelpEntry] + List of help entries to be displayed. + + Returns + ------- + tuple[ColumnSpec, ...] + Tuple of column specifications for table rendering. + """ + ... + + +@runtime_checkable +class HelpFormatter(Protocol): + """Protocol for help **formatter** functions. + + It's the Formatter's job to transform a :class:`.HelpPanel` into rendered text on the display. + + Implementations may optionally provide the following methods for custom rendering of "usage" and "description". If these methods are not provided, default rendering will be used. + + .. code-block:: python + + def render_usage(self, console: Console, options: ConsoleOptions, usage: Any) -> None: + \"\"\"Render the usage line.\"\"\" + ... + + def render_description(self, console: Console, options: ConsoleOptions, description: Any) -> None: + \"\"\"Render the description.\"\"\" + ... + """ + + def __call__( + self, + console: "Console", + options: "ConsoleOptions", + panel: "HelpPanel", + ) -> None: + """Format and render a single help panel. + + Parameters + ---------- + console : ~rich.console.Console + Console to render to. + options : ~rich.console.ConsoleOptions + Console rendering options. + panel : HelpPanel + Help panel to render (commands, parameters, etc). + """ + ... diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/rst_preprocessor.py b/.venv/lib/python3.10/site-packages/cyclopts/help/rst_preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..b43102f7f135747571095cdd714a7940d53f70bd --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/rst_preprocessor.py @@ -0,0 +1,424 @@ +"""Preprocessing utilities for reStructuredText content. + +This module provides workarounds for limitations in the rich_rst library when rendering +Sphinx directives. While rich_rst handles standard reStructuredText well, it doesn't +support Sphinx-specific directives (versionadded, deprecated, note, warning, etc.). + +Since Cyclopts docstrings may contain these directives, we preprocess RST content to +convert Sphinx directives into plain text annotations before passing to rich_rst. This +ensures users see meaningful information in CLI help rather than raw directive syntax. + +This is a pragmatic workaround; ideally this functionality would be in rich_rst itself. +""" + +import re +from collections.abc import Callable + + +def _skip_indented_block(lines: list[str], start_index: int, base_indent: int) -> int: + """Skip over lines indented more than base_indent. + + Parameters + ---------- + lines : list[str] + All lines in the text. + start_index : int + Index to start from. + base_indent : int + Base indentation level; lines must be indented more than this. + + Returns + ------- + int + Index of the first non-matching line (or len(lines) if reached end). + """ + i = start_index + while i < len(lines): + line = lines[i] + stripped = line.lstrip() + indent = len(line) - len(stripped) + + if not stripped or indent > base_indent: + i += 1 + else: + break + + return i + + +def _is_list_item(line: str) -> bool: + """Check if a line is a list item. + + Parameters + ---------- + line : str + The stripped line to check. + + Returns + ------- + bool + True if the line starts with a list marker. + """ + if not line: + return False + if line[0] in ("-", "*", "+"): + return len(line) == 1 or line[1] in (" ", "\t") + match = re.match(r"^\d+[\.\)](\s|$)", line) + return match is not None + + +def _gather_indented_block(lines: list[str], start_index: int, base_indent: int) -> tuple[list[str], int]: + """Gather lines indented more than base_indent, preserving structure. + + This function preserves paragraph breaks (blank lines), list structure, + and code block indentation while gathering indented content. List items + are kept on separate lines. Lines that are indented beyond the minimum + content indentation (like code blocks) preserve their relative indentation. + + Parameters + ---------- + lines : list[str] + All lines in the text. + start_index : int + Index to start from. + base_indent : int + Base indentation level; lines must be indented more than this. + + Returns + ------- + content_lines : list[str] + Content lines preserving paragraph structure. Each element represents + either a paragraph (multiple lines joined with spaces), a single + list item line, or indented code lines. + end_index : int + Index of the first non-matching line (or len(lines) if reached end). + """ + # First pass: collect all content and determine minimum indentation + collected_lines = [] + i = start_index + min_indent = float("inf") + + while i < len(lines): + line = lines[i] + stripped = line.lstrip() + indent = len(line) - len(stripped) + + if indent > base_indent or not stripped: + if stripped: + min_indent = min(min_indent, indent) + collected_lines.append((line, indent, stripped)) + i += 1 + else: + break + + if min_indent == float("inf"): + min_indent = base_indent + 1 + + # Second pass: format content preserving relative indentation + paragraphs = [] + current_paragraph = [] + last_was_empty = False + + for _, indent, stripped in collected_lines: + if not stripped: + if current_paragraph: + paragraphs.append(" ".join(current_paragraph)) + current_paragraph = [] + last_was_empty = True + else: + is_list = _is_list_item(stripped) + is_code_block = indent > min_indent + + if is_list: + if current_paragraph: + paragraphs.append(" ".join(current_paragraph)) + current_paragraph = [] + paragraphs.append(stripped) + last_was_empty = False + elif is_code_block: + # Preserve code block indentation + if current_paragraph: + paragraphs.append(" ".join(current_paragraph)) + current_paragraph = [] + # Preserve relative indentation (subtract min_indent to normalize) + relative_indent = indent - min_indent + paragraphs.append(" " * relative_indent + stripped) + last_was_empty = False + else: + if last_was_empty and current_paragraph: + paragraphs.append(" ".join(current_paragraph)) + current_paragraph = [] + current_paragraph.append(stripped) + last_was_empty = False + + if current_paragraph: + paragraphs.append(" ".join(current_paragraph)) + + return paragraphs, i + + +def _handle_version_directive( + directive_name: str, directive_arg: str, lines: list[str], start_index: int, current_indent: int +) -> tuple[str, int]: + """Handle versionadded and versionchanged directives. + + Parameters + ---------- + directive_name : str + Name of the directive (e.g., "versionadded"). + directive_arg : str + Version number argument. + lines : list[str] + All lines in the text. + start_index : int + Current line index. + current_indent : int + Current indentation level. + + Returns + ------- + tag : str + Formatted tag text. + next_index : int + Next line index to process. + """ + prefix = "Added" if directive_name == "versionadded" else "Changed" + tag = f"[{prefix} in v{directive_arg}]" + return tag, start_index + 1 + + +def _handle_deprecated_directive( + directive_name: str, directive_arg: str, lines: list[str], start_index: int, current_indent: int +) -> tuple[str, int]: + """Handle deprecated directive with optional content. + + Parameters + ---------- + directive_name : str + Name of the directive ("deprecated"). + directive_arg : str + Version number argument. + lines : list[str] + All lines in the text. + start_index : int + Current line index. + current_indent : int + Current indentation level. + + Returns + ------- + tag : str + Formatted tag text with optional content. + next_index : int + Next line index to process. + """ + paragraphs, next_i = _gather_indented_block(lines, start_index + 1, current_indent) + content = "\n\n".join(paragraphs).strip() + tag = f"[⚠ Deprecated in v{directive_arg}]" + return f"{tag} {content}" if content else tag, next_i + + +def _handle_admonition_directive( + directive_name: str, directive_arg: str, lines: list[str], start_index: int, current_indent: int +) -> tuple[str, int]: + """Handle note, warning, and seealso directives. + + Parameters + ---------- + directive_name : str + Name of the directive (e.g., "note", "warning", "seealso"). + directive_arg : str + Inline content on the directive line. + lines : list[str] + All lines in the text. + start_index : int + Current line index. + current_indent : int + Current indentation level. + + Returns + ------- + tag : str + Formatted tag text with content. + next_index : int + Next line index to process. + """ + paragraphs = [directive_arg] if directive_arg else [] + more_paragraphs, next_i = _gather_indented_block(lines, start_index + 1, current_indent) + paragraphs.extend(more_paragraphs) + + blocks = [] + current_list = [] + current_code_block = [] + + for para in paragraphs: + is_list = _is_list_item(para) + is_code = para.startswith(" ") and para.strip() # Code block lines start with space + + if is_list: + # Flush any current blocks + if current_code_block: + blocks.append("\n".join(current_code_block)) + current_code_block = [] + current_list.append(para) + elif is_code: + # Flush current list if any + if current_list: + blocks.append("\n".join(current_list)) + current_list = [] + current_code_block.append(para) + else: + # Regular paragraph + if current_list: + blocks.append("\n".join(current_list)) + current_list = [] + if current_code_block: + blocks.append("\n".join(current_code_block)) + current_code_block = [] + blocks.append(para) + + # Flush any remaining blocks + if current_list: + blocks.append("\n".join(current_list)) + if current_code_block: + blocks.append("\n".join(current_code_block)) + + content = "\n\n".join(blocks).strip() + + prefix_map = { + "note": "Note:", + "warning": "⚠ Warning:", + "seealso": "See also:", + } + prefix = prefix_map[directive_name] + formatted = f"\n\n{prefix} {content}\n\n" if content else f"\n\n{prefix}\n\n" + return formatted, next_i + + +DirectiveHandler = Callable[[str, str, list[str], int, int], tuple[str, int]] + +DIRECTIVE_HANDLERS: dict[str, DirectiveHandler] = { + "versionadded": _handle_version_directive, + "versionchanged": _handle_version_directive, + "deprecated": _handle_deprecated_directive, + "note": _handle_admonition_directive, + "warning": _handle_admonition_directive, + "seealso": _handle_admonition_directive, +} + + +def process_sphinx_directives(text: str | None) -> str: + """Process Sphinx directives in reStructuredText content for CLI help display. + + Converts Sphinx directives to readable format: + - .. versionadded:: X -> [Added in vX] + - .. versionchanged:: X -> [Changed in vX] + - .. deprecated:: X -> [⚠ Deprecated in vX] + - .. note:: content -> Note: content + - .. warning:: content -> ⚠ Warning: content + - .. seealso:: content -> See also: content + + Unknown directives are silently removed but logged as debug messages. + + Parameters + ---------- + text : str | None + The reStructuredText content to process. + + Returns + ------- + str + Processed text with directives converted to inline annotations. + Returns empty string if input is None or empty. + """ + if not text: + return "" + + lines = text.split("\n") + result_parts = [] + version_tags = [] + first_inline_directive_idx = None + i = 0 + + # Admonition directives that should appear inline at their position + admonition_directives = {"note", "warning", "seealso"} + + while i < len(lines): + line = lines[i] + stripped = line.lstrip() + current_indent = len(line) - len(stripped) + + if stripped.startswith("..") and "::" in stripped: + match = re.match(r"\.\.\s+(\w+)::\s*(.*)", stripped) + if match: + directive_name = match.group(1) + directive_arg = match.group(2).strip() + + handler = DIRECTIVE_HANDLERS.get(directive_name) + if handler: + tag, next_i = handler(directive_name, directive_arg, lines, i, current_indent) + if directive_name in admonition_directives: + # Track position of first inline directive + if first_inline_directive_idx is None: + first_inline_directive_idx = len(result_parts) + # Add inline directive (strip() removes the newlines added by handler) + result_parts.append(tag.strip()) + else: + # Collect version/deprecated directives + version_tags.append(tag) + i = next_i + else: + i = _skip_indented_block(lines, i + 1, current_indent) + else: + i = _skip_indented_block(lines, i + 1, current_indent) + else: + result_parts.append(line) + i += 1 + + # Append version tags + if version_tags: + # If there are inline directives and no text after them, insert tags before first inline directive + if first_inline_directive_idx is not None: + # Check if there's any non-empty text after the first inline directive + has_text_after = any( + result_parts[i].strip() for i in range(first_inline_directive_idx + 1, len(result_parts)) + ) + if not has_text_after: + # Insert before first inline directive + _insert_version_tags_at_index(result_parts, version_tags, first_inline_directive_idx) + else: + # Insert at the end + _insert_version_tags(result_parts, version_tags) + else: + # No inline directives, insert at the end + _insert_version_tags(result_parts, version_tags) + + result = "\n".join(result_parts).strip() + return result + + +def _insert_version_tags(result_parts: list[str], version_tags: list[str]) -> None: + """Insert version tags at the end of the last non-empty line.""" + tags_text = " ".join(version_tags) + if result_parts: + # Find last non-empty line + for idx in range(len(result_parts) - 1, -1, -1): + if result_parts[idx].strip(): + result_parts[idx] = f"{result_parts[idx]} {tags_text}" + return + # All lines are empty, append tags as new line + result_parts.append(tags_text) + else: + result_parts.append(tags_text) + + +def _insert_version_tags_at_index(result_parts: list[str], version_tags: list[str], before_index: int) -> None: + """Insert version tags before the specified index, appending to the last non-empty line before that index.""" + tags_text = " ".join(version_tags) + # Find last non-empty line before the index + for idx in range(before_index - 1, -1, -1): + if result_parts[idx].strip(): + result_parts[idx] = f"{result_parts[idx]} {tags_text}" + return + # All lines before index are empty, insert at the index + result_parts.insert(before_index, tags_text) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/silent.py b/.venv/lib/python3.10/site-packages/cyclopts/help/silent.py new file mode 100644 index 0000000000000000000000000000000000000000..178690aecb02940df79fe2b60e56ea49380a8c05 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/silent.py @@ -0,0 +1,18 @@ +"""Silent Rich object that renders nothing.""" + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from rich.console import Console, ConsoleOptions, RenderResult + + +class SilentRich: + """Dummy object that causes nothing to be printed.""" + + def __rich_console__(self, console: "Console", options: "ConsoleOptions") -> "RenderResult": + # This generator yields nothing, so ``rich`` will print nothing for this object. + if False: + yield + + +SILENT = SilentRich() diff --git a/.venv/lib/python3.10/site-packages/cyclopts/help/specs.py b/.venv/lib/python3.10/site-packages/cyclopts/help/specs.py new file mode 100644 index 0000000000000000000000000000000000000000..536e96c01ba7598ebe810205d2c5c2ff73751943 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/help/specs.py @@ -0,0 +1,834 @@ +import math +import textwrap +from collections.abc import Iterable +from operator import attrgetter +from typing import TYPE_CHECKING, Literal, Optional, Union + +from attrs import evolve + +from cyclopts.utils import frozen + +if TYPE_CHECKING: + from rich.box import Box + from rich.console import Console, ConsoleOptions, RenderableType + from rich.padding import PaddingDimensions + from rich.panel import Panel + from rich.style import StyleType + from rich.table import Table + + from cyclopts.help import HelpEntry + from cyclopts.help.protocols import Renderer + + +class NameRenderer: + """Renderer for parameter/command names with optional text wrapping. + + Parameters + ---------- + max_width : int | None + Maximum width for wrapping. If None, no wrapping is applied. + """ + + def __init__(self, max_width: int | None = None): + """Initialize the renderer with formatting options. + + Parameters + ---------- + max_width : int | None + Maximum width for wrapping. If None, no wrapping is applied. + """ + self.max_width = max_width + + def __call__(self, entry: "HelpEntry") -> "RenderableType": + """Render the names column with optional text wrapping. + + Parameters + ---------- + entry : HelpEntry + The table entry to render. + + Returns + ------- + ~rich.console.RenderableType + Combined names and shorts, optionally wrapped. + Order: positive_names, positive_shorts, negative_names, negative_shorts + """ + text = " ".join(entry.all_options) + + if self.max_width is None: + return text + + wrapped = textwrap.wrap( + text, + self.max_width, + subsequent_indent=" ", + break_on_hyphens=False, + tabsize=4, + ) + + return "\n".join(wrapped) + + +class CommandNameRenderer: + """Renderer for command names with aliases in parentheses. + + Displays commands in argparse-style format: ``primary (alias1, alias2)``. + + Parameters + ---------- + max_width : int | None + Maximum width for wrapping. If None, no wrapping is applied. + """ + + def __init__(self, max_width: int | None = None): + """Initialize the renderer with formatting options. + + Parameters + ---------- + max_width : int | None + Maximum width for wrapping. If None, no wrapping is applied. + """ + self.max_width = max_width + + def __call__(self, entry: "HelpEntry") -> "RenderableType": + """Render command name with aliases in parentheses. + + Parameters + ---------- + entry : HelpEntry + The table entry to render. + + Returns + ------- + ~rich.console.RenderableType + Primary command name with aliases in parentheses. + """ + primary = entry.all_options[0] if entry.all_options else "" + aliases = list(entry.all_options[1:]) + + if aliases: + text = f"{primary} ({', '.join(aliases)})" + else: + text = primary + + if self.max_width is None: + return text + + wrapped = textwrap.wrap( + text, + self.max_width, + subsequent_indent=" ", + break_on_hyphens=False, + tabsize=4, + ) + + return "\n".join(wrapped) + + +class DescriptionRenderer: + """Renderer for descriptions with configurable metadata formatting. + + Parameters + ---------- + newline_metadata : bool + If True, display metadata (choices, env vars, defaults) on separate lines. + If False (default), display metadata inline with the description. + """ + + def __init__(self, newline_metadata: bool = False): + """Initialize the renderer with formatting options. + + Parameters + ---------- + newline_metadata : bool + If True, display metadata on separate lines instead of inline. + """ + self.newline_metadata = newline_metadata + + def __call__(self, entry: "HelpEntry") -> "RenderableType": + """Render parameter description with metadata annotations. + + Enriches the base description with choices, environment variables, + default values, and required status. + + Parameters + ---------- + entry : HelpEntry + The table entry to render. + + Returns + ------- + ~rich.console.RenderableType + Description with appended metadata. + """ + from rich.text import Text + + from cyclopts.help.inline_text import InlineText + + description = entry.description + if description is None: + description = InlineText(Text()) + elif not isinstance(description, InlineText): + # Convert to InlineText if it isn't already + if hasattr(entry.description, "__rich_console__"): + # It's already a Rich renderable, wrap it + description = InlineText(description) + else: + # Convert to Text first, then wrap in InlineText + from rich.text import Text + + description = InlineText(Text(str(description))) + + # Collect metadata items + metadata_items = [] + + if entry.choices: + choices_str = ", ".join(entry.choices) + metadata_items.append(Text(rf"[choices: {choices_str}]", "dim")) + + if entry.env_var: + env_vars_str = ", ".join(entry.env_var) + metadata_items.append(Text(rf"[env var: {env_vars_str}]", "dim")) + + if entry.default is not None: + metadata_items.append(Text(rf"[default: {entry.default}]", "dim")) + + if entry.required: + metadata_items.append(Text(r"[required]", "dim red")) + + # Apply metadata based on formatting mode + if self.newline_metadata and metadata_items: + # Add metadata on separate lines with indentation + from rich.console import Group as RichGroup + from rich.text import Text + + # Create a list of renderables to group + renderables = [] + + # Add the original description first + if description.primary_renderable: + renderables.append(description.primary_renderable) + + # Add each metadata item without indentation + for item in metadata_items: + renderables.append(item) + + # Return a Rich Group that stacks these vertically + return RichGroup(*renderables) if renderables else Text() + else: + # Original inline behavior + for item in metadata_items: + description.append(item) + + return description + + +class AsteriskRenderer: + """Renderer for required parameter asterisk indicator. + + A simple renderer that displays an asterisk (*) for required parameters. + """ + + def __call__(self, entry: "HelpEntry") -> "RenderableType": + """Render an asterisk for required parameters. + + Parameters + ---------- + entry : HelpEntry + The table entry to render. + + Returns + ------- + ~rich.console.RenderableType + An asterisk if the entry is required, empty string otherwise. + """ + return "*" if entry.required else "" + + +@frozen +class ColumnSpec: + """Specification for a single column in a help table. + + Used by :class:`~cyclopts.help.formatters.default.DefaultFormatter` to define + how individual columns are rendered in help tables. Each column can have its + own renderer, styling, and layout properties. + + See Also + -------- + ~cyclopts.help.formatters.default.DefaultFormatter : The formatter that uses these specs. + ~cyclopts.help.specs.TableSpec : Specification for the entire table. + ~cyclopts.help.specs.PanelSpec : Specification for the outer panel. + """ + + renderer: Union[str, "Renderer"] + """Specifies how to extract and render cell content from a :class:`~cyclopts.help.HelpEntry`. + + Can be either: + + - A string: The attribute name to retrieve from :class:`~cyclopts.help.HelpEntry` (e.g., 'names', + 'description', 'required', 'type'). The string is displayed as-is. + - A callable: A function matching the :class:`~cyclopts.help.protocols.Renderer` protocol. + The function receives a :class:`~cyclopts.help.HelpEntry` and should return a + :class:`~rich.console.RenderableType` (str, :class:`~rich.text.Text`, or other Rich renderable). + + Examples:: + + # String renderer - get attribute directly + ColumnSpec(renderer="description") + + # Callable renderer - custom formatting + def format_names(entry: HelpEntry) -> str: + return ", ".join(entry.names) if entry.names else "" + ColumnSpec(renderer=format_names) + """ + + header: str = "" + """Column header text displayed at the top of the column. + + Example:: + + header="Options" renders: + ┌─────────┬─────────────┐ + │ Options │ Description │ + ├─────────┼─────────────┤ + │ --help │ Show help │ + └─────────┴─────────────┘ + """ + + footer: str = "" + """Column footer text displayed at the bottom of the column. + + Example:: + + footer="Required" renders: + ┌──────────┬────────────┐ + │ --help │ Show help │ + ├──────────┼────────────┤ + │ Required │ │ + └──────────┴────────────┘ + """ + + header_style: Optional["StyleType"] = None + """Style applied to the column header text. + + Corresponds to the ``header_style`` parameter of :meth:`rich.table.Table.add_column`. + """ + + footer_style: Optional["StyleType"] = None + """Style applied to the column footer text. + + Corresponds to the ``footer_style`` parameter of :meth:`rich.table.Table.add_column`. + """ + + style: Optional["StyleType"] = None + """Default style applied to all cells in this column. + + Corresponds to the ``style`` parameter of :meth:`rich.table.Table.add_column`. + """ + + justify: Literal["default", "left", "center", "right", "full"] = "left" + """Text justification within the column. + + Corresponds to the ``justify`` parameter of :meth:`rich.table.Table.add_column`. + """ + + vertical: Literal["top", "middle", "bottom"] = "top" + """Vertical alignment of text within cells. + + Corresponds to the ``vertical`` parameter of :meth:`rich.table.Table.add_column`. + """ + + overflow: Literal["fold", "crop", "ellipsis", "ignore"] = "ellipsis" + """How to handle text that exceeds column width. + + Corresponds to the ``overflow`` parameter of :meth:`rich.table.Table.add_column`. + """ + + width: int | None = None + """Fixed width for the column in characters. + + Corresponds to the ``width`` parameter of :meth:`rich.table.Table.add_column`. + """ + + min_width: int | None = None + """Minimum width for the column in characters. + + Corresponds to the ``min_width`` parameter of :meth:`rich.table.Table.add_column`. + """ + + max_width: int | None = None + """Maximum width for the column in characters. + + Corresponds to the ``max_width`` parameter of :meth:`rich.table.Table.add_column`. + """ + + ratio: int | None = None + """Relative width ratio compared to other columns. + + Corresponds to the ``ratio`` parameter of :meth:`rich.table.Table.add_column`. + """ + + no_wrap: bool = False + """Prevent text wrapping in the column. + + Corresponds to the ``no_wrap`` parameter of :meth:`rich.table.Table.add_column`. + """ + + highlight: bool | None = None + """Enable automatic highlighting of text in the column. + + Corresponds to the ``highlight`` parameter of :meth:`rich.table.Table.add_column`. + """ + + def _render_cell(self, entry: "HelpEntry") -> "RenderableType": + """Render the cell content based on the renderer type. + + If renderer is a string, retrieves that attribute from the entry. + If renderer is callable, calls it with the entry. + """ + if isinstance(self.renderer, str): + value = attrgetter(self.renderer)(entry) + elif callable(self.renderer): + value = self.renderer(entry) + else: + value = None + return "" if value is None else value + + def copy(self, **kwargs): + return evolve(self, **kwargs) + + +# For Parameters: +AsteriskColumn = ColumnSpec( + renderer=AsteriskRenderer(), + header="", + justify="left", + width=1, + style="red bold", +) + +NameColumn = ColumnSpec( + renderer=NameRenderer(), + header="Option", + justify="left", + style="cyan", +) + +DescriptionColumn = ColumnSpec(renderer=DescriptionRenderer(), header="Description", justify="left", overflow="fold") + + +def get_default_command_columns( + console: "Console", options: "ConsoleOptions", entries: list["HelpEntry"] +) -> tuple[ColumnSpec, ...]: + """Get default column specifications for command display. + + Parameters + ---------- + console : ~rich.console.Console + Rich console for width calculations. + options : ~rich.console.ConsoleOptions + Console rendering options. + entries : list[HelpEntry] + Command entries to display. + + Returns + ------- + tuple[ColumnSpec, ...] + Column specifications for command table. + """ + max_width = math.ceil(console.width * 0.35) + command_column = ColumnSpec( + renderer=CommandNameRenderer(max_width=max_width), + header="Command", + justify="left", + style="cyan", + max_width=max_width, + ) + + return ( + command_column, + DescriptionColumn, + ) + + +def get_default_parameter_columns( + console: "Console", options: "ConsoleOptions", entries: list["HelpEntry"] +) -> tuple[ColumnSpec, ...]: + """Get default column specifications for parameter display. + + Parameters + ---------- + console : ~rich.console.Console + Rich console for width calculations. + options : ~rich.console.ConsoleOptions + Console rendering options. + entries : list[HelpEntry] + Parameter entries to display. + + Returns + ------- + tuple[ColumnSpec, ...] + Column specifications for parameter table. + """ + max_width = math.ceil(console.width * 0.35) + name_column = ColumnSpec( + renderer=NameRenderer(max_width=max_width), + header="Option", + justify="left", + style="cyan", + max_width=max_width, + ) + + if any(x.required for x in entries): + return ( + AsteriskColumn, + name_column, + DescriptionColumn, + ) + else: + return ( + name_column, + DescriptionColumn, + ) + + +@frozen +class TableSpec: + """Specification for table layout and styling. + + Used by :class:`~cyclopts.help.formatters.default.DefaultFormatter` to control + the appearance of tables that display commands and parameters. This spec defines + table-wide properties like borders, headers, and padding. + + See Also + -------- + ~cyclopts.help.formatters.default.DefaultFormatter : The formatter that uses these specs. + ~cyclopts.help.specs.ColumnSpec : Specification for individual columns. + ~cyclopts.help.specs.PanelSpec : Specification for the outer panel. + """ + + # Intrinsic table styling/config + title: str | None = None + """Title text displayed above the table. + + Corresponds to the ``title`` parameter of :class:`~rich.table.Table`. + """ + + caption: str | None = None + """Caption text displayed below the table. + + Corresponds to the ``caption`` parameter of :class:`~rich.table.Table`. + """ + + style: Optional["StyleType"] = None + """Default style applied to the entire table. + + Corresponds to the ``style`` parameter of :class:`~rich.table.Table`. + """ + + border_style: Optional["StyleType"] = None + """Style applied to table borders. + + Corresponds to the ``border_style`` parameter of :class:`~rich.table.Table`. + """ + + header_style: Optional["StyleType"] = None + """Default style for all table headers (can be overridden per column). + + Corresponds to the ``header_style`` parameter of :class:`~rich.table.Table`. + """ + + footer_style: Optional["StyleType"] = None + """Default style for all table footers (can be overridden per column). + + Corresponds to the ``footer_style`` parameter of :class:`~rich.table.Table`. + """ + + box: Optional["Box"] = None + """Box drawing style for the table borders. + + Corresponds to the ``box`` parameter of :class:`~rich.table.Table`. See :mod:`rich.box` for available styles. + """ + + show_header: bool = False + """Whether to display column headers. + + Corresponds to the ``show_header`` parameter of :class:`~rich.table.Table`. + """ + + show_footer: bool = False + """Whether to display column footers. + + Corresponds to the ``show_footer`` parameter of :class:`~rich.table.Table`. + """ + + show_lines: bool = False + """Whether to show horizontal lines between rows. + + Corresponds to the ``show_lines`` parameter of :class:`~rich.table.Table`. + """ + + show_edge: bool = True + """Whether to draw a box around the outside of the table. + + Corresponds to the ``show_edge`` parameter of :class:`~rich.table.Table`. + """ + + expand: bool = False + """Whether the table should expand to fill available width. + + Corresponds to the ``expand`` parameter of :class:`~rich.table.Table`. + """ + + pad_edge: bool = False + """Whether to add padding to the table edges. + + Corresponds to the ``pad_edge`` parameter of :class:`~rich.table.Table`. + """ + + padding: "PaddingDimensions" = (0, 2, 0, 0) + """Padding around cell content (top, right, bottom, left). + + Corresponds to the ``padding`` parameter of :class:`~rich.table.Table`. + """ + + collapse_padding: bool = False + """Whether to collapse padding when adjacent cells are empty. + + Corresponds to the ``collapse_padding`` parameter of :class:`~rich.table.Table`. + """ + + width: int | None = None + """Fixed width for the table in characters. + + Corresponds to the ``width`` parameter of :class:`~rich.table.Table`. + """ + + min_width: int | None = None + """Minimum width for the table in characters. + + Corresponds to the ``min_width`` parameter of :class:`~rich.table.Table`. + """ + + safe_box: bool | None = None + """Whether to use ASCII-safe box characters for compatibility. + + Corresponds to the ``safe_box`` parameter of :class:`~rich.table.Table`. + """ + + def build( + self, + columns: tuple[ColumnSpec, ...], + entries: Iterable["HelpEntry"], + **overrides, + ) -> "Table": + """Construct and populate a rich.Table. + + Parameters + ---------- + columns : tuple[ColumnSpec, ...] + Column specifications defining the table structure. + entries : Iterable[HelpEntry] + Table entries to populate the table with. + **overrides + Per-render overrides for table settings. + + Returns + ------- + Table + A populated Rich Table. + """ + # If show_header is True but all columns have empty headers, don't show the header + # This prevents an empty line from appearing at the top of the table + show_header = self.show_header + if show_header and all(not col.header for col in columns): + show_header = False + + opts = { + "title": self.title, + "caption": self.caption, + "style": self.style, + "border_style": self.border_style, + "header_style": self.header_style, + "footer_style": self.footer_style, + "box": self.box, + "show_header": show_header, + "show_footer": self.show_footer, + "show_lines": self.show_lines, + "show_edge": self.show_edge, + "expand": self.expand, + "pad_edge": self.pad_edge, + "padding": self.padding, + "collapse_padding": self.collapse_padding, + "width": self.width, + "min_width": self.min_width, + "safe_box": self.safe_box, + } + opts.update(overrides) + + from rich.table import Table + + table = Table(**opts) + + # Add columns + for column in columns: + col_opts = { + "header": column.header, + "footer": column.footer, + "header_style": column.header_style, + "footer_style": column.footer_style, + "style": column.style, + "justify": column.justify, + "vertical": column.vertical, + "overflow": column.overflow, + "width": column.width, + "min_width": column.min_width, + "max_width": column.max_width, + "ratio": column.ratio, + "no_wrap": column.no_wrap, + } + if column.highlight is not None: + col_opts["highlight"] = column.highlight + table.add_column(**col_opts) + + # Add entries + for e in entries: + cells = [col._render_cell(e) for col in columns] + table.add_row(*cells) + + return table + + def copy(self, **kwargs): + return evolve(self, **kwargs) + + +@frozen +class PanelSpec: + """Specification for panel (outer box) styling. + + Used by :class:`~cyclopts.help.formatters.default.DefaultFormatter` to control + the appearance of the outer panel that wraps help sections. This spec defines + the panel's border, title, subtitle, and overall styling. + + See Also + -------- + ~cyclopts.help.formatters.default.DefaultFormatter : The formatter that uses these specs. + ~cyclopts.help.specs.TableSpec : Specification for the inner table. + ~cyclopts.help.specs.ColumnSpec : Specification for individual columns. + """ + + # Content-independent panel chrome + title: Optional["RenderableType"] = None + """Title text displayed at the top of the panel. + + Corresponds to the ``title`` parameter of :class:`~rich.panel.Panel`. + """ + + subtitle: Optional["RenderableType"] = None + """Subtitle text displayed at the bottom of the panel. + + Corresponds to the ``subtitle`` parameter of :class:`~rich.panel.Panel`. + """ + + title_align: Literal["left", "center", "right"] = "left" + """Alignment of the title text within the panel. + + Corresponds to the ``title_align`` parameter of :class:`~rich.panel.Panel`. + """ + + subtitle_align: Literal["left", "center", "right"] = "center" + """Alignment of the subtitle text within the panel. + + Corresponds to the ``subtitle_align`` parameter of :class:`~rich.panel.Panel`. + """ + + style: Optional["StyleType"] = "none" + """Style applied to the panel background. + + Corresponds to the ``style`` parameter of :class:`~rich.panel.Panel`. + """ + + border_style: Optional["StyleType"] = "none" + """Style applied to the panel border. + + Corresponds to the ``border_style`` parameter of :class:`~rich.panel.Panel`. + """ + + box: Optional["Box"] = None # Will use ROUNDED as default when building + """Box drawing style for the panel border. + + Corresponds to the ``box`` parameter of :class:`~rich.panel.Panel`. See :mod:`rich.box` for available styles. + Defaults to ``rich.box.ROUNDED``. + """ + + padding: "PaddingDimensions" = (0, 1) + """Padding inside the panel (top/bottom, left/right) or (top, right, bottom, left). + + Corresponds to the ``padding`` parameter of :class:`~rich.panel.Panel`. + """ + + expand: bool = True + """Whether the panel should expand to fill available width. + + Corresponds to the ``expand`` parameter of :class:`~rich.panel.Panel`. + """ + + width: int | None = None + """Fixed width for the panel in characters. + + Corresponds to the ``width`` parameter of :class:`~rich.panel.Panel`. + """ + + height: int | None = None + """Fixed height for the panel in lines. + + Corresponds to the ``height`` parameter of :class:`~rich.panel.Panel`. + """ + + safe_box: bool | None = None + """Whether to use ASCII-safe box characters for compatibility. + + Corresponds to the ``safe_box`` parameter of :class:`~rich.panel.Panel`. + """ + + highlight: bool = False + """Enable automatic highlighting of panel contents. + + Corresponds to the ``highlight`` parameter of :class:`~rich.panel.Panel`. + """ + + def build(self, renderable: "RenderableType", **overrides) -> "Panel": + """Create a Panel around `renderable`. Use kwargs to override spec per render.""" + # Import box here for lazy loading + box = self.box + if box is None: + from rich.box import ROUNDED + + box = ROUNDED + + opts = { + "title_align": self.title_align, + "subtitle_align": self.subtitle_align, + "style": self.style, + "border_style": self.border_style, + "box": box, + "padding": self.padding, + "expand": self.expand, + "width": self.width, + "height": self.height, + "safe_box": self.safe_box, + "highlight": self.highlight, + } + if self.title is not None: + opts["title"] = self.title + if self.subtitle is not None: + opts["subtitle"] = self.subtitle + + opts.update(overrides) + + from rich.panel import Panel + + return Panel(renderable, **opts) + + def copy(self, **kwargs): + return evolve(self, **kwargs) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/loader.py b/.venv/lib/python3.10/site-packages/cyclopts/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb1969bcb20b40e895078fe0d78c8fa3ea2d06d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/loader.py @@ -0,0 +1,150 @@ +"""Load Cyclopts App objects from Python scripts.""" + +import importlib.util +import sys +from contextlib import contextmanager +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from cyclopts import App + +from cyclopts.command_spec import CommandSpec + + +@contextmanager +def _suppress_app_execution(): + """Temporarily disable App.__call__ to prevent execution during module loading. + + This context manager replaces App.__call__ with a no-op function, allowing + scripts that call app() at module level to be imported without executing. + """ + from cyclopts import App + + original_call = App.__call__ + + def _dummy_call(self, *args, **kwargs): + """No-op replacement for App.__call__ during module loading.""" + return None + + try: + App.__call__ = _dummy_call + yield + finally: + App.__call__ = original_call + + +def load_app_from_script(script: str | Path) -> tuple["App", str]: + """Load a Cyclopts App object from a Python script. + + Parameters + ---------- + script : str | Path + Python script path, optionally with ``':app_object'`` notation to specify + the :class:`App` object. If not specified, will search for :class:`App` + objects in the script's global namespace. + + Returns + ------- + tuple[App, str] + The loaded :class:`App` object and its name. + + Raises + ------ + SystemExit + If the script cannot be loaded, no App objects are found, or multiple + App objects exist without specification. + """ + # Avoid circular import + from cyclopts import App + + # Parse the script path and optional app object + app_name = None + script_str = str(script) + if ":" in script_str: + # Split on the last colon + script_path_str, potential_app_name = script_str.rsplit(":", 1) + # Only treat it as an app name if it looks like a Python identifier + # (no path separators), otherwise it may be part of a Windows path like C:\path\to\file.py + if potential_app_name and not any(sep in potential_app_name for sep in ["/", "\\"]): + # Looks like an app name + app_name = potential_app_name + script_path = Path(script_path_str) + else: + # It's part of the path (e.g., Windows drive letter) + script_path = Path(script) + else: + script_path = Path(script) + + script_path = script_path.resolve() + + if not script_path.exists(): + print(f"Error: Script '{script_path}' not found.", file=sys.stderr) + sys.exit(1) + + if not script_path.suffix == ".py": + print(f"Error: '{script_path}' is not a Python file.", file=sys.stderr) + sys.exit(1) + + # Load the module + spec = importlib.util.spec_from_file_location("__cyclopts_doc_module", script_path) + if spec is None or spec.loader is None: + print(f"Error: Could not load module from '{script_path}'.", file=sys.stderr) + sys.exit(1) + + module = importlib.util.module_from_spec(spec) + sys.modules["__cyclopts_doc_module"] = module + + with _suppress_app_execution(): + spec.loader.exec_module(module) + + # Find the App object + if app_name: + # User specified the app object name + if not hasattr(module, app_name): + print(f"Error: No object named '{app_name}' found in '{script_path}'.", file=sys.stderr) + sys.exit(1) + app_obj = getattr(module, app_name) + if not isinstance(app_obj, App): + print(f"Error: '{app_name}' is not a Cyclopts App object.", file=sys.stderr) + sys.exit(1) + return app_obj, app_name + else: + # Heuristic: find App objects in the module's global namespace + app_objects = [] + for name in dir(module): + if not name.startswith("_"): # Skip private/protected names + obj = getattr(module, name) + if isinstance(obj, App): + app_objects.append((name, obj)) + + if not app_objects: + print(f"Error: No Cyclopts App objects found in '{script_path}'.", file=sys.stderr) + sys.exit(1) + + if len(app_objects) > 1: + # Filter out Apps that are registered as commands to other Apps + # Skip CommandSpec - those are lazy imports from other modules, not apps from this file + registered_apps = [] + for _, app in app_objects: + if hasattr(app, "_commands"): + # Only include direct App references; CommandSpec entries can't point to apps in this file + registered_apps.extend(cmd for cmd in app._commands.values() if not isinstance(cmd, CommandSpec)) + + # Keep only Apps that are not registered to others + filtered_apps = [(name, app) for name, app in app_objects if app not in registered_apps] + + if filtered_apps: + app_objects = filtered_apps + + if len(app_objects) > 1: + names = ", ".join(name for name, _ in app_objects) + script_str = str(script) if isinstance(script, Path) else script + print( + f"Error: Multiple App objects found: {names}. Please specify one using '{script_str}:app_name'.", + file=sys.stderr, + ) + sys.exit(1) + + name, app_obj = app_objects[0] + return app_obj, name diff --git a/.venv/lib/python3.10/site-packages/cyclopts/panel.py b/.venv/lib/python3.10/site-packages/cyclopts/panel.py new file mode 100644 index 0000000000000000000000000000000000000000..75e86f01a6b1d2ccec6d1ae2fd5d2ab6c6cba43b --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/panel.py @@ -0,0 +1,46 @@ +"""Cyclopts panel utilities for Rich-based terminal output.""" + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from rich.panel import Panel + + +def CycloptsPanel(message: Any, title: str = "Error", style: str = "red") -> "Panel": # noqa: N802 + """Create a :class:`~rich.panel.Panel` with a consistent style. + + The resulting panel can be displayed using a :class:`~rich.console.Console`. + + .. code-block:: text + + ╭─ Title ──────────────────────────────────╮ + │ Message content here. │ + ╰──────────────────────────────────────────╯ + + Parameters + ---------- + message: Any + The body of the panel will be filled with the stringified version of the message. + title: str + Title of the panel that appears in the top-left corner. + style: str + Rich `style `_ for the panel border. + + Returns + ------- + ~rich.panel.Panel + Formatted panel object. + """ + from rich import box + from rich.panel import Panel + from rich.text import Text + + panel = Panel( + Text(str(message), "default"), + title=title, + style=style, + box=box.ROUNDED, + expand=True, + title_align="left", + ) + return panel diff --git a/.venv/lib/python3.10/site-packages/cyclopts/parameter.py b/.venv/lib/python3.10/site-packages/cyclopts/parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ad20bb22b11fa54e26f65eb2edd05db5d95630 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/parameter.py @@ -0,0 +1,643 @@ +import collections.abc +import inspect +import re +import sys +from collections.abc import Callable, Iterable, Sequence +from copy import deepcopy +from typing import ( # noqa: UP035 + Any, + List, + Tuple, + TypeVar, + cast, + get_args, + get_origin, +) + +from attrs import define, field + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +import cyclopts._env_var +from cyclopts.annotations import ( + ITERABLE_TYPES, + NoneType, + is_annotated, + is_nonetype, + is_union, + resolve, + resolve_annotated, + resolve_optional, +) +from cyclopts.field_info import get_field_infos, signature_parameters +from cyclopts.group import Group +from cyclopts.utils import ( + default_name_transform, + frozen, + optional_to_tuple_converter, + record_init, + to_tuple_converter, +) + +ITERATIVE_BOOL_IMPLICIT_VALUE = frozenset( + { + Iterable[bool], + Sequence[bool], + collections.abc.Sequence[bool], + list[bool], + List[bool], # noqa: UP006 + tuple[bool, ...], + Tuple[bool, ...], # noqa: UP006 + } +) + + +T = TypeVar("T") + +_NEGATIVE_FLAG_TYPES = frozenset([bool, None, NoneType, *ITERABLE_TYPES, *ITERATIVE_BOOL_IMPLICIT_VALUE]) + + +def _not_hyphen_validator(instance, attribute, values): + for value in values: + if value is not None and value.startswith("-"): + raise ValueError(f'{attribute.alias} value must NOT start with "-".') + + +def _str_tuple_converter(value: str | Iterable[str] | None) -> tuple[str, ...]: + return cast(tuple[str, ...], to_tuple_converter(value)) + + +def _validator_tuple_converter( + value: Callable[[Any, Any], Any] | Iterable[Callable[[Any, Any], Any]] | None, +) -> tuple[Callable[[Any, Any], Any], ...]: + return cast(tuple[Callable[[Any, Any], Any], ...], to_tuple_converter(value)) + + +def _group_tuple_converter(value: "None | Group | str | Iterable[Group | str]") -> tuple["Group | str", ...]: + return cast(tuple["Group | str", ...], to_tuple_converter(value)) + + +def _optional_str_tuple_converter(value: bool | str | Iterable[str] | None) -> tuple[str, ...] | None: + return optional_to_tuple_converter(value) # type: ignore[return-value] + + +def _default_if_none_true(value: bool | None) -> bool: + return value if value is not None else True + + +def _default_if_none_false(value: bool | None) -> bool: + return value if value is not None else False + + +def _negative_converter(default: tuple[str, ...]): + def converter(value: str | Iterable[str] | None) -> tuple[str, ...]: + if value is None: + return default + else: + return to_tuple_converter(value) + + return converter + + +def _consume_multiple_converter( + value: bool | int | Sequence[int] | tuple[int, int | None] | None, +) -> tuple[int, int | None] | None: + """Normalize consume_multiple into (min, max) or None. + + Returns + ------- + tuple[int, int | None] | None + ``None`` if consume_multiple is disabled (``None`` or ``False``). + ``(min, max)`` where ``max=None`` means unlimited. + """ + if value is None or value is False: + return None + if value is True: + return (0, None) + if isinstance(value, int): + if value < 0: + raise ValueError(f"consume_multiple int value must be non-negative, got {value}.") + return (value, None) + if isinstance(value, Sequence): + if len(value) != 2: + raise ValueError(f"consume_multiple sequence must have exactly 2 elements (min, max), got {len(value)}.") + mn, mx = value + if mx is None: + # Already-normalized form (min, None); pass through. + return (mn, None) + if not isinstance(mn, int) or isinstance(mn, bool) or not isinstance(mx, int) or isinstance(mx, bool): + raise TypeError( + f"consume_multiple sequence elements must be int, got ({type(mn).__name__}, {type(mx).__name__})." + ) + if mn < 0 or mx < 0: + raise ValueError(f"consume_multiple sequence values must be non-negative, got ({mn}, {mx}).") + if mn > mx: + raise ValueError(f"consume_multiple min must be <= max, got ({mn}, {mx}).") + return (mn, mx) + raise TypeError(f"consume_multiple must be None, bool, int, or a (min, max) sequence, got {type(value).__name__}.") + + +def _parse_converter(value: bool | re.Pattern[str] | str | None) -> bool | re.Pattern[str] | None: + """Convert string patterns to compiled regex, pass through other types. + + Note: re.compile() internally caches compiled patterns, so no additional + caching is needed here. + """ + if isinstance(value, str): + return re.compile(value) + return value + + +@record_init("_provided_args") +@frozen +class Parameter: + """Cyclopts configuration for individual function parameters with :obj:`~typing.Annotated`. + + Example usage: + + .. code-block:: python + + from cyclopts import app, Parameter + from typing import Annotated + + app = App() + + + @app.default + def main(foo: Annotated[int, Parameter(name="bar")]): + print(foo) + + + app() + + .. code-block:: console + + $ my-script 100 + 100 + + $ my-script --bar 100 + 100 + """ + + # All attribute docstrings has been moved to ``docs/api.rst`` for greater control with attrs. + + # This can ONLY ever be a Tuple[str, ...] + # Usually starts with "--" or "-" + name: None | str | Iterable[str] = field( + default=None, + converter=_str_tuple_converter, + ) + + # Accepts regular converters (type, tokens) -> Any, bound methods (tokens) -> Any, or string references + converter: Callable[..., Any] | str | None = field( + default=None, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[Callable, ...] + validator: None | Callable[[Any, Any], Any] | Iterable[Callable[[Any, Any], Any]] = field( + default=(), + converter=_validator_tuple_converter, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[str, ...] + alias: None | str | Iterable[str] = field( + default=None, + converter=_str_tuple_converter, + kw_only=True, + ) + + # This can ONLY ever be ``None`` or ``Tuple[str, ...]`` + negative: None | str | Iterable[str] = field( + default=None, + converter=_optional_str_tuple_converter, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[Union[Group, str], ...] + group: None | Group | str | Iterable[Group | str] = field( + default=None, + converter=_group_tuple_converter, + kw_only=True, + hash=False, + ) + + parse: bool | re.Pattern | None = field( + default=None, + converter=_parse_converter, + kw_only=True, + ) + + _show: bool | None = field( + default=None, + alias="show", + kw_only=True, + ) + + show_default: None | bool | Callable[[Any], Any] = field( + default=None, + kw_only=True, + ) + + show_choices: bool = field( + default=None, + converter=_default_if_none_true, + kw_only=True, + ) + + help: str | None = field(default=None, kw_only=True) + + show_env_var: bool = field( + default=None, + converter=_default_if_none_true, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[str, ...] + env_var: None | str | Iterable[str] = field( + default=None, + converter=_str_tuple_converter, + kw_only=True, + ) + + env_var_split: Callable[..., Any] = field( + default=cyclopts._env_var.env_var_split, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[str, ...] + negative_bool: None | str | Iterable[str] = field( + default=None, + converter=_negative_converter(("no-",)), + validator=_not_hyphen_validator, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[str, ...] + negative_iterable: None | str | Iterable[str] = field( + default=None, + converter=_negative_converter(("empty-",)), + validator=_not_hyphen_validator, + kw_only=True, + ) + + # This can ONLY ever be a Tuple[str, ...] + negative_none: None | str | Iterable[str] = field( + default=None, + converter=_negative_converter(()), + validator=_not_hyphen_validator, + kw_only=True, + ) + + required: bool | None = field( + default=None, + kw_only=True, + ) + + allow_leading_hyphen: bool = field( + default=False, + kw_only=True, + ) + + requires_equals: bool = field( + default=False, + kw_only=True, + ) + + _name_transform: Callable[[str], str] | None = field( + alias="name_transform", + default=None, + kw_only=True, + ) + + accepts_keys: bool | None = field( + default=None, + kw_only=True, + ) + + consume_multiple: None | bool | int | Sequence[int] | tuple[int, int | None] = field( + default=None, + converter=_consume_multiple_converter, + kw_only=True, + ) + + json_dict: bool | None = field(default=None, kw_only=True) + + json_list: bool | None = field(default=None, kw_only=True) + + count: bool = field( + default=None, + converter=_default_if_none_false, + kw_only=True, + ) + + allow_repeating: bool | None = field( + default=None, + kw_only=True, + ) + + n_tokens: int | None = field( + default=None, + kw_only=True, + ) + + # Populated by the record_attrs_init_args decorator. + _provided_args: tuple[str, ...] = field(factory=tuple, init=False, eq=False) + + @property + def show(self) -> bool | None: + if self._show is not None: + return self._show + if self.parse is None or isinstance(self.parse, re.Pattern): + return None # For regex or None, let Argument.show handle it + return bool(self.parse) + + @property + def name_transform(self): + return self._name_transform if self._name_transform else default_name_transform + + def get_negatives(self, type_) -> tuple[str, ...]: + if self.count and self.negative is None: + return () + + type_ = resolve_annotated(type_) + if is_union(type_): + union_args = get_args(type_) + # Sort union members by priority: non-None types first, then None/NoneType + # This ensures that if bool | None both produce the same custom negative, + # we only include it once from the higher-priority type (bool). + sorted_args = sorted(union_args, key=lambda x: (is_nonetype(x) or x is None)) + out: list[str] = [] + for x in sorted_args: + for neg in self.get_negatives(x): + if neg not in out: + out.append(neg) + return tuple(out) + + origin = get_origin(type_) + + if type_ not in _NEGATIVE_FLAG_TYPES: + if origin: + if origin not in _NEGATIVE_FLAG_TYPES: + return () + else: + return () + + out, user_negatives = [], [] + if self.negative: + for negative in self.negative: + (out if negative.startswith("-") else user_negatives).append(negative) + + if not user_negatives: + return tuple(out) + + assert isinstance(self.name, tuple) + for name in self.name: + if not name.startswith("--"): # Only provide negation for option-like long flags. + continue + name = name[2:] + name_components = name.split(".") + + if type_ is bool or type_ in ITERATIVE_BOOL_IMPLICIT_VALUE: + negative_prefixes = self.negative_bool + elif is_nonetype(type_) or type_ is None: + negative_prefixes = self.negative_none + else: + negative_prefixes = self.negative_iterable + name_prefix = ".".join(name_components[:-1]) + if name_prefix: + name_prefix += "." + assert isinstance(negative_prefixes, tuple) + if self.negative is None: + for negative_prefix in negative_prefixes: + if negative_prefix: + out.append(f"--{name_prefix}{negative_prefix}{name_components[-1]}") + else: + for negative in user_negatives: + out.append(f"--{name_prefix}{negative}") + return tuple(out) + + def __repr__(self): + """Only shows non-default values.""" + content = ", ".join( + [ + f"{a.alias}={getattr(self, a.name)!r}" + for a in self.__attrs_attrs__ # pyright: ignore[reportAttributeAccessIssue] + if a.alias in self._provided_args + ] + ) + return f"{type(self).__name__}({content})" + + @classmethod + def combine(cls, *parameters: "Parameter | None") -> "Parameter": + """Returns a new Parameter with combined values of all provided ``parameters``. + + Parameters + ---------- + *parameters : Parameter | None + Parameters who's attributes override ``self`` attributes. + Ordered from least-to-highest attribute priority. + """ + kwargs = {} + filtered = [x for x in parameters if x is not None] + # In the common case of 0/1 parameters to combine, we can avoid + # instantiating a new Parameter object. + if len(filtered) == 1: + return filtered[0] + elif not filtered: + return EMPTY_PARAMETER + + for parameter in filtered: + for alias in parameter._provided_args: + kwargs[alias] = getattr(parameter, _parameter_alias_to_name[alias]) + + return cls(**kwargs) + + @classmethod + def default(cls) -> Self: + """Create a Parameter with all Cyclopts-default values. + + This is different than just :class:`Parameter` because the default + values will be recorded and override all upstream parameter values. + """ + return cls( + **{a.alias: a.default for a in cls.__attrs_attrs__ if a.init} # pyright: ignore[reportAttributeAccessIssue] + ) + + @classmethod + def from_annotation(cls, type_: Any, *default_parameters: "Parameter | None") -> tuple[Any, "Parameter"]: + """Resolve the immediate Parameter from a type hint.""" + if type_ is inspect.Parameter.empty: + if default_parameters: + return type_, cls.combine(*default_parameters) + else: + return type_, EMPTY_PARAMETER + else: + type_, parameters = get_parameters(type_) + return type_, cls.combine(*default_parameters, *parameters) + + def __call__(self, obj: T) -> T: + """Decorator interface for annotating a function/class with a :class:`Parameter`. + + Most commonly used for directly configuring a class: + + .. code-block:: python + + @Parameter(...) + class Foo: ... + """ + if not hasattr(obj, "__cyclopts__"): + obj.__cyclopts__ = CycloptsConfig(obj=obj) # pyright: ignore[reportAttributeAccessIssue] + elif obj.__cyclopts__.obj != obj: # pyright: ignore[reportAttributeAccessIssue] + # Create a copy so that children class Parameter decorators don't impact the parent. + obj.__cyclopts__ = deepcopy(obj.__cyclopts__) # pyright: ignore[reportAttributeAccessIssue] + obj.__cyclopts__.parameters.append(self) # pyright: ignore[reportAttributeAccessIssue] + return obj + + +_parameter_alias_to_name = { + p.alias: p.name + for p in Parameter.__attrs_attrs__ # pyright: ignore[reportAttributeAccessIssue] + if p.init +} + +EMPTY_PARAMETER = Parameter() + + +def validate_command(f: Callable): + """Validate if a function abides by Cyclopts's rules. + + Raises + ------ + ValueError + Function has naming or parameter/signature inconsistencies. + """ + if (f.__module__ or "").startswith("cyclopts"): # Speed optimization. + return + for field_info in signature_parameters(f).values(): + # Speed optimization: if no annotation and no cyclopts config, skip validation + field_info_is_annotated = is_annotated(field_info.annotation) + if not field_info_is_annotated and not getattr(field_info.annotation, "__cyclopts__", None): + # There is no annotation, so there is nothing to validate. + continue + + # Check both annotated parameters and classes with __cyclopts__ attribute + _, cparam = Parameter.from_annotation(field_info.annotation) + + if cparam.parse is not None and not isinstance(cparam.parse, re.Pattern) and not cparam.parse: + is_keyword_only = field_info.kind is field_info.KEYWORD_ONLY + has_default = field_info.default is not field_info.empty + if not (is_keyword_only or has_default): + raise ValueError( + "Parameter.parse=False must be used with either a KEYWORD_ONLY function parameter " + "or a parameter with a default value." + ) + + # Check for Parameter(name="*") without a default value when ALL class fields are optional + # This is confusing for CLI users who expect the dataclass to be instantiated automatically + if ( + "*" in cparam.name # pyright: ignore[reportOperatorIssue] + and field_info.default is field_info.empty + ): + # Get field info for the class to check if all fields have defaults + annotated = field_info.annotation + annotated = resolve(annotated) + class_field_infos = get_field_infos(annotated) + all_fields_optional = all(not field_info.required for field_info in class_field_infos.values()) + + if all_fields_optional: + param_name = field_info.names[0] if field_info.names else "" + quoted_param_name = f'"{param_name}" ' if param_name else "" + raise ValueError( + f'Parameter {quoted_param_name}in function {f} has all optional values, uses Parameter(name="*"), but itself has no default value. ' + "Consider either:\n" + f' 1) If immutable, providing a default value "{param_name}: {field_info.annotation.__name__} = {field_info.annotation.__name__}()"\n' + f' 2) Otherwise, declaring it optional like "{param_name}: {field_info.annotation.__name__} | None = None" and instanting the {param_name} object in the function body:\n' + f" if {param_name} is None:\n" + f" {param_name} = {field_info.annotation.__name__}()" + ) + + +def get_parameters(hint: T, skip_converter_params: bool = False) -> tuple[T, list[Parameter]]: + """At root level, checks for cyclopts.Parameter annotations. + + Includes checking the ``__cyclopts__`` attribute on both the type and any converter functions. + + Parameters + ---------- + hint + Type hint to extract parameters from. + skip_converter_params + If True, skip extracting parameters from converter's __cyclopts__. + Used to prevent infinite recursion in token_count. + + Returns + ------- + hint + Annotation hint with :obj:`Annotated` and :obj:`Optional` resolved. + list[Parameter] + List of parameters discovered, ordered by priority (lowest to highest): + converter-decoration < type-decoration < annotation. + """ + hint = resolve_optional(hint) + + # Extract parameters from Annotated metadata + annotated_params = [] + if is_annotated(hint): + inner = get_args(hint) + hint = inner[0] + annotated_params.extend(x for x in inner[1:] if isinstance(x, Parameter)) + # Resolve Optional again after unwrapping Annotated, since hint could be Type | None + hint = resolve_optional(hint) + + # Extract parameters from type's __cyclopts__ attribute (after unwrapping Annotated) + type_cyclopts_config_params = [] + if cyclopts_config := getattr(hint, "__cyclopts__", None): + type_cyclopts_config_params.extend(cyclopts_config.parameters) + + # Check if any parameter has a converter with __cyclopts__ and extract its parameters + converter_params = [] + if not skip_converter_params: + for param in annotated_params + type_cyclopts_config_params: + if param.converter: + converter = param.converter + + # Resolve string converters to methods on the type + if isinstance(converter, str): + converter = getattr(hint, converter) + + # Check for __cyclopts__ on the converter + if hasattr(converter, "__cyclopts__"): + converter_params.extend(converter.__cyclopts__.parameters) + break + # For bound methods from classmethods/staticmethods, access the descriptor via __self__ + elif ( + hasattr(converter, "__self__") + and hasattr(converter, "__name__") + and hasattr(converter.__self__, "__dict__") + ): + # Get the descriptor from the class's __dict__ + descriptor = converter.__self__.__dict__.get(converter.__name__) + if descriptor and hasattr(descriptor, "__cyclopts__"): + converter_params.extend(descriptor.__cyclopts__.parameters) + break + + # Return parameters in priority order (lowest to highest) + # This allows Parameter.combine() to correctly prioritize later parameters + parameters = converter_params + type_cyclopts_config_params + annotated_params + + return hint, parameters + + +@define +class CycloptsConfig: + """ + Intended for storing additional data to a ``__cyclopts__`` attribute via decoration. + """ + + obj: Any = None + parameters: list[Parameter] = field(factory=list, init=False) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/protocols.py b/.venv/lib/python3.10/site-packages/cyclopts/protocols.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf332766e6f3a2a597bf5281b340c7c617b2a98 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/protocols.py @@ -0,0 +1,9 @@ +import inspect +from collections.abc import Callable +from typing import Any, Protocol + + +class Dispatcher(Protocol): + def __call__( + self, command: Callable[..., Any], bound: inspect.BoundArguments, ignored: dict[str, Any], / + ) -> Any: ... diff --git a/.venv/lib/python3.10/site-packages/cyclopts/py.typed b/.venv/lib/python3.10/site-packages/cyclopts/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.10/site-packages/cyclopts/sphinx_ext.py b/.venv/lib/python3.10/site-packages/cyclopts/sphinx_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..97437416755a1bb2b2638691d63ca047af9f5126 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/sphinx_ext.py @@ -0,0 +1,33 @@ +"""Backward compatibility wrapper for Sphinx extension. + +This module maintains backward compatibility for users who have +``cyclopts.sphinx_ext`` in their Sphinx conf.py files. + +The actual implementation is in :mod:`cyclopts.ext.sphinx`. + +.. deprecated:: 4.0 + Use :mod:`cyclopts.ext.sphinx` instead. + This backward-compatibility location will be removed in v5. +""" + +import warnings + +warnings.warn( + "Importing from 'cyclopts.sphinx_ext' is deprecated. " + "Please update your Sphinx conf.py to use 'cyclopts.ext.sphinx' instead. " + "This compatibility shim will be removed in Cyclopts v5.", + DeprecationWarning, + stacklevel=2, +) + +from cyclopts.ext.sphinx import ( + CycloptsDirective, + DirectiveOptions, + setup, +) + +__all__ = [ + "CycloptsDirective", + "DirectiveOptions", + "setup", +] diff --git a/.venv/lib/python3.10/site-packages/cyclopts/token.py b/.venv/lib/python3.10/site-packages/cyclopts/token.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb7c01598b014d43e1cc5471148e0d91397964d --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/token.py @@ -0,0 +1,26 @@ +from typing import Any + +from attrs import evolve, field + +from cyclopts.utils import UNSET, frozen + + +@frozen(kw_only=True) +class Token: + """Tracks how a user supplied a value to the application.""" + + keyword: str | None = None + value: str = "" + source: str = "" + index: int = field(default=0, kw_only=True) + keys: tuple[str, ...] = field(default=(), kw_only=True) + implicit_value: Any = field(default=UNSET, kw_only=True) + + @property + def address(self) -> tuple[tuple[str, ...], int]: + """Hashable subkey destination address for this token.""" + return (self.keys, self.index) + + def evolve(self, **kwargs) -> "Token": + # TODO: replace return-hint with Self cp311 + return evolve(self, **kwargs) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/types.py b/.venv/lib/python3.10/site-packages/cyclopts/types.py new file mode 100644 index 0000000000000000000000000000000000000000..f49ec6c5534e757448892f34900287c66dbe04fd --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/types.py @@ -0,0 +1,374 @@ +import json +import sys +from collections.abc import Sequence +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Annotated, Any + +from cyclopts import validators +from cyclopts.parameter import Parameter + +if TYPE_CHECKING: + from cyclopts._path_type import StdioPath as StdioPath + from cyclopts.token import Token + +__all__ = [ + # Path + "StdioPath", + "ExistingPath", + "NonExistentPath", + "ExistingFile", + "NonExistentFile", + "ExistingDirectory", + "NonExistentDirectory", + "Directory", + "File", + "ResolvedExistingPath", + "ResolvedExistingFile", + "ResolvedExistingDirectory", + "ResolvedDirectory", + "ResolvedFile", + "ResolvedPath", + # Path with extensions + "BinPath", + "ExistingBinPath", + "NonExistentBinPath", + "CsvPath", + "ExistingCsvPath", + "NonExistentCsvPath", + "ImagePath", + "ExistingImagePath", + "NonExistentImagePath", + "JsonPath", + "ExistingJsonPath", + "NonExistentJsonPath", + "Mp4Path", + "ExistingMp4Path", + "NonExistentMp4Path", + "TomlPath", + "ExistingTomlPath", + "NonExistentTomlPath", + "TxtPath", + "ExistingTxtPath", + "NonExistentTxtPath", + "YamlPath", + "ExistingYamlPath", + "NonExistentYamlPath", + # Number + "PositiveFloat", + "NonNegativeFloat", + "NegativeFloat", + "NonPositiveFloat", + "PositiveInt", + "NonNegativeInt", + "NegativeInt", + "NonPositiveInt", + "UInt8", + "Int8", + "UInt16", + "Int16", + "UInt32", + "Int32", + "UInt64", + "Int64", + "HexUInt", + "HexUInt8", + "HexUInt16", + "HexUInt32", + "HexUInt64", + "NormFloat", + "SignedNormFloat", + "PercentInt", + # Json, + "Json", + # Web + "Email", + "Port", + "URL", +] + + +######## +# Path # +######## +def _path_resolve_converter(type_, tokens: Sequence["Token"]): + assert len(tokens) == 1 + return type_(tokens[0].value).resolve() + + +ExistingPath = Annotated[Path, Parameter(validator=validators.Path(exists=True))] +"A :class:`~pathlib.Path` file or directory that **must** exist." + +NonExistentPath = Annotated[Path, Parameter(validator=validators.Path(file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` file or directory that **must not** exist." + +ResolvedPath = Annotated[Path, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` file or directory. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." +ResolvedExistingPath = Annotated[ExistingPath, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` file or directory that **must** exist. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." + +Directory = Annotated[Path, Parameter(validator=validators.Path(file_okay=False))] +"A :class:`~pathlib.Path` that **must** be a directory (or not exist)." +ExistingDirectory = Annotated[Path, Parameter(validator=validators.Path(exists=True, file_okay=False))] +"A :class:`~pathlib.Path` directory that **must** exist." + +NonExistentDirectory = Annotated[Path, Parameter(validator=validators.Path(file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` directory that **must not** exist." +ResolvedDirectory = Annotated[Directory, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` directory. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." +ResolvedExistingDirectory = Annotated[ExistingDirectory, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` directory that **must** exist. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." + +File = Annotated[Path, Parameter(validator=validators.Path(dir_okay=False))] +"A :class:`~pathlib.File` that **must** be a file (or not exist)." +ExistingFile = Annotated[Path, Parameter(validator=validators.Path(exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` file that **must** exist." + +NonExistentFile = Annotated[Path, Parameter(validator=validators.Path(file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` file that **must not** exist." +ResolvedFile = Annotated[File, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` file. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." +ResolvedExistingFile = Annotated[ExistingFile, Parameter(converter=_path_resolve_converter)] +"A :class:`~pathlib.Path` file that **must** exist. :meth:`~pathlib.Path.resolve` is invoked prior to returning the path." + +# Common path extensions +BinPath = Annotated[Path, Parameter(validator=validators.Path(ext="bin", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``bin``." +ExistingBinPath = Annotated[Path, Parameter(validator=validators.Path(ext="bin", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``bin``." + +NonExistentBinPath = Annotated[Path, Parameter(validator=validators.Path(ext="bin", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``bin``." + +CsvPath = Annotated[Path, Parameter(validator=validators.Path(ext="csv", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``csv``." +ExistingCsvPath = Annotated[Path, Parameter(validator=validators.Path(ext="csv", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``csv``." + +NonExistentCsvPath = Annotated[Path, Parameter(validator=validators.Path(ext="csv", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``csv``." + +TxtPath = Annotated[Path, Parameter(validator=validators.Path(ext="txt", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``txt``." +ExistingTxtPath = Annotated[Path, Parameter(validator=validators.Path(ext="txt", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``txt``." + +NonExistentTxtPath = Annotated[Path, Parameter(validator=validators.Path(ext="txt", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``txt``." + +ImagePath = Annotated[Path, Parameter(validator=validators.Path(ext=("png", "jpg", "jpeg"), dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension in {``png``, ``jpg``, ``jpeg``}." +ExistingImagePath = Annotated[ + Path, Parameter(validator=validators.Path(ext=("png", "jpg", "jpeg"), exists=True, dir_okay=False)) +] +"A :class:`~pathlib.Path` that **must** exist and have extension in {``png``, ``jpg``, ``jpeg``}." + +NonExistentImagePath = Annotated[ + Path, Parameter(validator=validators.Path(ext=("png", "jpg", "jpeg"), file_okay=False, dir_okay=False)) +] +"A :class:`~pathlib.Path` that **must not** exist and have extension in {``png``, ``jpg``, ``jpeg``}." + +Mp4Path = Annotated[Path, Parameter(validator=validators.Path(ext="mp4", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``mp4``." +ExistingMp4Path = Annotated[Path, Parameter(validator=validators.Path(ext="mp4", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``mp4``." + +NonExistentMp4Path = Annotated[Path, Parameter(validator=validators.Path(ext="mp4", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``mp4``." + +JsonPath = Annotated[Path, Parameter(validator=validators.Path(ext="json", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``json``." +ExistingJsonPath = Annotated[Path, Parameter(validator=validators.Path(ext="json", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``json``." + +NonExistentJsonPath = Annotated[Path, Parameter(validator=validators.Path(ext="json", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``json``." + +TomlPath = Annotated[Path, Parameter(validator=validators.Path(ext="toml", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``toml``." +ExistingTomlPath = Annotated[Path, Parameter(validator=validators.Path(ext="toml", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``toml``." + +NonExistentTomlPath = Annotated[Path, Parameter(validator=validators.Path(ext="toml", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``toml``." + +YamlPath = Annotated[Path, Parameter(validator=validators.Path(ext="yaml", dir_okay=False))] +"A :class:`~pathlib.Path` that **must** have extension ``yaml``." +ExistingYamlPath = Annotated[Path, Parameter(validator=validators.Path(ext="yaml", exists=True, dir_okay=False))] +"A :class:`~pathlib.Path` that **must** exist and have extension ``yaml``." + +NonExistentYamlPath = Annotated[Path, Parameter(validator=validators.Path(ext="yaml", file_okay=False, dir_okay=False))] +"A :class:`~pathlib.Path` that **must not** exist and have extension ``yaml``." + + +########## +# Number # +########## +# foo +PositiveFloat = Annotated[float, Parameter(validator=validators.Number(gt=0))] +"A float that **must** be ``>0``." +NonNegativeFloat = Annotated[float, Parameter(validator=validators.Number(gte=0))] +"A float that **must** be ``>=0``." +NegativeFloat = Annotated[float, Parameter(validator=validators.Number(lt=0))] +"A float that **must** be ``<0``." +NonPositiveFloat = Annotated[float, Parameter(validator=validators.Number(lte=0))] +"A float that **must** be ``<=0``." + +PositiveInt = Annotated[int, Parameter(validator=validators.Number(gt=0))] +"An int that **must** be ``>0``." +NonNegativeInt = Annotated[int, Parameter(validator=validators.Number(gte=0))] +"An int that **must** be ``>=0``." +NegativeInt = Annotated[int, Parameter(validator=validators.Number(lt=0))] +"An int that **must** be ``<0``." +NonPositiveInt = Annotated[int, Parameter(validator=validators.Number(lte=0))] +"An int that **must** be ``<=0``." + +UInt8 = Annotated[int, Parameter(validator=validators.Number(gte=0, lte=255))] +"An unsigned 8-bit integer." +Int8 = Annotated[int, Parameter(validator=validators.Number(gte=-128, lte=127))] +"A signed 8-bit integer." + +UInt16 = Annotated[int, Parameter(validator=validators.Number(gte=0, lte=65535))] +"An unsigned 16-bit integer." +Int16 = Annotated[int, Parameter(validator=validators.Number(gte=-32768, lte=32767))] +"A signed 16-bit integer." + +UInt32 = Annotated[int, Parameter(validator=validators.Number(gte=0, lt=1 << 32))] +"An unsigned 32-bit integer." +Int32 = Annotated[int, Parameter(validator=validators.Number(gte=(-1 << 31), lt=(1 << 31)))] +"A signed 32-bit integer." + +UInt64 = Annotated[int, Parameter(validator=validators.Number(gte=0, lt=1 << 64))] +"An unsigned 64-bit integer." +Int64 = Annotated[int, Parameter(validator=validators.Number(gte=(-1 << 63), lt=(1 << 63)))] +"A signed 64-bit integer." + + +def _hex_formatter(value: int, digits=0) -> str: + return f"0x{value:X}" if digits <= 0 else f"0x{value:0{digits}X}" + + +HexUInt = Annotated[NonNegativeInt, Parameter(show_default=_hex_formatter)] +"A non-negative integer who's default value will be displayed as hexadecimal in the help-page." + +HexUInt8 = Annotated[UInt8, Parameter(show_default=partial(_hex_formatter, digits=2))] +"An unsigned 8-bit integer who's default value will be displayed as hexadecimal in the help-page." + +HexUInt16 = Annotated[UInt16, Parameter(show_default=partial(_hex_formatter, digits=4))] +"An unsigned 16-bit integer who's default value will be displayed as hexadecimal in the help-page." + +HexUInt32 = Annotated[UInt32, Parameter(show_default=partial(_hex_formatter, digits=8))] +"An unsigned 32-bit integer who's default value will be displayed as hexadecimal in the help-page." + +HexUInt64 = Annotated[UInt64, Parameter(show_default=partial(_hex_formatter, digits=16))] +"An unsigned 64-bit integer who's default value will be displayed as hexadecimal in the help-page." + +NormFloat = Annotated[float, Parameter(validator=validators.Number(gte=0, lte=1))] +"A float in the range ``[0, 1]``." + +SignedNormFloat = Annotated[float, Parameter(validator=validators.Number(gte=-1, lte=1))] +"A float in the range ``[-1, 1]``." + +PercentInt = Annotated[int, Parameter(validator=validators.Number(gte=0, lte=100))] +"An int in the range ``[0, 100]``." + + +######## +# Json # +######## +def _json_converter(type_, tokens: Sequence["Token"]): + assert len(tokens) == 1 + out = json.loads(tokens[0].value) + return out + + +Json = Annotated[Any, Parameter(converter=_json_converter)] +""" +Parse a json-string from the CLI. + +Note: Since Cyclopts v3.6.0, all dataclass-like classes now natively attempt +to parse json-strings, so practical use-case of this annotation is limited. + +Usage example: + +.. code-block:: python + + from cyclopts import App, types + + app = App() + + @app.default + def main(json: types.Json): + print(json) + + app() + +.. code-block:: console + + $ my-script '{"foo": 1, "bar": 2}' + {'foo': 1, 'bar': 2} +""" + +####### +# Web # +####### + + +def _email_validator(type_: Any, value: Any): + """Simplified email validation; probably good enough for CLI usage.""" + if not isinstance(value, str): + return + + if _email_validator.regex is None: # pyright: ignore[reportFunctionMemberAccess] + import re + + _email_validator.regex = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$") # pyright: ignore[reportFunctionMemberAccess] + + if not _email_validator.regex.match(value): # pyright: ignore[reportFunctionMemberAccess] + raise ValueError(f"Invalid email: {value}") + + +_email_validator.regex = None # pyright: ignore[reportFunctionMemberAccess] + +Email = Annotated[str, Parameter(validator=_email_validator)] +"An email address string with simple validation." + + +def _url_validator(type_: Any, value: Any): + """Simplified URL validation; probably good enough for CLI usage.""" + if not isinstance(value, str): + return + if _url_validator.regex is None: # pyright: ignore[reportFunctionMemberAccess] + import re + + _url_validator.regex = re.compile( # pyright: ignore[reportFunctionMemberAccess] + r"^(?:(?:https?|ftp):\/\/)?" # protocol + r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|" # domain + r"localhost|" # localhost + r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" # IP + r"(?::\d+)?" # port + r"(?:\/\S*)?$", # path, query string, fragment + re.IGNORECASE, + ) + + if not _url_validator.regex.match(value): # pyright: ignore[reportFunctionMemberAccess] + raise ValueError(f"Invalid URL: {value}") + + +_url_validator.regex = None # pyright: ignore[reportFunctionMemberAccess] + +URL = Annotated[str, Parameter(validator=_url_validator)] +"A :class:`str` URL string with some simple validation." + +Port = Annotated[int, Parameter(validator=validators.Number(gte=0, lte=65535))] +"An :class:`int` limited to range ``[0, 65535]``." + + +def __getattr__(name: str): + if name == "StdioPath": + if sys.version_info < (3, 12): + raise ImportError("StdioPath requires Python 3.12+ (Path subclassing support)") + from cyclopts._path_type import StdioPath + + return StdioPath + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/utils.py b/.venv/lib/python3.10/site-packages/cyclopts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2ff16c3751880f6adf121c30b22e1fa302491605 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/utils.py @@ -0,0 +1,529 @@ +"""To prevent circular dependencies, this module should never import anything else from Cyclopts.""" + +import functools +import importlib +import inspect +import re +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import suppress +from operator import itemgetter +from typing import TYPE_CHECKING, Any, Literal, TypeVar + +from attrs import field, frozen + +T = TypeVar("T") + +# https://threeofwands.com/attra-iv-zero-overhead-frozen-attrs-classes/ +if TYPE_CHECKING: + from json import JSONDecodeError + + from attrs import frozen + from rich.console import Console + + from cyclopts.help.protocols import HelpFormatter +else: + from attrs import define + + frozen = functools.partial(define, unsafe_hash=True) + +from sys import stdlib_module_names + + +class SentinelMeta(type): + def __repr__(cls) -> str: + return f"<{cls.__name__}>" + + def __bool__(cls) -> Literal[False]: + return False + + +class Sentinel(metaclass=SentinelMeta): + def __new__(cls): + raise ValueError("Sentinel objects are not intended to be instantiated. Subclass instead.") + + +class UNSET(Sentinel): + """Special sentinel value indicating that no data was provided. **Do not instantiate**.""" + + +def record_init(target: str) -> Callable[[type[T]], type[T]]: + """Class decorator that records init argument names as a tuple to ``target``.""" + + def decorator(cls: type[T]) -> type[T]: + original_init = cls.__init__ + function_signature = inspect.signature(original_init) + param_names = tuple(name for name in function_signature.parameters if name != "self") + + @functools.wraps(original_init) + def new_init(self, *args, **kwargs): + original_init(self, *args, **kwargs) + # Circumvent frozen protection. + object.__setattr__(self, target, tuple(param_names[i] for i in range(len(args))) + tuple(kwargs)) + + cls.__init__ = new_init + return cls + + return decorator + + +def is_iterable(obj) -> bool: + if isinstance(obj, list | tuple | set | dict): # Fast path for common types + return True + return not isinstance(obj, str) and isinstance(obj, Iterable) + + +def is_class_and_subclass(hint, target_class) -> bool: + """Safely check if a type is both a class and a subclass of target_class. + + Parameters + ---------- + hint : Any + The type to check. + target_class : type + The target class to check subclass relationship against. + + Returns + ------- + bool + True if hint is a class and is a subclass of target_class, False otherwise. + """ + try: + return inspect.isclass(hint) and issubclass(hint, target_class) + except TypeError: + # issubclass() raises TypeError for non-class arguments like Union types + return False + + +def to_tuple_converter(value: None | Any | Iterable[Any]) -> tuple[Any, ...]: + """Convert a single element or an iterable of elements into a tuple. + + Intended to be used in an ``attrs.Field``. If :obj:`None` is provided, returns an empty tuple. + If a single element is provided, returns a tuple containing just that element. + If an iterable is provided, converts it into a tuple. + + Parameters + ---------- + value: Any | Iterable[Any] | None + An element, an iterable of elements, or None. + + Returns + ------- + tuple[Any, ...]: A tuple containing the elements. + """ + if value is None: + return () + elif is_iterable(value): + return tuple(value) + else: + return (value,) + + +def to_list_converter(value: None | Any | Iterable[Any]) -> list[Any]: + return list(to_tuple_converter(value)) + + +def optional_to_tuple_converter(value: None | Any | Iterable[Any]) -> tuple[Any, ...] | None: + """Convert a string or Iterable or None into an Iterable or None. + + Intended to be used in an ``attrs.Field``. + """ + if value is None: + return None + + if not value: + return () + + return to_tuple_converter(value) + + +def sort_key_converter(value: Any) -> Any: + """Convert sort_key value, consuming generators with :func:`next`. + + Parameters + ---------- + value : Any + The sort_key value to convert. Can be None, a generator, or any other value. + + Returns + ------- + Any + UNSET if value is None, ``next(value)`` if generator, otherwise value unchanged. + """ + if value is None: + return UNSET + elif inspect.isgenerator(value): + return next(value) + else: + return value + + +def help_formatter_converter( + input_value: "None | Literal['default', 'plain'] | HelpFormatter", +) -> "HelpFormatter | None": + """Convert string literals to help formatter instances. + + Parameters + ---------- + input_value : None | Literal["default", "plain"] | Any + The input value to convert. Can be None, "default", "plain", or a formatter instance. + + Returns + ------- + Any | None + None, or a HelpFormatter instance. + + Notes + ----- + Lazily imports formatters to avoid importing Rich during normal execution. + """ + if input_value is None: + return None + elif isinstance(input_value, str): + if input_value == "default": + from cyclopts.help.formatters import DefaultFormatter + + return DefaultFormatter() + elif input_value == "plain": + from cyclopts.help.formatters import PlainFormatter + + return PlainFormatter() + else: + raise ValueError(f"Unknown formatter: {input_value!r}. Must be 'default' or 'plain'") + else: + # Assume it's already a HelpFormatter instance + return input_value + + +def _pascal_to_snake(s: str) -> str: + # (Borrowed from pydantic) + # Handle the sequence of uppercase letters followed by a lowercase letter + snake = re.sub(r"([A-Z]+)([A-Z][a-z])", lambda m: f"{m.group(1)}_{m.group(2)}", s) + # Insert an underscore between a lowercase letter and an uppercase letter + snake = re.sub(r"([a-z])([A-Z])", lambda m: f"{m.group(1)}_{m.group(2)}", snake) + # Insert an underscore between a digit and an uppercase letter + snake = re.sub(r"([0-9])([A-Z])", lambda m: f"{m.group(1)}_{m.group(2)}", snake) + return snake.lower() + + +def default_name_transform(s: str) -> str: + """Converts a python identifier into a CLI token. + + Performs the following operations (in order): + + 1. Convert PascalCase to snake_case. + 2. Convert the string to all lowercase. + 3. Replace ``_`` with ``-``. + 4. Strip any leading/trailing ``-`` (also stripping ``_``, due to point 3). + + Intended to be used with :attr:`App.name_transform` and :attr:`Parameter.name_transform`. + + Parameters + ---------- + s: str + Input python identifier string. + + Returns + ------- + str + Transformed name. + """ + return _pascal_to_snake(s).lower().replace("_", "-").strip("-") + + +def grouper(iterable: Sequence[Any], n: int) -> Iterator[tuple[Any, ...]]: + """Collect data into non-overlapping fixed-length chunks or blocks. + + https://docs.python.org/3/library/itertools.html#itertools-recipes + + Parameters + ---------- + iterable: Sequence[Any] + Some iterable sequence to group. + n: int + Number of elements to put in each group. + """ + if len(iterable) % n: + raise ValueError(f"{iterable!r} is not divisible by {n}.") + iterators = [iter(iterable)] * n + return zip(*iterators, strict=False) + + +def is_option_like(token: str, *, allow_numbers=False) -> bool: + """Checks if a token looks like an option. + + Namely, negative numbers are not options, but a token like ``--foo`` is. + + Parameters + ---------- + token: str + String to interpret. + allow_numbers: bool + If :obj:`True`, then negative numbers (e.g. ``"-2"``) will return :obj:`True`. + Otherwise, numbers will be interpreted as non-option-like (:obj:`False`). + Note: ``-j`` **is option-like**, even though it can represent an imaginary number. + + Returns + ------- + bool + Whether or not the ``token`` is option-like. + """ + if not allow_numbers: + with suppress(ValueError): + complex(token) + if token.lower() == "-j": + # ``complex("-j")`` is a valid imaginary number, but more than likely + # the caller meant it as a short flag. + # https://github.com/BrianPugh/cyclopts/issues/328 + return True + return False + return token.startswith("-") + + +def is_builtin(obj: Any) -> bool: + return getattr(obj, "__module__", "").split(".")[0] in stdlib_module_names + + +def resolve_callables(t, *args, **kwargs): + """Recursively resolves callable elements in a tuple. + + Returns an object that "looks like" the input, but with all callable's invoked + and replaced with their return values. Positional and keyword elements will be + passed along to each invocation. + """ + if isinstance(t, type(Sentinel)): + return t + + if callable(t): + return t(*args, **kwargs) + elif is_iterable(t): + resolved = [] + for element in t: + if isinstance(element, type(Sentinel)): + resolved.append(element) + elif callable(element): + resolved.append(element(*args, **kwargs)) + elif is_iterable(element): + resolved.append(resolve_callables(element, *args, **kwargs)) + else: + resolved.append(element) + return tuple(resolved) + else: + return t + + +@frozen +class SortHelper: + """Sort a list of objects by an external key and retrieve the objects in-order.""" + + key: Any + """Primary key to sort by. + + SortHelpers with ``key`` :obj:`None` or :obj:`.UNSET` go last (alphabetically). + """ + + fallback_key: Any = field(converter=to_tuple_converter) + """Secondary key to sort by. + """ + + value: Any + """Actual object that caller wants to retrieve in the sorted order.""" + + @staticmethod + def sort(entries: Sequence["SortHelper"]) -> list["SortHelper"]: + """Sorts a sequence of :class:`SortHelper`.""" + from cyclopts.group import ( + DEFAULT_ARGUMENTS_GROUP_SORT_MARKER, + DEFAULT_COMMANDS_GROUP_SORT_MARKER, + DEFAULT_PARAMETERS_GROUP_SORT_MARKER, + ) + + default_commands_group = [] + default_arguments_group = [] + default_parameters_group = [] + + user_sort_key = [] + ordered_no_user_sort_key = [] + no_user_sort_key = [] + + for entry in entries: + if entry.key is DEFAULT_COMMANDS_GROUP_SORT_MARKER: + default_commands_group.append((None, entry)) + elif entry.key is DEFAULT_ARGUMENTS_GROUP_SORT_MARKER: + default_arguments_group.append((None, entry)) + elif entry.key is DEFAULT_PARAMETERS_GROUP_SORT_MARKER: + default_parameters_group.append((None, entry)) + elif entry.key in (UNSET, None): + no_user_sort_key.append((entry.fallback_key, entry)) + elif is_iterable(entry.key) and entry.key[0] in (UNSET, None): + # Items that are ordered internal to Cyclopts, but have lower order than user-provided sort_keys. + # Primarily to handle :meth:`Group.create_ordered`. + ordered_no_user_sort_key.append((entry.key[1:] + entry.fallback_key, entry)) + else: + user_sort_key.append(((entry.key, entry.fallback_key), entry)) + + user_sort_key.sort(key=itemgetter(0)) + ordered_no_user_sort_key.sort(key=itemgetter(0)) + no_user_sort_key.sort(key=itemgetter(0)) + + combined = ( + default_commands_group + + default_arguments_group + + default_parameters_group + + user_sort_key + + ordered_no_user_sort_key + + no_user_sort_key + ) + return [x[1] for x in combined] + + +def json_decode_error_verbosifier(decode_error: "JSONDecodeError", context: int = 20) -> str: + """Not intended to be a super robust implementation, but robust enough to be helpful. + + Parameters + ---------- + context: int + Number of surrounding-character context + """ + lines = decode_error.doc.splitlines() + line = lines[decode_error.lineno - 1] + + error_index = decode_error.colno - 1 # colno is 1-indexed + start = error_index - context + if start <= 0: + start = 0 + prefix_ellipsis = "" + segment_error_index = error_index + else: + prefix_ellipsis = "... " + segment_error_index = error_index - start + + end = error_index + context + if end >= len(line): + end = len(line) + 1 + suffix_ellipsis = "" + else: + suffix_ellipsis = " ..." + + segment = line[start:end] + carat_pointer = " " * (len(prefix_ellipsis) + segment_error_index) + "^" + + response = ( + f"JSONDecodeError:\n {prefix_ellipsis}{segment}{suffix_ellipsis}\n {carat_pointer}\n{str(decode_error)}" + ) + return response + + +def create_error_console_from_console(console: "Console") -> "Console": + """Create an error console (stderr=True) that inherits settings from a source console. + + Parameters + ---------- + console : Console + Source Rich Console to copy settings from. + + Returns + ------- + Console + New Rich Console with stderr=True and inherited settings. + """ + from rich.console import Console + + color_system = console.color_system or "auto" + + return Console( + stderr=True, + color_system=color_system, # type: ignore[arg-type] + force_terminal=getattr(console, "_force_terminal", None), + force_jupyter=console.is_jupyter or None, + force_interactive=console.is_interactive or None, + soft_wrap=console.soft_wrap, + width=console._width, + height=getattr(console, "_height", None), + tab_size=console.tab_size, + markup=getattr(console, "_markup", True), + emoji=getattr(console, "_emoji", True), + emoji_variant=getattr(console, "_emoji_variant", None), + highlight=getattr(console, "_highlight", True), + no_color=console.no_color, + legacy_windows=console.legacy_windows, + safe_box=console.safe_box, + _environ=getattr(console, "_environ", None), + get_datetime=getattr(console, "get_datetime", None), + get_time=getattr(console, "get_time", None), + ) + + +def parse_version(version_string: str) -> tuple[int, ...]: + """Parse a PEP 440 version string into a tuple of ints, stripping pre-release suffixes. + + Parameters + ---------- + version_string: str + A version string like ``"2.11.2"`` or ``"2.0.0b2"``. + + Returns + ------- + tuple[int, ...] + Tuple of the numeric components, e.g. ``(2, 11, 2)`` or ``(2, 0, 0)``. + """ + return tuple(int(m.group()) for x in version_string.split(".") if (m := re.match(r"\d+", x))) + + +def import_app(module_path: str): + """Import a Cyclopts App from a module path. + + Parameters + ---------- + module_path : str + Module path in format "module.name" or "module.name:app_name". + If ":app_name" is omitted, auto-discovers by searching for common + names (app, cli, main) or any public App instance. + + Returns + ------- + App + The imported Cyclopts App instance. + + Raises + ------ + ImportError + If the module cannot be imported. + AttributeError + If the specified app name doesn't exist or no App is found. + TypeError + If the specified attribute is not a Cyclopts App instance. + """ + from cyclopts import App + + if ":" in module_path: + module_name, app_name = module_path.rsplit(":", 1) + else: + module_name, app_name = module_path, None + + try: + module = importlib.import_module(module_name) + except ImportError as e: + raise ImportError(f"Cannot import module '{module_name}': {e}") from e + + if app_name: + if not hasattr(module, app_name): + raise AttributeError(f"Module '{module_name}' has no attribute '{app_name}'") + app = getattr(module, app_name) + if not isinstance(app, App): + raise TypeError(f"'{app_name}' is not a Cyclopts App instance") + return app + + # Auto-discovery: search for App instance + for name in ["app", "cli", "main"]: + obj = getattr(module, name, None) + if isinstance(obj, App): + return obj + + # Search all public attributes + for name in dir(module): + if not name.startswith("_"): + obj = getattr(module, name) + if isinstance(obj, App): + return obj + + raise AttributeError(f"No Cyclopts App found in '{module_name}'. Specify explicitly: '{module_name}:app_name'") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/validators/__init__.py b/.venv/lib/python3.10/site-packages/cyclopts/validators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..74f4193587f38dfd3f08c8966f352dc9b9e5b0f4 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/validators/__init__.py @@ -0,0 +1,12 @@ +__all__ = [ + "all_or_none", + "LimitedChoice", + "MutuallyExclusive", + "mutually_exclusive", + "Number", + "Path", +] + +from cyclopts.validators._group import LimitedChoice, MutuallyExclusive, all_or_none, mutually_exclusive +from cyclopts.validators._number import Number +from cyclopts.validators._path import Path diff --git a/.venv/lib/python3.10/site-packages/cyclopts/validators/_group.py b/.venv/lib/python3.10/site-packages/cyclopts/validators/_group.py new file mode 100644 index 0000000000000000000000000000000000000000..e71b2d3615a65864af250ed86de523e6a38da8c5 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/validators/_group.py @@ -0,0 +1,83 @@ +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from cyclopts.argument import ArgumentCollection + + +class LimitedChoice: + def __init__( + self, + min: int = 0, + max: int | None = None, + allow_none: bool = False, + ): + """Group validator that limits the number of selections per group. + + Commonly used for enforcing mutually-exclusive parameters (default behavior). + + Parameters + ---------- + min: int + The minimum (inclusive) number of CLI parameters allowed. + If negative, then **all** parameters in the group must have CLI values provided. + max: int | None + The maximum (inclusive) number of CLI parameters allowed. + Defaults to ``1`` if ``min==0``, ``min`` otherwise. + allow_none: bool + If :obj:`True`, also allow 0 CLI parameters (even if ``min`` is greater than 0). + Defaults to :obj:`False`. + """ + self.min = min + self.max = (self.min or 1) if max is None else max + if self.max < self.min: + raise ValueError("max must be >=min.") + self.allow_none = allow_none + + def __call__(self, argument_collection: "ArgumentCollection"): + group_size = len(argument_collection) + populated_argument_collection = argument_collection.filter_by(value_set=True) + n_arguments = len(populated_argument_collection) + + if self.allow_none and n_arguments == 0: + return + elif self.min < 0: + # Require all arguments in the group to be supplied. + if group_size == n_arguments: + return + all_names = {a.name for a in argument_collection} + supplied_names = {a.name for a in populated_argument_collection} + missing_names = sorted(all_names - supplied_names) + if len(missing_names) == 1: + raise ValueError(f"Missing argument: {missing_names[0]}") + else: + raise ValueError(f"Missing arguments: {missing_names}") + elif self.min <= n_arguments <= self.max: + return + else: + offenders = ( + "{" + + ", ".join( + a.tokens[0].keyword if (a.tokens and a.tokens[0].keyword) else a.name + for a in populated_argument_collection + ) + + "}" + ) + if self.min == 0 and self.max == 1: + raise ValueError(f"Mutually exclusive arguments: {offenders}") + else: + raise ValueError( + f"Received {n_arguments} arguments: {offenders}. Only [{self.min}, {self.max}] choices may be specified." + ) + + +class MutuallyExclusive(LimitedChoice): + def __init__(self): + """Alias for :class:`LimitedChoice` to make intentions more obvious. + + Only 1 argument in the group can be supplied a value. + """ + super().__init__() + + +mutually_exclusive = MutuallyExclusive() +all_or_none = LimitedChoice(-1, allow_none=True) diff --git a/.venv/lib/python3.10/site-packages/cyclopts/validators/_number.py b/.venv/lib/python3.10/site-packages/cyclopts/validators/_number.py new file mode 100644 index 0000000000000000000000000000000000000000..c9dc0eb9fe982617cb2bced6cb7ae2fa15a5a3fb --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/validators/_number.py @@ -0,0 +1,82 @@ +from collections.abc import Sequence +from typing import Any + +from cyclopts.utils import frozen + + +@frozen(kw_only=True) +class Number: + """Limit input number to a value range. + + Example Usage: + + .. code-block:: python + + from cyclopts import App, Parameter, validators + from typing import Annotated + + app = App() + + + @app.default + def main(age: Annotated[int, Parameter(validator=validators.Number(gte=0, lte=150))]): + print(f"You are {age} years old.") + + + app() + + .. code-block:: console + + $ my-script 100 + You are 100 years old. + + $ my-script -1 + ╭─ Error ───────────────────────────────────────────────────────╮ + │ Invalid value "-1" for "AGE". Must be >= 0. │ + ╰───────────────────────────────────────────────────────────────╯ + + $ my-script 200 + ╭─ Error ───────────────────────────────────────────────────────╮ + │ Invalid value "200" for "AGE". Must be <= 150. │ + ╰───────────────────────────────────────────────────────────────╯ + """ + + lt: int | float | None = None + """Input value must be **less than** this value.""" + + lte: int | float | None = None + """Input value must be **less than or equal** this value.""" + + gt: int | float | None = None + """Input value must be **greater than** this value.""" + + gte: int | float | None = None + """Input value must be **greater than or equal** this value.""" + + modulo: int | float | None = None + """Input value must be a multiple of this value.""" + + def __call__(self, type_: Any, value: Any): + if isinstance(value, Sequence): + if isinstance(value, str): + raise TypeError + for v in value: + self(type_, v) + else: + if not isinstance(value, int | float): + return + + if self.lt is not None and value >= self.lt: + raise ValueError(f"Must be < {self.lt}.") + + if self.lte is not None and value > self.lte: + raise ValueError(f"Must be <= {self.lte}.") + + if self.gt is not None and value <= self.gt: + raise ValueError(f"Must be > {self.gt}.") + + if self.gte is not None and value < self.gte: + raise ValueError(f"Must be >= {self.gte}.") + + if self.modulo is not None and value % self.modulo: + raise ValueError(f"Must be a multiple of {self.modulo}.") diff --git a/.venv/lib/python3.10/site-packages/cyclopts/validators/_path.py b/.venv/lib/python3.10/site-packages/cyclopts/validators/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..1b99022c1dc7e0a8f774471b556f3fac8f0cdc67 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/cyclopts/validators/_path.py @@ -0,0 +1,122 @@ +import pathlib +from collections.abc import Iterable, Sequence +from typing import Any + +from attrs import field + +from cyclopts.utils import frozen, to_tuple_converter + + +def ext_converter(value: str | Iterable[str] | None) -> tuple[str, ...]: + return tuple(e.lower().lstrip(".") for e in to_tuple_converter(value)) + + +@frozen(kw_only=True) +class Path: + """Assertions on properties of :class:`pathlib.Path`. + + Example Usage: + + .. code-block:: python + + from cyclopts import App, Parameter, validators + from pathlib import Path + from typing import Annotated + + app = App() + + + @app.default + def main( + # ``src`` must be a file that exists. + src: Annotated[Path, Parameter(validator=validators.Path(exists=True, dir_okay=False))], + # ``dst`` must be a path that does **not** exist. + dst: Annotated[Path, Parameter(validator=validators.Path(dir_okay=False, file_okay=False))], + ): + "Copies src->dst." + dst.write_bytes(src.read_bytes()) + + + app() + + .. code-block:: console + + $ my-script foo.bin bar.bin # if foo.bin does not exist + ╭─ Error ───────────────────────────────────────────────────────╮ + │ Invalid value "foo.bin" for "SRC". "foo.bin" does not exist. │ + ╰───────────────────────────────────────────────────────────────╯ + + $ my-script foo.bin bar.bin # if bar.bin exists + ╭─ Error ───────────────────────────────────────────────────────╮ + │ Invalid value "bar.bin" for "DST". "bar.bin" already exists. │ + ╰───────────────────────────────────────────────────────────────╯ + """ + + exists: bool = False + """If :obj:`True`, specified path **must** exist. Defaults to :obj:`False`.""" + + file_okay: bool = True + """ + If path exists, check it's type: + + * If :obj:`True`, specified path may be an **existing** file. + + * If :obj:`False`, then **existing** files are not allowed. + + Defaults to :obj:`True`. + """ + + dir_okay: bool = True + """ + If path exists, check it's type: + + * If :obj:`True`, specified path may be an **existing** directory. + + * If :obj:`False`, then **existing** directories are not allowed. + + Defaults to :obj:`True`. + """ + + # Can only ever really be a tuple[str, ...] + ext: str | Sequence[str] = field(default=None, converter=ext_converter) + """ + Supplied path must have this extension (case insensitive). + May or may not include the ".". + """ + + def __attrs_post_init__(self): + if self.exists and not self.file_okay and not self.dir_okay: + raise ValueError("(exists=True, file_okay=False, dir_okay=False) is an invalid configuration.") + + def __call__(self, type_: Any, path: Any): + if isinstance(path, Sequence): + if isinstance(path, str): + raise TypeError + + for p in path: + self(type_, p) + else: + if not isinstance(path, pathlib.Path): + return + + if self.ext and path.suffix.lower().lstrip(".") not in self.ext: + if len(self.ext) == 1: + raise ValueError(f'"{path}" must have extension "{self.ext[0]}".') + else: + pretty_ext = "{" + ", ".join(f'"{x}"' for x in self.ext) + "}" + raise ValueError(f'"{path}" does not match one of supported extensions {pretty_ext}.') + + if path.exists(): + if not self.file_okay and path.is_file(): + if self.dir_okay: + raise ValueError(f'Only directory is allowed, but "{path}" is a file.') + else: + raise ValueError(f'"{path}" already exists.') + + if not self.dir_okay and path.is_dir(): + if self.file_okay: + raise ValueError(f'Only file is allowed, but "{path}" is a directory.') + else: + raise ValueError(f'"{path}" already exists.') + elif self.exists: + raise ValueError(f'"{path}" does not exist.') diff --git a/.venv/lib/python3.10/site-packages/docutils/__init__.py b/.venv/lib/python3.10/site-packages/docutils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e27f1266d3be25d13a69639472d0ff5cb6d70701 --- /dev/null +++ b/.venv/lib/python3.10/site-packages/docutils/__init__.py @@ -0,0 +1,341 @@ +# $Id: __init__.py 10275 2025-12-18 18:44:54Z grubert $ +# Author: David Goodger +# Copyright: This module has been placed in the public domain. + +""" +This is the Docutils (Python Documentation Utilities) package. + +Package Structure +================= + +Modules: + +- __init__.py: Contains component base classes, exception classes, and + Docutils version information. + +- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience + functions. + +- frontend.py: Runtime settings (command-line interface, configuration files) + processing, for Docutils front-ends. + +- io.py: Provides a uniform API for low-level input and output. + +- nodes.py: Docutils document tree (doctree) node class library. + +- statemachine.py: A finite state machine specialized for + regular-expression-based text filters. + +Subpackages: + +- languages: Language-specific mappings of terms. + +- parsers: Syntax-specific input parser modules or packages. + +- readers: Context-specific input handlers which understand the data + source and manage a parser. + +- transforms: Modules used by readers and writers to modify + the Docutils document tree. + +- utils: Contains the ``Reporter`` system warning class and miscellaneous + utilities used by readers, writers, and transforms. + + utils/urischemes.py: Contains a complete mapping of known URI addressing + scheme names to descriptions. + +- utils/math: Contains functions for conversion of mathematical notation + between different formats (LaTeX, MathML, text, ...). + +- writers: Format-specific output translators. +""" + +from __future__ import annotations + +from collections import namedtuple + +TYPE_CHECKING = False +if TYPE_CHECKING: + from collections.abc import Sequence + from typing import Any, ClassVar, Literal, Protocol, Union + + from docutils.nodes import Element + from docutils.transforms import Transform + + _Components = Literal['reader', 'parser', 'writer', 'input', 'output'] + _OptionTuple = tuple[str, list[str], dict[str, Any]] + _ReleaseLevels = Literal['alpha', 'beta', 'candidate', 'final'] + _SettingsSpecTuple = Union[ + tuple[str|None, str|None, Sequence[_OptionTuple]], + tuple[str|None, str|None, Sequence[_OptionTuple], + str|None, str|None, Sequence[_OptionTuple]], + tuple[str|None, str|None, Sequence[_OptionTuple], + str|None, str|None, Sequence[_OptionTuple], + str|None, str|None, Sequence[_OptionTuple]], + ] + + class _UnknownReferenceResolver(Protocol): + """Deprecated. Will be removed in Docutils 1.0.""" + # See `TransformSpec.unknown_reference_resolvers`. + + priority: int + + def __call__(self, node: Element, /) -> bool: + ... + +__docformat__ = 'reStructuredText' + +__version__ = '0.22.4' +"""Docutils version identifier (complies with PEP 440):: + + major.minor[.micro][releaselevel[serial]][.dev] + +For version comparison operations, use `__version_info__` (see, below) +rather than parsing the text of `__version__`. + +https://docutils.sourceforge.io/docs/dev/policies.html#version-identification +""" + +__version_details__ = '' +"""Optional extra version details (e.g. 'snapshot 2005-05-29, r3410'). + +For development and release status, use `__version__ and `__version_info__`. +""" + + +class VersionInfo(namedtuple('VersionInfo', + 'major minor micro releaselevel serial release')): + __slots__ = () + + major: int + minor: int + micro: int + releaselevel: _ReleaseLevels + serial: int + release: bool + + def __new__(cls, + major: int = 0, minor: int = 0, micro: int = 0, + releaselevel: _ReleaseLevels = 'final', + serial: int = 0, release: bool = True, + ) -> VersionInfo: + releaselevels = ('alpha', 'beta', 'candidate', 'final') + if releaselevel not in releaselevels: + raise ValueError('releaselevel must be one of %r.' + % (releaselevels, )) + if releaselevel == 'final': + if not release: + raise ValueError('releaselevel "final" must not be used ' + 'with development versions (leads to wrong ' + 'version ordering of the related __version__') + # cf. https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering # NoQA: E501 + if serial != 0: + raise ValueError('"serial" must be 0 for final releases') + + return super().__new__(cls, major, minor, micro, + releaselevel, serial, release) + + def __lt__(self, other: object) -> bool: + if isinstance(other, tuple): + other = VersionInfo(*other) + return tuple.__lt__(self, other) + + def __gt__(self, other: object) -> bool: + if isinstance(other, tuple): + other = VersionInfo(*other) + return tuple.__gt__(self, other) + + def __le__(self, other: object) -> bool: + if isinstance(other, tuple): + other = VersionInfo(*other) + return tuple.__le__(self, other) + + def __ge__(self, other: object) -> bool: + if isinstance(other, tuple): + other = VersionInfo(*other) + return tuple.__ge__(self, other) + + +__version_info__ = VersionInfo( + major=0, + minor=22, + micro=4, + releaselevel='final', # one of 'alpha', 'beta', 'candidate', 'final' + serial=0, # pre-release number (0 for final releases and snapshots) + release=True # True for official releases and pre-releases + ) +"""Comprehensive version information tuple. + +https://docutils.sourceforge.io/docs/dev/policies.html#version-identification +""" + + +class ApplicationError(Exception): pass +class DataError(ApplicationError): pass + + +class SettingsSpec: + + """ + Runtime setting specification base class. + + SettingsSpec subclass objects used by `docutils.frontend.OptionParser`. + """ + + # TODO: replace settings_specs with a new data structure + # Backwards compatiblity: + # Drop-in components: + # Sphinx supplies settings_spec in the current format in some places + # Myst parser provides a settings_spec tuple + # + # Sphinx reads a settings_spec in order to set a default value + # in writers/html.py:59 + # https://github.com/sphinx-doc/sphinx/blob/4.x/sphinx/writers/html.py + # This should be changed (before retiring the old format) + # to use `settings_default_overrides` instead. + settings_spec: ClassVar[_SettingsSpecTuple] = () + """Runtime settings specification. Override in subclasses. + + Defines runtime settings and associated command-line options, as used by + `docutils.frontend.OptionParser`. This is a tuple of: + + - Option group title (string or `None` which implies no group, just a list + of single options). + + - Description (string or `None`). + + - A sequence of option tuples. Each consists of: + + - Help text (string) + + - List of option strings (e.g. ``['-Q', '--quux']``). + + - Dictionary of keyword arguments sent to the OptionParser/OptionGroup + ``add_option`` method. + + Runtime setting names are derived implicitly from long option names + ('--a-setting' becomes ``settings.a_setting``) or explicitly from the + 'dest' keyword argument. + + Most settings will also have a 'validator' keyword & function. The + validator function validates setting values (from configuration files + and command-line option arguments) and converts them to appropriate + types. For example, the ``docutils.frontend.validate_boolean`` + function, **required by all boolean settings**, converts true values + ('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off', + 'no', 'false', and '') to 0. Validators need only be set once per + setting. See the `docutils.frontend.validate_*` functions. + + See the optparse docs for more details. + + - More triples of group title, description, options, as many times as + needed. Thus, `settings_spec` tuples can be simply concatenated. + """ + + settings_defaults: ClassVar[dict[str, Any] | None] = None + """A dictionary of defaults for settings not in `settings_spec` (internal + settings, intended to be inaccessible by command-line and config file). + Override in subclasses.""" + + settings_default_overrides: ClassVar[dict[str, Any] | None] = None + """A dictionary of auxiliary defaults, to override defaults for settings + defined in other components' `setting_specs`. Override in subclasses.""" + + relative_path_settings: ClassVar[tuple[str, ...]] = () + """Settings containing filesystem paths. Override in subclasses. + Settings listed here are to be interpreted relative to the current working + directory.""" + + config_section: ClassVar[str | None] = None + """The name of the config file section specific to this component + (lowercase, no brackets). Override in subclasses.""" + + config_section_dependencies: ClassVar[tuple[str, ...] | None] = None + """A list of names of config file sections that are to be applied before + `config_section`, in order (from general to specific). In other words, + the settings in `config_section` are to be overlaid on top of the settings + from these sections. The "general" section is assumed implicitly. + Override in subclasses.""" + + +class TransformSpec: + """ + Runtime transform specification base class. + + Provides the interface to register "transforms" and helper functions + to resolve references with a `docutils.transforms.Transformer`. + + https://docutils.sourceforge.io/docs/ref/transforms.html + """ + + def get_transforms(self) -> list[type[Transform]]: + """Transforms required by this class. Override in subclasses.""" + if self.default_transforms != (): + import warnings + warnings.warn('TransformSpec: the "default_transforms" attribute ' + 'will be removed in Docutils 2.0.\n' + 'Use get_transforms() method instead.', + DeprecationWarning) + return list(self.default_transforms) + return [] + + # Deprecated; for compatibility. + default_transforms: ClassVar[tuple[()]] = () + + unknown_reference_resolvers: Sequence[_UnknownReferenceResolver] = () + """List of hook functions which assist in resolving references. + + Deprecated. Will be removed in Docutils 1.0 + """ + # Override in subclasses to implement component-specific resolving of + # unknown references. + # + # Unknown references have a 'refname' attribute which doesn't correspond + # to any target in the document. Called when the transforms in + # `docutils.transforms.references` are unable to find a correct target. + # + # The list should contain functions which will try to resolve unknown + # references, with the following signature:: + # + # def reference_resolver(node: nodes.Element) -> bool: + # '''Returns boolean: true if resolved, false if not.''' + # + # If the function is able to resolve the reference, it should also remove + # the 'refname' attribute and mark the node as resolved:: + # + # del node['refname'] + # node.resolved = True + # + # Each function must have a "priority" attribute which will affect the + # order the unknown_reference_resolvers are run + # cf. ../docs/api/transforms.html#transform-priority-range-categories :: + # + # reference_resolver.priority = 500 + # + # Examples: + # The `MoinMoin ReStructured Text Parser`__ provided a resolver for + # "WikiWiki links" in the 1.9 version. + # + # __ https://github.com/moinwiki/moin-1.9/blob/1.9.11/MoinMoin/parser/ + # text_rst.py + + +class Component(SettingsSpec, TransformSpec): + + """Base class for Docutils components.""" + + component_type: ClassVar[_Components | None] = None + """Name of the component type ('reader', 'parser', 'writer'). + Override in subclasses.""" + + supported: ClassVar[tuple[str, ...]] = () + """Name and aliases for this component. Override in subclasses.""" + + def supports(self, format: str) -> bool: + """ + Is `format` supported by this component? + + To be used by transforms to ask the dependent component if it supports + a certain input context or output format. + """ + return format in self.supported diff --git a/.venv/lib/python3.10/site-packages/docutils/__main__.py b/.venv/lib/python3.10/site-packages/docutils/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4ce42d76bcbf95c6986c1ad97063712bdb89ea --- /dev/null +++ b/.venv/lib/python3.10/site-packages/docutils/__main__.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# :Copyright: © 2020, 2022 Günter Milde. +# :License: Released under the terms of the `2-Clause BSD license`_, in short: +# +# Copying and distribution of this file, with or without modification, +# are permitted in any medium without royalty provided the copyright +# notice and this notice are preserved. +# This file is offered as-is, without any warranty. +# +# .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause +# +# Revision: $Revision: 10136 $ +# Date: $Date: 2025-05-20 17:48:27 +0200 (Di, 20. Mai 2025) $ + +"""Generic command line interface for the `docutils` package. + +See also +https://docs.python.org/3/library/__main__.html#main-py-in-python-packages +""" + +from __future__ import annotations + +__docformat__ = 'reStructuredText' + +import argparse +import locale +import sys + +import docutils +from docutils.core import Publisher, publish_cmdline, default_description + + +class CliSettingsSpec(docutils.SettingsSpec): + """Runtime settings & command-line options for the generic CLI. + + Configurable reader, parser, and writer components. + + The "--writer" default will change to 'html' in Docutils 2.0 + when 'html' becomes an alias for the current value 'html5'. + """ + + settings_spec = ( + 'Docutils Application Options', + 'Reader, writer, and parser settings influence the available options. ' + ' Example: use `--help --writer=latex` to see LaTeX writer options. ', + # options: ('help text', [