Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/INSTALLER +1 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/METADATA +158 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/RECORD +9 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/REQUESTED +0 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/WHEEL +6 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE +19 -0
- .venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/top_level.txt +2 -0
- .venv/lib/python3.10/site-packages/cyclopts/__init__.py +112 -0
- .venv/lib/python3.10/site-packages/cyclopts/__init__.pyi +37 -0
- .venv/lib/python3.10/site-packages/cyclopts/__main__.py +6 -0
- .venv/lib/python3.10/site-packages/cyclopts/_convert.py +978 -0
- .venv/lib/python3.10/site-packages/cyclopts/_edit.py +108 -0
- .venv/lib/python3.10/site-packages/cyclopts/_env_var.py +59 -0
- .venv/lib/python3.10/site-packages/cyclopts/_markup.py +132 -0
- .venv/lib/python3.10/site-packages/cyclopts/_path_type.py +155 -0
- .venv/lib/python3.10/site-packages/cyclopts/_result_action.py +147 -0
- .venv/lib/python3.10/site-packages/cyclopts/_run.py +132 -0
- .venv/lib/python3.10/site-packages/cyclopts/_version.py +24 -0
- .venv/lib/python3.10/site-packages/cyclopts/annotations.py +238 -0
- .venv/lib/python3.10/site-packages/cyclopts/app_stack.py +173 -0
- .venv/lib/python3.10/site-packages/cyclopts/argument/__init__.py +21 -0
- .venv/lib/python3.10/site-packages/cyclopts/argument/_argument.py +1178 -0
- .venv/lib/python3.10/site-packages/cyclopts/argument/_collection.py +767 -0
- .venv/lib/python3.10/site-packages/cyclopts/argument/utils.py +255 -0
- .venv/lib/python3.10/site-packages/cyclopts/bind.py +614 -0
- .venv/lib/python3.10/site-packages/cyclopts/cli/__init__.py +21 -0
- .venv/lib/python3.10/site-packages/cyclopts/cli/_complete.py +130 -0
- .venv/lib/python3.10/site-packages/cyclopts/cli/docs.py +111 -0
- .venv/lib/python3.10/site-packages/cyclopts/cli/run.py +46 -0
- .venv/lib/python3.10/site-packages/cyclopts/command_spec.py +174 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/__init__.py +11 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/_base.py +216 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/bash.py +580 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/detect.py +90 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/fish.py +543 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/install.py +237 -0
- .venv/lib/python3.10/site-packages/cyclopts/completion/zsh.py +680 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/__init__.py +14 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/_common.py +211 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/_env.py +69 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/_json.py +15 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/_toml.py +17 -0
- .venv/lib/python3.10/site-packages/cyclopts/config/_yaml.py +12 -0
- .venv/lib/python3.10/site-packages/cyclopts/core.py +0 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/__init__.py +21 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/base.py +534 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/html.py +623 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/markdown.py +780 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/rst.py +483 -0
- .venv/lib/python3.10/site-packages/cyclopts/docs/types.py +50 -0
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/METADATA
AD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
Version: 1.2.0
|
| 4 |
+
Summary: Python bindings for the Brotli compression library
|
| 5 |
+
Home-page: https://github.com/google/brotli
|
| 6 |
+
Author: The Brotli Authors
|
| 7 |
+
License: MIT
|
| 8 |
+
Platform: Posix
|
| 9 |
+
Platform: MacOS X
|
| 10 |
+
Platform: Windows
|
| 11 |
+
Classifier: Development Status :: 4 - Beta
|
| 12 |
+
Classifier: Environment :: Console
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 15 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 16 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 17 |
+
Classifier: Programming Language :: C
|
| 18 |
+
Classifier: Programming Language :: C++
|
| 19 |
+
Classifier: Programming Language :: Python
|
| 20 |
+
Classifier: Programming Language :: Python :: 2
|
| 21 |
+
Classifier: Programming Language :: Python :: 2.7
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.3
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.4
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.5
|
| 26 |
+
Classifier: Programming Language :: Unix Shell
|
| 27 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 28 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 29 |
+
Classifier: Topic :: System :: Archiving
|
| 30 |
+
Classifier: Topic :: System :: Archiving :: Compression
|
| 31 |
+
Classifier: Topic :: Text Processing :: Fonts
|
| 32 |
+
Classifier: Topic :: Utilities
|
| 33 |
+
Description-Content-Type: text/markdown
|
| 34 |
+
License-File: LICENSE
|
| 35 |
+
Dynamic: author
|
| 36 |
+
Dynamic: classifier
|
| 37 |
+
Dynamic: description
|
| 38 |
+
Dynamic: description-content-type
|
| 39 |
+
Dynamic: home-page
|
| 40 |
+
Dynamic: license
|
| 41 |
+
Dynamic: license-file
|
| 42 |
+
Dynamic: platform
|
| 43 |
+
Dynamic: summary
|
| 44 |
+
|
| 45 |
+
<p align="center">
|
| 46 |
+
<img src="https://github.com/google/brotli/actions/workflows/build_test.yml/badge.svg" alt="GitHub Actions Build Status" href="https://github.com/google/brotli/actions?query=branch%3Amaster">
|
| 47 |
+
<img src="https://oss-fuzz-build-logs.storage.googleapis.com/badges/brotli.svg" alt="Fuzzing Status" href="https://oss-fuzz-build-logs.storage.googleapis.com/index.html#brotli">
|
| 48 |
+
</p>
|
| 49 |
+
<p align="center"><img src="https://brotli.org/brotli.svg" alt="Brotli" width="64"></p>
|
| 50 |
+
|
| 51 |
+
### Introduction
|
| 52 |
+
|
| 53 |
+
Brotli is a generic-purpose lossless compression algorithm that compresses data
|
| 54 |
+
using a combination of a modern variant of the LZ77 algorithm, Huffman coding
|
| 55 |
+
and 2nd order context modeling, with a compression ratio comparable to the best
|
| 56 |
+
currently available general-purpose compression methods. It is similar in speed
|
| 57 |
+
with deflate but offers more dense compression.
|
| 58 |
+
|
| 59 |
+
The specification of the Brotli Compressed Data Format is defined in
|
| 60 |
+
[RFC 7932](https://datatracker.ietf.org/doc/html/rfc7932).
|
| 61 |
+
|
| 62 |
+
Brotli is open-sourced under the MIT License, see the LICENSE file.
|
| 63 |
+
|
| 64 |
+
> **Please note:** brotli is a "stream" format; it does not contain
|
| 65 |
+
> meta-information, like checksums or uncompressed data length. It is possible
|
| 66 |
+
> to modify "raw" ranges of the compressed stream and the decoder will not
|
| 67 |
+
> notice that.
|
| 68 |
+
|
| 69 |
+
### Installation
|
| 70 |
+
|
| 71 |
+
In most Linux distributions, installing `brotli` is just a matter of using
|
| 72 |
+
the package management system. For example in Debian-based distributions:
|
| 73 |
+
`apt install brotli` will install `brotli`. On MacOS, you can use
|
| 74 |
+
[Homebrew](https://brew.sh/): `brew install brotli`.
|
| 75 |
+
|
| 76 |
+
[](https://repology.org/project/brotli/versions)
|
| 77 |
+
|
| 78 |
+
Of course you can also build brotli from sources.
|
| 79 |
+
|
| 80 |
+
### Build instructions
|
| 81 |
+
|
| 82 |
+
#### Vcpkg
|
| 83 |
+
|
| 84 |
+
You can download and install brotli using the
|
| 85 |
+
[vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:
|
| 86 |
+
|
| 87 |
+
git clone https://github.com/Microsoft/vcpkg.git
|
| 88 |
+
cd vcpkg
|
| 89 |
+
./bootstrap-vcpkg.sh
|
| 90 |
+
./vcpkg integrate install
|
| 91 |
+
./vcpkg install brotli
|
| 92 |
+
|
| 93 |
+
The brotli port in vcpkg is kept up to date by Microsoft team members and
|
| 94 |
+
community contributors. If the version is out of date, please [create an issue
|
| 95 |
+
or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
|
| 96 |
+
|
| 97 |
+
#### Bazel
|
| 98 |
+
|
| 99 |
+
See [Bazel](https://www.bazel.build/)
|
| 100 |
+
|
| 101 |
+
#### CMake
|
| 102 |
+
|
| 103 |
+
The basic commands to build and install brotli are:
|
| 104 |
+
|
| 105 |
+
$ mkdir out && cd out
|
| 106 |
+
$ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./installed ..
|
| 107 |
+
$ cmake --build . --config Release --target install
|
| 108 |
+
|
| 109 |
+
You can use other [CMake](https://cmake.org/) configuration.
|
| 110 |
+
|
| 111 |
+
#### Python
|
| 112 |
+
|
| 113 |
+
To install the latest release of the Python module, run the following:
|
| 114 |
+
|
| 115 |
+
$ pip install brotli
|
| 116 |
+
|
| 117 |
+
To install the tip-of-the-tree version, run:
|
| 118 |
+
|
| 119 |
+
$ pip install --upgrade git+https://github.com/google/brotli
|
| 120 |
+
|
| 121 |
+
See the [Python readme](python/README.md) for more details on installing
|
| 122 |
+
from source, development, and testing.
|
| 123 |
+
|
| 124 |
+
### Contributing
|
| 125 |
+
|
| 126 |
+
We glad to answer/library related questions in
|
| 127 |
+
[brotli mailing list](https://groups.google.com/g/brotli).
|
| 128 |
+
|
| 129 |
+
Regular issues / feature requests should be reported in
|
| 130 |
+
[issue tracker](https://github.com/google/brotli/issues).
|
| 131 |
+
|
| 132 |
+
For reporting vulnerability please read [SECURITY](SECURITY.md).
|
| 133 |
+
|
| 134 |
+
For contributing changes please read [CONTRIBUTING](CONTRIBUTING.md).
|
| 135 |
+
|
| 136 |
+
### Benchmarks
|
| 137 |
+
* [Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/) / [Unstable Squash Compression Benchmark](https://quixdb.github.io/squash-benchmark/unstable/)
|
| 138 |
+
* [Large Text Compression Benchmark](https://mattmahoney.net/dc/text.html)
|
| 139 |
+
* [Lzturbo Benchmark](https://sites.google.com/site/powturbo/home/benchmark)
|
| 140 |
+
|
| 141 |
+
### Related projects
|
| 142 |
+
> **Disclaimer:** Brotli authors take no responsibility for the third party projects mentioned in this section.
|
| 143 |
+
|
| 144 |
+
Independent [decoder](https://github.com/madler/brotli) implementation
|
| 145 |
+
by Mark Adler, based entirely on format specification.
|
| 146 |
+
|
| 147 |
+
JavaScript port of brotli [decoder](https://github.com/devongovett/brotli.js).
|
| 148 |
+
Could be used directly via `npm install brotli`
|
| 149 |
+
|
| 150 |
+
Hand ported [decoder / encoder](https://github.com/dominikhlbg/BrotliHaxe)
|
| 151 |
+
in haxe by Dominik Homberger.
|
| 152 |
+
Output source code: JavaScript, PHP, Python, Java and C#
|
| 153 |
+
|
| 154 |
+
7Zip [plugin](https://github.com/mcmilk/7-Zip-Zstd)
|
| 155 |
+
|
| 156 |
+
Dart compression framework with
|
| 157 |
+
[fast FFI-based Brotli implementation](https://pub.dev/documentation/es_compression/latest/brotli/)
|
| 158 |
+
with ready-to-use prebuilt binaries for Win/Linux/Mac
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_brotli.cpython-310-x86_64-linux-gnu.so,sha256=Rx-Ml4X8kqv4Zeyh-9KvI8XLKBBHOBqs29aTzajqizk,5170080
|
| 2 |
+
brotli-1.2.0.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 3 |
+
brotli-1.2.0.dist-info/METADATA,sha256=-dEtUYS1CQsUay5fDWKTFSGysUNepGZDOiObt8QfyWI,6116
|
| 4 |
+
brotli-1.2.0.dist-info/RECORD,,
|
| 5 |
+
brotli-1.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
brotli-1.2.0.dist-info/WHEEL,sha256=DTnKjM5OInJxWADod3iQyWxWcdG-eRwxzGww236swpY,151
|
| 7 |
+
brotli-1.2.0.dist-info/licenses/LICENSE,sha256=PRgACONpIqTo2uwRw0x68mT-1ZYtB5JK6pKMOOhmPJQ,1084
|
| 8 |
+
brotli-1.2.0.dist-info/top_level.txt,sha256=gsS54HrhO3ZveFxeMrKo_7qH4Sm4TbQ7jGLVBEqJ4NI,15
|
| 9 |
+
brotli.py,sha256=gTYQvw10ppmNe0fZEuiJLDiW5urBnLeyJXXgT8KUtj8,1970
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
| 6 |
+
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 4 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 5 |
+
in the Software without restriction, including without limitation the rights
|
| 6 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 7 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 8 |
+
furnished to do so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in
|
| 11 |
+
all copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 19 |
+
THE SOFTWARE.
|
.venv/lib/python3.10/site-packages/brotli-1.2.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_brotli
|
| 2 |
+
brotli
|
.venv/lib/python3.10/site-packages/cyclopts/__init__.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__version__: str
|
| 2 |
+
try:
|
| 3 |
+
# _version.py is auto-generated by hatch-vcs during build from git tags
|
| 4 |
+
from cyclopts._version import __version__ # type: ignore[import-not-found]
|
| 5 |
+
except ImportError:
|
| 6 |
+
__version__ = "0.0.0.dev0"
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"__version__",
|
| 10 |
+
"App",
|
| 11 |
+
"Argument",
|
| 12 |
+
"ArgumentCollection",
|
| 13 |
+
"ArgumentOrderError",
|
| 14 |
+
"Token",
|
| 15 |
+
"CoercionError",
|
| 16 |
+
"CombinedShortOptionError",
|
| 17 |
+
"CommandCollisionError",
|
| 18 |
+
"CycloptsError",
|
| 19 |
+
"CycloptsPanel",
|
| 20 |
+
"Dispatcher",
|
| 21 |
+
"DocstringError",
|
| 22 |
+
"EditorError",
|
| 23 |
+
"EditorNotFoundError",
|
| 24 |
+
"EditorDidNotSaveError",
|
| 25 |
+
"EditorDidNotChangeError",
|
| 26 |
+
"Group",
|
| 27 |
+
"UnknownCommandError",
|
| 28 |
+
"MissingArgumentError",
|
| 29 |
+
"ConsumeMultipleError",
|
| 30 |
+
"MixedArgumentError",
|
| 31 |
+
"RepeatArgumentError",
|
| 32 |
+
"RequiresEqualsError",
|
| 33 |
+
"Parameter",
|
| 34 |
+
"ResultAction",
|
| 35 |
+
"UnknownOptionError",
|
| 36 |
+
"UnusedCliTokensError",
|
| 37 |
+
"UNSET",
|
| 38 |
+
"ValidationError",
|
| 39 |
+
"config",
|
| 40 |
+
"convert",
|
| 41 |
+
"default_name_transform",
|
| 42 |
+
"edit",
|
| 43 |
+
"env_var_split",
|
| 44 |
+
"types",
|
| 45 |
+
"validators",
|
| 46 |
+
"run",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
from cyclopts._convert import convert
|
| 50 |
+
from cyclopts._env_var import env_var_split
|
| 51 |
+
from cyclopts._result_action import ResultAction
|
| 52 |
+
from cyclopts._run import run
|
| 53 |
+
from cyclopts.argument import Argument, ArgumentCollection
|
| 54 |
+
from cyclopts.core import App
|
| 55 |
+
from cyclopts.exceptions import (
|
| 56 |
+
ArgumentOrderError,
|
| 57 |
+
CoercionError,
|
| 58 |
+
CombinedShortOptionError,
|
| 59 |
+
CommandCollisionError,
|
| 60 |
+
ConsumeMultipleError,
|
| 61 |
+
CycloptsError,
|
| 62 |
+
DocstringError,
|
| 63 |
+
MissingArgumentError,
|
| 64 |
+
MixedArgumentError,
|
| 65 |
+
RepeatArgumentError,
|
| 66 |
+
RequiresEqualsError,
|
| 67 |
+
UnknownCommandError,
|
| 68 |
+
UnknownOptionError,
|
| 69 |
+
UnusedCliTokensError,
|
| 70 |
+
ValidationError,
|
| 71 |
+
)
|
| 72 |
+
from cyclopts.group import Group
|
| 73 |
+
from cyclopts.panel import CycloptsPanel
|
| 74 |
+
from cyclopts.parameter import Parameter
|
| 75 |
+
from cyclopts.protocols import Dispatcher
|
| 76 |
+
from cyclopts.token import Token
|
| 77 |
+
from cyclopts.utils import UNSET, default_name_transform
|
| 78 |
+
|
| 79 |
+
# Lazy imports for opt-in features (saves ~6ms on import)
|
| 80 |
+
# These modules are only loaded when explicitly accessed by user code
|
| 81 |
+
_LAZY_IMPORTS = {
|
| 82 |
+
# Submodules - opt-in features not needed for basic CLI parsing
|
| 83 |
+
"config": "cyclopts.config", # Configuration file parsing (JSON, TOML, YAML, env)
|
| 84 |
+
"types": "cyclopts.types", # ~3ms - special types like ResolvedExistingPath
|
| 85 |
+
"validators": "cyclopts.validators", # ~2ms - validators like Number, Path
|
| 86 |
+
# Editor functionality - rarely used
|
| 87 |
+
"edit": "cyclopts._edit", # ~4ms
|
| 88 |
+
"EditorError": "cyclopts._edit",
|
| 89 |
+
"EditorNotFoundError": "cyclopts._edit",
|
| 90 |
+
"EditorDidNotSaveError": "cyclopts._edit",
|
| 91 |
+
"EditorDidNotChangeError": "cyclopts._edit",
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def __getattr__(name: str):
|
| 96 |
+
"""Lazy-load opt-in features and rarely-used functionality."""
|
| 97 |
+
if name in _LAZY_IMPORTS:
|
| 98 |
+
import importlib
|
| 99 |
+
|
| 100 |
+
module_path = _LAZY_IMPORTS[name]
|
| 101 |
+
if name in ("config", "types", "validators"):
|
| 102 |
+
# These are submodules, import the module itself
|
| 103 |
+
module = importlib.import_module(module_path)
|
| 104 |
+
globals()[name] = module
|
| 105 |
+
return module
|
| 106 |
+
else:
|
| 107 |
+
# These are attributes from modules (e.g., edit, EditorError)
|
| 108 |
+
module = importlib.import_module(module_path)
|
| 109 |
+
value = getattr(module, name)
|
| 110 |
+
globals()[name] = value
|
| 111 |
+
return value
|
| 112 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
.venv/lib/python3.10/site-packages/cyclopts/__init__.pyi
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cyclopts import config as config
|
| 2 |
+
from cyclopts import types as types
|
| 3 |
+
from cyclopts import validators as validators
|
| 4 |
+
from cyclopts._convert import convert as convert
|
| 5 |
+
from cyclopts._edit import EditorDidNotChangeError as EditorDidNotChangeError
|
| 6 |
+
from cyclopts._edit import EditorDidNotSaveError as EditorDidNotSaveError
|
| 7 |
+
from cyclopts._edit import EditorError as EditorError
|
| 8 |
+
from cyclopts._edit import EditorNotFoundError as EditorNotFoundError
|
| 9 |
+
from cyclopts._edit import edit as edit
|
| 10 |
+
from cyclopts._env_var import env_var_split as env_var_split
|
| 11 |
+
from cyclopts._result_action import ResultAction as ResultAction
|
| 12 |
+
from cyclopts._run import run as run
|
| 13 |
+
from cyclopts.argument import Argument as Argument
|
| 14 |
+
from cyclopts.argument import ArgumentCollection as ArgumentCollection
|
| 15 |
+
from cyclopts.core import App as App
|
| 16 |
+
from cyclopts.exceptions import ArgumentOrderError as ArgumentOrderError
|
| 17 |
+
from cyclopts.exceptions import CoercionError as CoercionError
|
| 18 |
+
from cyclopts.exceptions import CombinedShortOptionError as CombinedShortOptionError
|
| 19 |
+
from cyclopts.exceptions import CommandCollisionError as CommandCollisionError
|
| 20 |
+
from cyclopts.exceptions import CycloptsError as CycloptsError
|
| 21 |
+
from cyclopts.exceptions import DocstringError as DocstringError
|
| 22 |
+
from cyclopts.exceptions import MissingArgumentError as MissingArgumentError
|
| 23 |
+
from cyclopts.exceptions import MixedArgumentError as MixedArgumentError
|
| 24 |
+
from cyclopts.exceptions import RepeatArgumentError as RepeatArgumentError
|
| 25 |
+
from cyclopts.exceptions import UnknownCommandError as UnknownCommandError
|
| 26 |
+
from cyclopts.exceptions import UnknownOptionError as UnknownOptionError
|
| 27 |
+
from cyclopts.exceptions import UnusedCliTokensError as UnusedCliTokensError
|
| 28 |
+
from cyclopts.exceptions import ValidationError as ValidationError
|
| 29 |
+
from cyclopts.group import Group as Group
|
| 30 |
+
from cyclopts.panel import CycloptsPanel as CycloptsPanel
|
| 31 |
+
from cyclopts.parameter import Parameter as Parameter
|
| 32 |
+
from cyclopts.protocols import Dispatcher as Dispatcher
|
| 33 |
+
from cyclopts.token import Token as Token
|
| 34 |
+
from cyclopts.utils import UNSET as UNSET
|
| 35 |
+
from cyclopts.utils import default_name_transform as default_name_transform
|
| 36 |
+
|
| 37 |
+
__version__: str
|
.venv/lib/python3.10/site-packages/cyclopts/__main__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cyclopts CLI entry point."""
|
| 2 |
+
|
| 3 |
+
from cyclopts.cli import app
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
app()
|
.venv/lib/python3.10/site-packages/cyclopts/_convert.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections.abc
|
| 2 |
+
import inspect
|
| 3 |
+
import json
|
| 4 |
+
import operator
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
import typing
|
| 8 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 9 |
+
from datetime import date, datetime, timedelta
|
| 10 |
+
from enum import Enum, Flag
|
| 11 |
+
from functools import partial, reduce
|
| 12 |
+
from typing import (
|
| 13 |
+
TYPE_CHECKING,
|
| 14 |
+
Any,
|
| 15 |
+
Literal,
|
| 16 |
+
TypeVar,
|
| 17 |
+
Union,
|
| 18 |
+
get_args,
|
| 19 |
+
get_origin,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
if sys.version_info >= (3, 12):
|
| 23 |
+
from typing import TypeAliasType
|
| 24 |
+
else:
|
| 25 |
+
TypeAliasType = None
|
| 26 |
+
|
| 27 |
+
from cyclopts.annotations import (
|
| 28 |
+
ITERABLE_TYPES,
|
| 29 |
+
get_annotated_discriminator,
|
| 30 |
+
is_annotated,
|
| 31 |
+
is_enum_flag,
|
| 32 |
+
is_nonetype,
|
| 33 |
+
is_union,
|
| 34 |
+
resolve,
|
| 35 |
+
resolve_optional,
|
| 36 |
+
)
|
| 37 |
+
from cyclopts.exceptions import CoercionError, ValidationError
|
| 38 |
+
from cyclopts.field_info import FieldInfo, get_field_infos
|
| 39 |
+
from cyclopts.utils import UNSET, default_name_transform, grouper, is_builtin, is_class_and_subclass
|
| 40 |
+
|
| 41 |
+
if sys.version_info >= (3, 12): # pragma: no cover
|
| 42 |
+
from typing import TypeAliasType
|
| 43 |
+
else: # pragma: no cover
|
| 44 |
+
TypeAliasType = None
|
| 45 |
+
|
| 46 |
+
if TYPE_CHECKING:
|
| 47 |
+
from cyclopts.argument import Token
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
T = TypeVar("T")
|
| 51 |
+
E = TypeVar("E", bound=Enum)
|
| 52 |
+
F = TypeVar("F", bound=Flag)
|
| 53 |
+
|
| 54 |
+
# Mapping from bare concrete types to their default parameterized versions.
|
| 55 |
+
# Used when type parameters are not specified (e.g., bare `list` becomes `list[str]`).
|
| 56 |
+
_implicit_iterable_type_mapping: dict[type, type] = {
|
| 57 |
+
frozenset: frozenset[str],
|
| 58 |
+
list: list[str],
|
| 59 |
+
set: set[str],
|
| 60 |
+
tuple: tuple[str, ...],
|
| 61 |
+
dict: dict[str, str],
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# Mapping from abstract collection types to their concrete implementations.
|
| 65 |
+
# Used to convert abstract types like collections.abc.Set to concrete types like set.
|
| 66 |
+
_abstract_to_concrete_type_mapping: dict[type, type] = {
|
| 67 |
+
Iterable: list,
|
| 68 |
+
typing.Sequence: list,
|
| 69 |
+
Sequence: list,
|
| 70 |
+
collections.abc.Set: set,
|
| 71 |
+
collections.abc.MutableSet: set,
|
| 72 |
+
collections.abc.MutableSequence: list,
|
| 73 |
+
collections.abc.Mapping: dict,
|
| 74 |
+
collections.abc.MutableMapping: dict,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
NestedCliArgs = dict[str, Union[Sequence[str], "NestedCliArgs"]]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _bool(s: str) -> bool:
|
| 81 |
+
s = s.lower()
|
| 82 |
+
if s in {"no", "n", "0", "false", "f"}:
|
| 83 |
+
return False
|
| 84 |
+
elif s in {"yes", "y", "1", "true", "t"}:
|
| 85 |
+
return True
|
| 86 |
+
else:
|
| 87 |
+
# Cyclopts is a little bit conservative when coercing strings into boolean.
|
| 88 |
+
raise CoercionError(target_type=bool)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _int(s: str) -> int:
|
| 92 |
+
s = s.lower()
|
| 93 |
+
if s.startswith("0x"):
|
| 94 |
+
return int(s, 16)
|
| 95 |
+
elif s.startswith("0o"):
|
| 96 |
+
return int(s, 8)
|
| 97 |
+
elif s.startswith("0b"):
|
| 98 |
+
return int(s, 2)
|
| 99 |
+
elif "." in s:
|
| 100 |
+
# Casting to a float first allows for things like "30.0"
|
| 101 |
+
# We handle this conditionally because very large integers can lose
|
| 102 |
+
# meaningful precision when cast to a float.
|
| 103 |
+
return int(round(float(s)))
|
| 104 |
+
else:
|
| 105 |
+
return int(s)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _bytes(s: str) -> bytes:
|
| 109 |
+
return bytes(s, encoding="utf8")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _bytearray(s: str) -> bytearray:
|
| 113 |
+
return bytearray(_bytes(s))
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _date(s: str) -> date:
|
| 117 |
+
"""Parse a date string.
|
| 118 |
+
|
| 119 |
+
Returns
|
| 120 |
+
-------
|
| 121 |
+
datetime.date
|
| 122 |
+
"""
|
| 123 |
+
return date.fromisoformat(s)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _datetime(s: str) -> datetime:
|
| 127 |
+
"""Parse a datetime string.
|
| 128 |
+
|
| 129 |
+
Returns
|
| 130 |
+
-------
|
| 131 |
+
datetime.datetime
|
| 132 |
+
"""
|
| 133 |
+
try:
|
| 134 |
+
return datetime.fromisoformat(s)
|
| 135 |
+
except ValueError:
|
| 136 |
+
# Fallback for space-separated format (not ISO 8601 compliant)
|
| 137 |
+
# Python 3.11+ fromisoformat() accepts spaces, but 3.10 doesn't
|
| 138 |
+
# Convert space to 'T' to make it ISO-compliant
|
| 139 |
+
return datetime.fromisoformat(s.strip().replace(" ", "T", 1))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _timedelta(s: str) -> timedelta:
|
| 143 |
+
"""Parse a timedelta string."""
|
| 144 |
+
negative = False
|
| 145 |
+
if s.startswith("-"):
|
| 146 |
+
negative = True
|
| 147 |
+
s = s[1:]
|
| 148 |
+
|
| 149 |
+
matches = re.findall(r"((\d+\.\d+|\d+)([smhdwMy]))", s)
|
| 150 |
+
|
| 151 |
+
if not matches:
|
| 152 |
+
raise ValueError(f"Could not parse duration string: {s}")
|
| 153 |
+
|
| 154 |
+
seconds = 0
|
| 155 |
+
for _, value, unit in matches:
|
| 156 |
+
value = float(value)
|
| 157 |
+
if unit == "s":
|
| 158 |
+
seconds += value
|
| 159 |
+
elif unit == "m":
|
| 160 |
+
seconds += value * 60
|
| 161 |
+
elif unit == "h":
|
| 162 |
+
seconds += value * 3600
|
| 163 |
+
elif unit == "d":
|
| 164 |
+
seconds += value * 86400
|
| 165 |
+
elif unit == "w":
|
| 166 |
+
seconds += value * 604800
|
| 167 |
+
elif unit == "M":
|
| 168 |
+
# Approximation: 1 month = 30 days
|
| 169 |
+
seconds += value * 2592000
|
| 170 |
+
elif unit == "y":
|
| 171 |
+
# Approximation: 1 year = 365 days
|
| 172 |
+
seconds += value * 31536000
|
| 173 |
+
|
| 174 |
+
if negative:
|
| 175 |
+
seconds = -seconds
|
| 176 |
+
return timedelta(seconds=seconds)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def get_enum_member(
|
| 180 |
+
type_: type[E],
|
| 181 |
+
token: Union["Token", str],
|
| 182 |
+
name_transform: Callable[[str], str],
|
| 183 |
+
) -> E:
|
| 184 |
+
"""Match a token's value to an enum's member.
|
| 185 |
+
|
| 186 |
+
Applies ``name_transform`` to both the value and the member.
|
| 187 |
+
"""
|
| 188 |
+
from cyclopts.argument import Token
|
| 189 |
+
|
| 190 |
+
is_token = isinstance(token, Token)
|
| 191 |
+
value = token.value if is_token else token
|
| 192 |
+
value_transformed = name_transform(value)
|
| 193 |
+
for name, member in type_.__members__.items():
|
| 194 |
+
if name_transform(name) == value_transformed:
|
| 195 |
+
return member
|
| 196 |
+
raise CoercionError(
|
| 197 |
+
token=token if is_token else None,
|
| 198 |
+
target_type=type_,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def convert_enum_flag(
|
| 203 |
+
enum_type: type[F],
|
| 204 |
+
tokens: Iterable[str] | Iterable["Token"],
|
| 205 |
+
name_transform: Callable[[str], str],
|
| 206 |
+
) -> F:
|
| 207 |
+
"""Convert tokens to a Flag enum value.
|
| 208 |
+
|
| 209 |
+
Parameters
|
| 210 |
+
----------
|
| 211 |
+
enum_type : type[F]
|
| 212 |
+
The Flag enum type to convert to.
|
| 213 |
+
tokens : Iterable[str] | Iterable[Token]
|
| 214 |
+
The tokens to convert. Can be member names or :class:`Token` objects.
|
| 215 |
+
name_transform : Callable[[str], str] | None
|
| 216 |
+
Function to transform names for comparison.
|
| 217 |
+
|
| 218 |
+
Returns
|
| 219 |
+
-------
|
| 220 |
+
F
|
| 221 |
+
The combined flag value.
|
| 222 |
+
|
| 223 |
+
Raises
|
| 224 |
+
------
|
| 225 |
+
CoercionError
|
| 226 |
+
If a token is not a valid flag member.
|
| 227 |
+
"""
|
| 228 |
+
return reduce(
|
| 229 |
+
operator.or_,
|
| 230 |
+
(get_enum_member(enum_type, token, name_transform) for token in tokens),
|
| 231 |
+
enum_type(0),
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# For types that need more logic than just invoking their type
|
| 236 |
+
_converters: dict[Any, Callable] = {
|
| 237 |
+
bool: _bool,
|
| 238 |
+
int: _int,
|
| 239 |
+
bytes: _bytes,
|
| 240 |
+
bytearray: _bytearray,
|
| 241 |
+
date: _date,
|
| 242 |
+
datetime: _datetime,
|
| 243 |
+
timedelta: _timedelta,
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _convert_tuple(
|
| 248 |
+
type_: type[Any],
|
| 249 |
+
*tokens: "Token",
|
| 250 |
+
converter: Callable[[type, str], Any] | None,
|
| 251 |
+
name_transform: Callable[[str], str],
|
| 252 |
+
) -> tuple:
|
| 253 |
+
convert = partial(_convert, converter=converter, name_transform=name_transform)
|
| 254 |
+
inner_types = tuple(x for x in get_args(type_) if x is not ...)
|
| 255 |
+
inner_token_count, consume_all = token_count(type_)
|
| 256 |
+
# Elements like boolean-flags will have an inner_token_count of 0.
|
| 257 |
+
inner_token_count = max(inner_token_count, 1)
|
| 258 |
+
if consume_all:
|
| 259 |
+
# variable-length tuple (list-like)
|
| 260 |
+
remainder = len(tokens) % inner_token_count
|
| 261 |
+
if remainder:
|
| 262 |
+
raise CoercionError(
|
| 263 |
+
msg=f"Incorrect number of arguments: expected multiple of {inner_token_count} but got {len(tokens)}."
|
| 264 |
+
)
|
| 265 |
+
if len(inner_types) == 1:
|
| 266 |
+
inner_type = inner_types[0]
|
| 267 |
+
elif len(inner_types) == 0:
|
| 268 |
+
inner_type = str
|
| 269 |
+
else:
|
| 270 |
+
raise ValueError("A tuple must have 0 or 1 inner-types.")
|
| 271 |
+
|
| 272 |
+
return tuple(
|
| 273 |
+
convert(inner_type, chunk[0] if inner_token_count == 1 else chunk)
|
| 274 |
+
for chunk in grouper(tokens, inner_token_count)
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
# Fixed-length tuple
|
| 278 |
+
if inner_token_count != len(tokens):
|
| 279 |
+
raise CoercionError(
|
| 280 |
+
msg=f"Incorrect number of arguments: expected {inner_token_count} but got {len(tokens)}."
|
| 281 |
+
)
|
| 282 |
+
args_per_convert = [token_count(x)[0] for x in inner_types]
|
| 283 |
+
it = iter(tokens)
|
| 284 |
+
batched = [[next(it) for _ in range(size)] for size in args_per_convert]
|
| 285 |
+
batched = [elem[0] if len(elem) == 1 else elem for elem in batched]
|
| 286 |
+
out = tuple(convert(inner_type, arg) for inner_type, arg in zip(inner_types, batched, strict=False))
|
| 287 |
+
return out
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _validate_json_extra_keys(
|
| 291 |
+
data: dict,
|
| 292 |
+
type_: type,
|
| 293 |
+
token: "Token | None" = None,
|
| 294 |
+
) -> None:
|
| 295 |
+
"""Validate that JSON data doesn't contain extra keys not in the type's fields.
|
| 296 |
+
|
| 297 |
+
Parameters
|
| 298 |
+
----------
|
| 299 |
+
data : dict
|
| 300 |
+
The JSON dictionary to validate.
|
| 301 |
+
type_ : type
|
| 302 |
+
The target type (dataclass, etc.) to validate against.
|
| 303 |
+
token : Token | None
|
| 304 |
+
Optional token for error context.
|
| 305 |
+
|
| 306 |
+
Raises
|
| 307 |
+
------
|
| 308 |
+
CoercionError
|
| 309 |
+
If the data contains keys not present in the type's fields.
|
| 310 |
+
"""
|
| 311 |
+
field_infos = get_field_infos(type_)
|
| 312 |
+
# Collect all valid names including aliases (e.g., Pydantic camelCase aliases)
|
| 313 |
+
valid_names: set[str] = set()
|
| 314 |
+
for field_name, field_info in field_infos.items():
|
| 315 |
+
valid_names.add(field_name)
|
| 316 |
+
valid_names.update(field_info.names)
|
| 317 |
+
extra_keys = set(data.keys()) - valid_names
|
| 318 |
+
if extra_keys:
|
| 319 |
+
extra_key = sorted(extra_keys)[0] # Report first extra key alphabetically for determinism
|
| 320 |
+
valid_fields = ", ".join(sorted(field_infos.keys()))
|
| 321 |
+
raise CoercionError(
|
| 322 |
+
msg=f'Unknown field "{extra_key}" in JSON for {type_.__name__}. Valid fields: {valid_fields}',
|
| 323 |
+
target_type=type_,
|
| 324 |
+
token=token,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _convert_json(
|
| 329 |
+
type_: Any,
|
| 330 |
+
data: dict,
|
| 331 |
+
field_infos: dict,
|
| 332 |
+
converter: Callable | None,
|
| 333 |
+
name_transform: Callable[[str], str],
|
| 334 |
+
):
|
| 335 |
+
"""Convert JSON dict to dataclass with proper type conversion for fields.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
----------
|
| 339 |
+
type_ : Type
|
| 340 |
+
The dataclass type to create.
|
| 341 |
+
data : dict
|
| 342 |
+
The JSON dictionary containing field values.
|
| 343 |
+
field_infos : dict
|
| 344 |
+
Field information from the dataclass.
|
| 345 |
+
converter : Callable | None
|
| 346 |
+
Optional converter function.
|
| 347 |
+
name_transform : Callable[[str], str]
|
| 348 |
+
Function to transform field names.
|
| 349 |
+
|
| 350 |
+
Returns
|
| 351 |
+
-------
|
| 352 |
+
Instance of type_ with properly converted field values.
|
| 353 |
+
"""
|
| 354 |
+
from cyclopts.token import Token
|
| 355 |
+
|
| 356 |
+
# Validate no extra keys in JSON data
|
| 357 |
+
_validate_json_extra_keys(data, type_)
|
| 358 |
+
|
| 359 |
+
converted_data = {}
|
| 360 |
+
for field_name, field_info in field_infos.items():
|
| 361 |
+
if field_name in data:
|
| 362 |
+
value = data[field_name]
|
| 363 |
+
# Convert the value to the proper type
|
| 364 |
+
if value is not None and not is_class_and_subclass(field_info.hint, str):
|
| 365 |
+
# Create a token for the value and convert it
|
| 366 |
+
token = Token(value=json.dumps(value) if isinstance(value, dict | list) else str(value))
|
| 367 |
+
# Always attempt conversion, let errors propagate for consistency
|
| 368 |
+
converted_value = convert(field_info.hint, [token], converter, name_transform)
|
| 369 |
+
else:
|
| 370 |
+
converted_value = value
|
| 371 |
+
converted_data[field_name] = converted_value
|
| 372 |
+
|
| 373 |
+
# Create the dataclass with converted values
|
| 374 |
+
return type_(**converted_data)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _create_json_decode_error_message(
|
| 378 |
+
token: "Token",
|
| 379 |
+
type_: Any,
|
| 380 |
+
error: json.JSONDecodeError,
|
| 381 |
+
) -> str:
|
| 382 |
+
"""Create a helpful error message for JSON decode errors.
|
| 383 |
+
|
| 384 |
+
Parameters
|
| 385 |
+
----------
|
| 386 |
+
token : Token
|
| 387 |
+
The token containing the invalid JSON.
|
| 388 |
+
type_ : Type
|
| 389 |
+
The target type we were trying to convert to.
|
| 390 |
+
error : json.JSONDecodeError
|
| 391 |
+
The JSON decode error that occurred.
|
| 392 |
+
|
| 393 |
+
Returns
|
| 394 |
+
-------
|
| 395 |
+
str
|
| 396 |
+
A formatted error message with context and hints.
|
| 397 |
+
"""
|
| 398 |
+
value_str = token.value.strip()
|
| 399 |
+
|
| 400 |
+
# Try to provide context around the error
|
| 401 |
+
error_pos = error.pos if hasattr(error, "pos") else error.colno - 1 if hasattr(error, "colno") else 0
|
| 402 |
+
|
| 403 |
+
# Create a snippet showing the error location
|
| 404 |
+
snippet_start = max(0, error_pos - 20)
|
| 405 |
+
snippet_end = min(len(value_str), error_pos + 20)
|
| 406 |
+
snippet = value_str[snippet_start:snippet_end]
|
| 407 |
+
|
| 408 |
+
# Add markers if we truncated
|
| 409 |
+
if snippet_start > 0:
|
| 410 |
+
snippet = "..." + snippet
|
| 411 |
+
if snippet_end < len(value_str):
|
| 412 |
+
snippet = snippet + "..."
|
| 413 |
+
|
| 414 |
+
# Calculate where the error marker should point
|
| 415 |
+
marker_pos = error_pos - snippet_start
|
| 416 |
+
if snippet_start > 0:
|
| 417 |
+
marker_pos += 3 # Account for "..."
|
| 418 |
+
|
| 419 |
+
# Common error patterns with helpful hints
|
| 420 |
+
hint = ""
|
| 421 |
+
if re.search(r"\bTrue\b", value_str):
|
| 422 |
+
hint = "\n Hint: Use lowercase 'true' instead of Python's True"
|
| 423 |
+
elif re.search(r"\bFalse\b", value_str):
|
| 424 |
+
hint = "\n Hint: Use lowercase 'false' instead of Python's False"
|
| 425 |
+
elif re.search(r"\bNone\b", value_str):
|
| 426 |
+
hint = "\n Hint: Use 'null' instead of Python's None"
|
| 427 |
+
elif "'" in value_str:
|
| 428 |
+
hint = "\n Hint: JSON requires double quotes, not single quotes"
|
| 429 |
+
|
| 430 |
+
return f"Invalid JSON for {type_.__name__}:\n {snippet}\n {' ' * marker_pos}^ {error.msg}{hint}"
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def instantiate_from_dict(type_: type[T], data: dict[str, Any]) -> T:
|
| 434 |
+
"""Instantiate a type with proper handling of parameter kinds.
|
| 435 |
+
|
| 436 |
+
Respects POSITIONAL_ONLY, KEYWORD_ONLY, and POSITIONAL_OR_KEYWORD parameter kinds
|
| 437 |
+
when constructing the object.
|
| 438 |
+
|
| 439 |
+
This function is necessary because `inspect.signature().bind(**data)` has the same
|
| 440 |
+
limitation we're solving: it cannot accept positional-only parameters as keyword
|
| 441 |
+
arguments. For example, `def __init__(self, a, /, b)` requires `a` to be passed
|
| 442 |
+
positionally, but when we have a dict `{"a": 1, "b": 2}`, we need to transform
|
| 443 |
+
this into the call `type_(1, b=2)`.
|
| 444 |
+
|
| 445 |
+
Parameters
|
| 446 |
+
----------
|
| 447 |
+
type_ : type[T]
|
| 448 |
+
The type to instantiate.
|
| 449 |
+
data : dict[str, Any]
|
| 450 |
+
Dictionary mapping field names to values.
|
| 451 |
+
|
| 452 |
+
Returns
|
| 453 |
+
-------
|
| 454 |
+
T
|
| 455 |
+
Instance of type_ constructed from data.
|
| 456 |
+
"""
|
| 457 |
+
field_infos = get_field_infos(type_)
|
| 458 |
+
if not field_infos:
|
| 459 |
+
return type_(**data)
|
| 460 |
+
|
| 461 |
+
pos_args = []
|
| 462 |
+
kwargs = {}
|
| 463 |
+
|
| 464 |
+
for field_name, value in data.items():
|
| 465 |
+
field_info = field_infos.get(field_name)
|
| 466 |
+
if field_info and field_info.kind == FieldInfo.POSITIONAL_ONLY:
|
| 467 |
+
pos_args.append((field_name, value))
|
| 468 |
+
else:
|
| 469 |
+
kwargs[field_name] = value
|
| 470 |
+
|
| 471 |
+
# Sort positional args by their order in field_infos
|
| 472 |
+
field_names_order = list(field_infos.keys())
|
| 473 |
+
pos_args.sort(key=lambda x: field_names_order.index(x[0]))
|
| 474 |
+
|
| 475 |
+
return type_(*(v for _, v in pos_args), **kwargs)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _convert_structured_type(
|
| 479 |
+
type_: type[T],
|
| 480 |
+
token: Sequence["Token"],
|
| 481 |
+
field_infos: dict[str, "FieldInfo"],
|
| 482 |
+
convert: Callable,
|
| 483 |
+
) -> T:
|
| 484 |
+
"""Convert tokens to a structured type with proper positional/keyword argument handling.
|
| 485 |
+
|
| 486 |
+
Respects the parameter kind of each field:
|
| 487 |
+
- POSITIONAL_ONLY: passed as positional argument
|
| 488 |
+
- KEYWORD_ONLY or POSITIONAL_OR_KEYWORD: passed as keyword argument
|
| 489 |
+
|
| 490 |
+
This correctly handles types with keyword-only fields (e.g., dataclasses with kw_only=True).
|
| 491 |
+
|
| 492 |
+
Parameters
|
| 493 |
+
----------
|
| 494 |
+
type_ : type[T]
|
| 495 |
+
The target structured type to instantiate.
|
| 496 |
+
token : Sequence[Token]
|
| 497 |
+
The tokens to convert.
|
| 498 |
+
field_infos : dict[str, FieldInfo]
|
| 499 |
+
Field information for the structured type.
|
| 500 |
+
convert : Callable
|
| 501 |
+
Conversion function for nested types.
|
| 502 |
+
|
| 503 |
+
Returns
|
| 504 |
+
-------
|
| 505 |
+
T
|
| 506 |
+
Instance of type_ constructed from the tokens.
|
| 507 |
+
"""
|
| 508 |
+
i = 0
|
| 509 |
+
data = {}
|
| 510 |
+
hint = type_
|
| 511 |
+
|
| 512 |
+
for field_name, field_info in field_infos.items():
|
| 513 |
+
hint = field_info.hint
|
| 514 |
+
|
| 515 |
+
# Convert the token(s) for this field
|
| 516 |
+
if is_class_and_subclass(hint, str): # Avoids infinite recursion
|
| 517 |
+
value = token[i].value
|
| 518 |
+
i += 1
|
| 519 |
+
should_break = False
|
| 520 |
+
else:
|
| 521 |
+
tokens_per_element, consume_all = token_count(hint)
|
| 522 |
+
if tokens_per_element == 1:
|
| 523 |
+
value = convert(hint, token[i])
|
| 524 |
+
i += 1
|
| 525 |
+
else:
|
| 526 |
+
value = convert(hint, token[i : i + tokens_per_element])
|
| 527 |
+
i += tokens_per_element
|
| 528 |
+
should_break = consume_all
|
| 529 |
+
|
| 530 |
+
data[field_name] = value
|
| 531 |
+
|
| 532 |
+
# Handle consume_all or end of tokens
|
| 533 |
+
if should_break:
|
| 534 |
+
break
|
| 535 |
+
if i == len(token):
|
| 536 |
+
break
|
| 537 |
+
|
| 538 |
+
assert i == len(token)
|
| 539 |
+
return instantiate_from_dict(type_, data)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _convert(
|
| 543 |
+
type_,
|
| 544 |
+
token: Union["Token", Sequence["Token"]],
|
| 545 |
+
*,
|
| 546 |
+
converter: Callable[[Any, str], Any] | None,
|
| 547 |
+
name_transform: Callable[[str], str],
|
| 548 |
+
):
|
| 549 |
+
"""Inner recursive conversion function for public ``convert``.
|
| 550 |
+
|
| 551 |
+
Parameters
|
| 552 |
+
----------
|
| 553 |
+
converter: Callable
|
| 554 |
+
name_transform: Callable
|
| 555 |
+
"""
|
| 556 |
+
from cyclopts.argument import Token
|
| 557 |
+
from cyclopts.parameter import Parameter
|
| 558 |
+
|
| 559 |
+
converter_needs_token = False
|
| 560 |
+
if is_annotated(type_):
|
| 561 |
+
from cyclopts.parameter import Parameter
|
| 562 |
+
|
| 563 |
+
type_, cparam = Parameter.from_annotation(type_)
|
| 564 |
+
if cparam.converter:
|
| 565 |
+
converter_needs_token = True
|
| 566 |
+
|
| 567 |
+
def converter_with_token(t_, value):
|
| 568 |
+
assert cparam.converter
|
| 569 |
+
|
| 570 |
+
# Resolve string converters to methods on the type
|
| 571 |
+
resolved_converter = cparam.converter
|
| 572 |
+
if isinstance(resolved_converter, str):
|
| 573 |
+
resolved_converter = getattr(t_, resolved_converter)
|
| 574 |
+
|
| 575 |
+
# Detect bound methods (classmethods/instance methods)
|
| 576 |
+
# Bound methods already have their first parameter bound
|
| 577 |
+
if inspect.ismethod(resolved_converter):
|
| 578 |
+
# Call with just tokens - cls/self already bound
|
| 579 |
+
return resolved_converter((value,))
|
| 580 |
+
else:
|
| 581 |
+
# Regular function - pass type and tokens
|
| 582 |
+
return resolved_converter(t_, (value,))
|
| 583 |
+
|
| 584 |
+
converter = converter_with_token
|
| 585 |
+
|
| 586 |
+
if cparam.name_transform:
|
| 587 |
+
name_transform = cparam.name_transform
|
| 588 |
+
else:
|
| 589 |
+
cparam = None
|
| 590 |
+
|
| 591 |
+
convert = partial(_convert, converter=converter, name_transform=name_transform)
|
| 592 |
+
convert_tuple = partial(_convert_tuple, converter=converter, name_transform=name_transform)
|
| 593 |
+
|
| 594 |
+
origin_type = get_origin(type_)
|
| 595 |
+
# Normalize abstract origin types to concrete types early
|
| 596 |
+
# (e.g., collections.abc.Set -> set) so we only check ITERABLE_TYPES later
|
| 597 |
+
if origin_type in _abstract_to_concrete_type_mapping:
|
| 598 |
+
origin_type = _abstract_to_concrete_type_mapping[origin_type]
|
| 599 |
+
# Inner types **may** be ``Annotated``
|
| 600 |
+
inner_types = get_args(type_)
|
| 601 |
+
|
| 602 |
+
if type_ is dict:
|
| 603 |
+
out = convert(dict[str, str], token)
|
| 604 |
+
elif type_ in _implicit_iterable_type_mapping:
|
| 605 |
+
out = convert(_implicit_iterable_type_mapping[type_], token)
|
| 606 |
+
elif type_ in _abstract_to_concrete_type_mapping:
|
| 607 |
+
# Bare abstract type (e.g., collections.abc.Set with no [T])
|
| 608 |
+
# Convert to default parameterized concrete type
|
| 609 |
+
concrete_type = _abstract_to_concrete_type_mapping[type_]
|
| 610 |
+
default_param = _implicit_iterable_type_mapping.get(concrete_type, concrete_type)
|
| 611 |
+
out = convert(default_param, token)
|
| 612 |
+
elif TypeAliasType is not None and isinstance(type_, TypeAliasType):
|
| 613 |
+
out = convert(type_.__value__, token)
|
| 614 |
+
elif is_union(origin_type):
|
| 615 |
+
for t in inner_types:
|
| 616 |
+
if is_nonetype(t):
|
| 617 |
+
continue
|
| 618 |
+
try:
|
| 619 |
+
out = convert(t, token)
|
| 620 |
+
break
|
| 621 |
+
except Exception:
|
| 622 |
+
pass
|
| 623 |
+
else:
|
| 624 |
+
if isinstance(token, Sequence):
|
| 625 |
+
raise ValueError # noqa: TRY004
|
| 626 |
+
raise CoercionError(token=token, target_type=type_)
|
| 627 |
+
elif origin_type is Literal:
|
| 628 |
+
# Try coercing the token into each allowed Literal value (left-to-right).
|
| 629 |
+
last_coercion_error = None
|
| 630 |
+
for choice in get_args(type_):
|
| 631 |
+
try:
|
| 632 |
+
res = convert(type(choice), token)
|
| 633 |
+
except CoercionError as e:
|
| 634 |
+
last_coercion_error = e
|
| 635 |
+
continue
|
| 636 |
+
if res == choice:
|
| 637 |
+
out = res
|
| 638 |
+
break
|
| 639 |
+
else:
|
| 640 |
+
if last_coercion_error:
|
| 641 |
+
last_coercion_error.target_type = type_
|
| 642 |
+
raise last_coercion_error
|
| 643 |
+
else:
|
| 644 |
+
raise CoercionError(token=token[0] if isinstance(token, Sequence) else token, target_type=type_)
|
| 645 |
+
elif origin_type is tuple:
|
| 646 |
+
if isinstance(token, Token):
|
| 647 |
+
# E.g. Tuple[str] (Annotation: tuple containing a single string)
|
| 648 |
+
out = convert_tuple(type_, token, converter=converter)
|
| 649 |
+
else:
|
| 650 |
+
out = convert_tuple(type_, *token, converter=converter)
|
| 651 |
+
elif origin_type in ITERABLE_TYPES:
|
| 652 |
+
# NOT including tuple; handled in ``origin_type is tuple`` body above.
|
| 653 |
+
# Note: origin_type has already been normalized from abstract to concrete
|
| 654 |
+
count, _ = token_count(inner_types[0])
|
| 655 |
+
if not isinstance(token, Sequence):
|
| 656 |
+
raise ValueError
|
| 657 |
+
|
| 658 |
+
# Check if tokens are JSON strings
|
| 659 |
+
inner_type = inner_types[0]
|
| 660 |
+
if (
|
| 661 |
+
count > 1
|
| 662 |
+
and any(isinstance(t, Token) and t.value.strip().startswith("{") for t in token)
|
| 663 |
+
and inner_type is not str
|
| 664 |
+
):
|
| 665 |
+
# Each token is a complete JSON representation of the dataclass
|
| 666 |
+
gen = token
|
| 667 |
+
elif count > 1:
|
| 668 |
+
gen = zip(*[iter(token)] * count, strict=False)
|
| 669 |
+
else:
|
| 670 |
+
gen = token
|
| 671 |
+
out = origin_type(convert(inner_types[0], e) for e in gen)
|
| 672 |
+
elif is_class_and_subclass(type_, Flag):
|
| 673 |
+
# TODO: this might never execute since enum.Flag is now handled in ``convert``.
|
| 674 |
+
out = convert_enum_flag(type_, token if isinstance(token, Sequence) else [token], name_transform)
|
| 675 |
+
elif is_class_and_subclass(type_, Enum):
|
| 676 |
+
if isinstance(token, Sequence):
|
| 677 |
+
raise ValueError
|
| 678 |
+
|
| 679 |
+
if converter is None:
|
| 680 |
+
out = get_enum_member(type_, token, name_transform)
|
| 681 |
+
else:
|
| 682 |
+
out = converter(type_, token.value)
|
| 683 |
+
else:
|
| 684 |
+
field_infos = get_field_infos(type_)
|
| 685 |
+
# Hope that if there is no field_info, that it takes `*args` and would be happy with a single ``str`` input.
|
| 686 |
+
# This is common for many types, such as libraries that try to mimic pathlib.Path interface.
|
| 687 |
+
# TODO: This doesn't respect the type-annotation of ``*args``.
|
| 688 |
+
if is_builtin(type_) or not field_infos:
|
| 689 |
+
assert isinstance(token, Token)
|
| 690 |
+
try:
|
| 691 |
+
if token.implicit_value is not UNSET:
|
| 692 |
+
out = token.implicit_value
|
| 693 |
+
elif converter is None:
|
| 694 |
+
out = _converters.get(type_, type_)(token.value) # pyright: ignore[reportOptionalCall]
|
| 695 |
+
elif converter_needs_token:
|
| 696 |
+
out = converter(type_, token) # pyright: ignore[reportArgumentType]
|
| 697 |
+
else:
|
| 698 |
+
out = converter(type_, token.value)
|
| 699 |
+
except CoercionError as e:
|
| 700 |
+
if e.target_type is None:
|
| 701 |
+
e.target_type = type_
|
| 702 |
+
if e.token is None:
|
| 703 |
+
e.token = token
|
| 704 |
+
raise
|
| 705 |
+
except ValueError:
|
| 706 |
+
raise CoercionError(token=token, target_type=type_) from None
|
| 707 |
+
else:
|
| 708 |
+
# Convert it into a user-supplied class.
|
| 709 |
+
# First check if we have a single token that's a JSON string
|
| 710 |
+
if isinstance(token, Token) and token.value.strip().startswith("{") and type_ is not str:
|
| 711 |
+
try:
|
| 712 |
+
data = json.loads(token.value)
|
| 713 |
+
if not isinstance(data, dict):
|
| 714 |
+
# JSON was valid but didn't produce a dict (e.g., it was an array or scalar)
|
| 715 |
+
raise TypeError # noqa: TRY301
|
| 716 |
+
# Convert dict to dataclass with proper type conversion
|
| 717 |
+
out = _convert_json(type_, data, field_infos, converter, name_transform)
|
| 718 |
+
except json.JSONDecodeError as e:
|
| 719 |
+
# Create helpful error message for invalid JSON
|
| 720 |
+
msg = _create_json_decode_error_message(token, type_, e)
|
| 721 |
+
raise CoercionError(msg=msg, token=token, target_type=type_) from e
|
| 722 |
+
except TypeError:
|
| 723 |
+
# Fall back to positional argument parsing
|
| 724 |
+
if not isinstance(token, Sequence):
|
| 725 |
+
token = [token]
|
| 726 |
+
out = _convert_structured_type(type_, token, field_infos, convert)
|
| 727 |
+
else:
|
| 728 |
+
# Standard positional argument parsing
|
| 729 |
+
if not isinstance(token, Sequence):
|
| 730 |
+
token = [token]
|
| 731 |
+
out = _convert_structured_type(type_, token, field_infos, convert)
|
| 732 |
+
|
| 733 |
+
if cparam:
|
| 734 |
+
# An inner type may have an independent Parameter annotation;
|
| 735 |
+
# e.g.:
|
| 736 |
+
# Uint8 = Annotated[int, ...]
|
| 737 |
+
# rgb: tuple[Uint8, Uint8, Uint8]
|
| 738 |
+
try:
|
| 739 |
+
for validator in cparam.validator: # pyright: ignore
|
| 740 |
+
validator(type_, out)
|
| 741 |
+
except (AssertionError, ValueError, TypeError) as e:
|
| 742 |
+
raise ValidationError(exception_message=e.args[0] if e.args else "", value=out) from e
|
| 743 |
+
|
| 744 |
+
return out
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def convert(
|
| 748 |
+
type_: Any,
|
| 749 |
+
tokens: Sequence[str] | Sequence["Token"] | NestedCliArgs,
|
| 750 |
+
converter: Callable[[type, str], Any] | None = None,
|
| 751 |
+
name_transform: Callable[[str], str] | None = None,
|
| 752 |
+
):
|
| 753 |
+
"""Coerce variables into a specified type.
|
| 754 |
+
|
| 755 |
+
Internally used to coercing string CLI tokens into python builtin types.
|
| 756 |
+
Externally, may be useful in a custom converter.
|
| 757 |
+
See Cyclopt's automatic coercion rules :doc:`/rules`.
|
| 758 |
+
|
| 759 |
+
If ``type_`` **is not** iterable, then each element of ``tokens`` will be converted independently.
|
| 760 |
+
If there is more than one element, then the return type will be a ``Tuple[type_, ...]``.
|
| 761 |
+
If there is a single element, then the return type will be ``type_``.
|
| 762 |
+
|
| 763 |
+
If ``type_`` **is** iterable, then all elements of ``tokens`` will be collated.
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
----------
|
| 767 |
+
type_: Type
|
| 768 |
+
A type hint/annotation to coerce ``*args`` into.
|
| 769 |
+
tokens: Union[Sequence[str], NestedCliArgs]
|
| 770 |
+
String tokens to coerce.
|
| 771 |
+
Generally, either a list of strings, or a dictionary of list of strings (recursive).
|
| 772 |
+
Each leaf in the dictionary tree should be a list of strings.
|
| 773 |
+
converter: Optional[Callable[[Type, str], Any]]
|
| 774 |
+
An optional function to convert tokens to the inner-most types.
|
| 775 |
+
The converter should have signature:
|
| 776 |
+
|
| 777 |
+
.. code-block:: python
|
| 778 |
+
|
| 779 |
+
def converter(type_: type, value: str) -> Any:
|
| 780 |
+
"Perform conversion of string token."
|
| 781 |
+
|
| 782 |
+
This allows to use the :func:`convert` function to handle the the difficult task
|
| 783 |
+
of traversing lists/tuples/unions/etc, while leaving the final conversion logic to
|
| 784 |
+
the caller.
|
| 785 |
+
name_transform: Optional[Callable[[str], str]]
|
| 786 |
+
Currently only used for ``Enum`` type hints.
|
| 787 |
+
A function that transforms enum names and CLI values into a normalized format.
|
| 788 |
+
|
| 789 |
+
The function should have signature:
|
| 790 |
+
|
| 791 |
+
.. code-block:: python
|
| 792 |
+
|
| 793 |
+
def name_transform(s: str) -> str:
|
| 794 |
+
"Perform name transform."
|
| 795 |
+
|
| 796 |
+
where the returned value is the name to be used on the CLI.
|
| 797 |
+
|
| 798 |
+
If ``None``, defaults to ``cyclopts.default_name_transform``.
|
| 799 |
+
|
| 800 |
+
Returns
|
| 801 |
+
-------
|
| 802 |
+
Any
|
| 803 |
+
Coerced version of input ``*args``.
|
| 804 |
+
"""
|
| 805 |
+
from cyclopts.argument import Token
|
| 806 |
+
|
| 807 |
+
if not tokens:
|
| 808 |
+
raise ValueError
|
| 809 |
+
|
| 810 |
+
if not isinstance(tokens, dict) and isinstance(tokens[0], str):
|
| 811 |
+
tokens = tuple(Token(value=str(x)) for x in tokens)
|
| 812 |
+
|
| 813 |
+
if name_transform is None:
|
| 814 |
+
name_transform = default_name_transform
|
| 815 |
+
|
| 816 |
+
convert_priv = partial(_convert, converter=converter, name_transform=name_transform)
|
| 817 |
+
convert_tuple = partial(_convert_tuple, converter=converter, name_transform=name_transform)
|
| 818 |
+
type_ = resolve(type_)
|
| 819 |
+
|
| 820 |
+
if type_ is Any:
|
| 821 |
+
type_ = str
|
| 822 |
+
|
| 823 |
+
type_ = _implicit_iterable_type_mapping.get(type_, type_)
|
| 824 |
+
|
| 825 |
+
# Handle bare abstract types (e.g., collections.abc.Set without [T])
|
| 826 |
+
# Convert to their default parameterized concrete versions
|
| 827 |
+
if type_ in _abstract_to_concrete_type_mapping:
|
| 828 |
+
concrete_type = _abstract_to_concrete_type_mapping[type_]
|
| 829 |
+
type_ = _implicit_iterable_type_mapping.get(concrete_type, concrete_type)
|
| 830 |
+
|
| 831 |
+
origin_type = get_origin(type_)
|
| 832 |
+
# Normalize abstract origin types to concrete types early
|
| 833 |
+
if origin_type in _abstract_to_concrete_type_mapping:
|
| 834 |
+
origin_type = _abstract_to_concrete_type_mapping[origin_type]
|
| 835 |
+
maybe_origin_type = origin_type or type_
|
| 836 |
+
|
| 837 |
+
if origin_type is tuple:
|
| 838 |
+
return convert_tuple(type_, *tokens) # pyright: ignore
|
| 839 |
+
elif maybe_origin_type in ITERABLE_TYPES:
|
| 840 |
+
return convert_priv(type_, tokens) # pyright: ignore
|
| 841 |
+
elif maybe_origin_type is dict:
|
| 842 |
+
if not isinstance(tokens, dict):
|
| 843 |
+
raise ValueError # Programming error
|
| 844 |
+
try:
|
| 845 |
+
value_type = get_args(type_)[1]
|
| 846 |
+
except IndexError:
|
| 847 |
+
value_type = str
|
| 848 |
+
dict_converted = {
|
| 849 |
+
k: convert(value_type, v, converter=converter, name_transform=name_transform) for k, v in tokens.items()
|
| 850 |
+
}
|
| 851 |
+
return _converters.get(maybe_origin_type, maybe_origin_type)(**dict_converted)
|
| 852 |
+
elif isinstance(tokens, dict):
|
| 853 |
+
raise ValueError(f"Dictionary of tokens provided for unknown {type_!r}.") # Programming error
|
| 854 |
+
elif is_enum_flag(maybe_origin_type):
|
| 855 |
+
# Unlike other types that can accept multiple tokens, the result is not a sequence, it's a single
|
| 856 |
+
# enum.Flag object.
|
| 857 |
+
return convert_enum_flag(maybe_origin_type, tokens, name_transform)
|
| 858 |
+
else:
|
| 859 |
+
tokens_per_element, consume_all = token_count(type_)
|
| 860 |
+
if consume_all:
|
| 861 |
+
return convert_priv(type_, tokens) # pyright: ignore
|
| 862 |
+
elif len(tokens) == 1:
|
| 863 |
+
return convert_priv(type_, tokens[0]) # pyright: ignore
|
| 864 |
+
elif tokens_per_element == 1:
|
| 865 |
+
return [convert_priv(type_, item) for item in tokens] # pyright: ignore
|
| 866 |
+
elif len(tokens) == tokens_per_element:
|
| 867 |
+
return convert_priv(type_, tokens) # pyright: ignore
|
| 868 |
+
else:
|
| 869 |
+
raise NotImplementedError("Unreachable?")
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def token_count(type_: Any, skip_converter_params: bool = False) -> tuple[int, bool]:
|
| 873 |
+
"""The number of tokens after a keyword the parameter should consume.
|
| 874 |
+
|
| 875 |
+
Parameters
|
| 876 |
+
----------
|
| 877 |
+
type_: Type
|
| 878 |
+
A type hint/annotation to infer token_count from if not explicitly specified.
|
| 879 |
+
skip_converter_params: bool
|
| 880 |
+
If True, don't extract converter parameters from __cyclopts__.
|
| 881 |
+
Used to prevent infinite recursion when determining consume_all behavior.
|
| 882 |
+
|
| 883 |
+
Returns
|
| 884 |
+
-------
|
| 885 |
+
int
|
| 886 |
+
Number of tokens to consume.
|
| 887 |
+
bool
|
| 888 |
+
If this is ``True`` and positional, consume all remaining tokens.
|
| 889 |
+
The returned number of tokens constitutes a single element of the iterable-to-be-parsed.
|
| 890 |
+
"""
|
| 891 |
+
# Discriminated unions (e.g. Annotated[Cat | Dog, pydantic.Field(discriminator="type")])
|
| 892 |
+
# consume a single JSON string token regardless of member field counts.
|
| 893 |
+
# Check before get_parameters strips the Annotated metadata.
|
| 894 |
+
if get_annotated_discriminator(resolve_optional(type_)) is not None:
|
| 895 |
+
return 1, False
|
| 896 |
+
|
| 897 |
+
# Check for explicit n_tokens in Parameter annotation before resolving
|
| 898 |
+
# This handles nested cases like tuple[Annotated[str, Parameter(n_tokens=2)], int]
|
| 899 |
+
from cyclopts.parameter import get_parameters
|
| 900 |
+
|
| 901 |
+
resolved_type, parameters = get_parameters(type_, skip_converter_params=skip_converter_params)
|
| 902 |
+
for param in parameters:
|
| 903 |
+
if param.n_tokens is not None:
|
| 904 |
+
if param.n_tokens == -1:
|
| 905 |
+
return 1, True
|
| 906 |
+
else:
|
| 907 |
+
# Recursively determine consume_all from the type's natural structure.
|
| 908 |
+
# Only recurse if the type has changed (e.g., Annotated wrapper was removed).
|
| 909 |
+
# If resolved_type is the same as type_, recursing would cause infinite loop.
|
| 910 |
+
if resolved_type is not type_:
|
| 911 |
+
# Skip converter params to avoid infinite recursion when converter is decorated
|
| 912 |
+
# with @Parameter(n_tokens=...) and attached to a class via @Parameter(converter=...).
|
| 913 |
+
_, consume_all_from_type = token_count(resolved_type, skip_converter_params=True)
|
| 914 |
+
else:
|
| 915 |
+
# Type didn't change (e.g., class decorated with @Parameter(n_tokens=...))
|
| 916 |
+
# Can't determine natural consume_all by recursing on same type
|
| 917 |
+
consume_all_from_type = False
|
| 918 |
+
return param.n_tokens, consume_all_from_type
|
| 919 |
+
|
| 920 |
+
type_ = resolved_type
|
| 921 |
+
origin_type = get_origin(type_)
|
| 922 |
+
# Normalize abstract origin types to concrete types early
|
| 923 |
+
if origin_type in _abstract_to_concrete_type_mapping:
|
| 924 |
+
origin_type = _abstract_to_concrete_type_mapping[origin_type]
|
| 925 |
+
|
| 926 |
+
# Handle bare abstract types like bare concrete types
|
| 927 |
+
if type_ in _abstract_to_concrete_type_mapping:
|
| 928 |
+
concrete_type = _abstract_to_concrete_type_mapping[type_]
|
| 929 |
+
type_ = _implicit_iterable_type_mapping.get(concrete_type, concrete_type)
|
| 930 |
+
origin_type = get_origin(type_)
|
| 931 |
+
|
| 932 |
+
if (origin_type or type_) is tuple:
|
| 933 |
+
args = get_args(type_)
|
| 934 |
+
if args:
|
| 935 |
+
return sum(token_count(x)[0] for x in args if x is not ...), ... in args
|
| 936 |
+
else:
|
| 937 |
+
return 1, True
|
| 938 |
+
elif (origin_type or type_) is bool:
|
| 939 |
+
return 0, False
|
| 940 |
+
elif type_ in ITERABLE_TYPES or (origin_type in ITERABLE_TYPES and len(get_args(type_)) == 0):
|
| 941 |
+
return 1, True
|
| 942 |
+
elif is_enum_flag(type_):
|
| 943 |
+
return 1, True
|
| 944 |
+
elif origin_type in ITERABLE_TYPES and len(get_args(type_)):
|
| 945 |
+
return token_count(get_args(type_)[0])[0], True
|
| 946 |
+
elif TypeAliasType is not None and isinstance(type_, TypeAliasType):
|
| 947 |
+
return token_count(type_.__value__)
|
| 948 |
+
elif is_union(type_):
|
| 949 |
+
sub_args = get_args(type_)
|
| 950 |
+
token_count_target = token_count(sub_args[0])
|
| 951 |
+
for sub_type_ in sub_args[1:]:
|
| 952 |
+
this = token_count(sub_type_)
|
| 953 |
+
if this != token_count_target:
|
| 954 |
+
raise ValueError(
|
| 955 |
+
f"Cannot Union types that consume different numbers of tokens: {sub_args[0]} {sub_type_}"
|
| 956 |
+
)
|
| 957 |
+
return token_count_target
|
| 958 |
+
elif is_builtin(type_):
|
| 959 |
+
# Many builtins actually take in VAR_POSITIONAL when we really just want 1 argument.
|
| 960 |
+
return 1, False
|
| 961 |
+
else:
|
| 962 |
+
# This is usually/always a custom user-defined class.
|
| 963 |
+
field_infos = get_field_infos(type_)
|
| 964 |
+
count, consume_all = 0, False
|
| 965 |
+
for value in field_infos.values():
|
| 966 |
+
if value.kind is value.VAR_POSITIONAL:
|
| 967 |
+
consume_all = True
|
| 968 |
+
elif not value.required:
|
| 969 |
+
continue
|
| 970 |
+
elem_count, elem_consume_all = token_count(value.hint)
|
| 971 |
+
count += elem_count
|
| 972 |
+
consume_all |= elem_consume_all
|
| 973 |
+
|
| 974 |
+
# classes like ``enum.Enum`` can slip through here with a 0 count.
|
| 975 |
+
if not count:
|
| 976 |
+
return 1, False
|
| 977 |
+
|
| 978 |
+
return count, consume_all
|
.venv/lib/python3.10/site-packages/cyclopts/_edit.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import time
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class EditorError(Exception):
|
| 9 |
+
"""Root editor-related error.
|
| 10 |
+
|
| 11 |
+
Root exception raised by all exceptions in :func:`.edit`.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class EditorDidNotSaveError(EditorError):
|
| 16 |
+
"""User did not save upon exiting :func:`.edit`."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class EditorDidNotChangeError(EditorError):
|
| 20 |
+
"""User did not edit file contents in :func:`.edit`."""
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class EditorNotFoundError(EditorError):
|
| 24 |
+
"""Could not find a valid text editor for :func`.edit`."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def edit(
|
| 28 |
+
initial_text: str = "",
|
| 29 |
+
*,
|
| 30 |
+
fallback_editors: Sequence[str] = ("nano", "vim", "notepad", "gedit"),
|
| 31 |
+
editor_args: Sequence[str] = (),
|
| 32 |
+
path: str | Path = "",
|
| 33 |
+
encoding: str = "utf-8",
|
| 34 |
+
save: bool = True,
|
| 35 |
+
required: bool = True,
|
| 36 |
+
) -> str:
|
| 37 |
+
"""Get text input from a user by launching their default text editor.
|
| 38 |
+
|
| 39 |
+
Parameters
|
| 40 |
+
----------
|
| 41 |
+
initial_text: str
|
| 42 |
+
Initial text to populate the text file with.
|
| 43 |
+
fallback_editors: Sequence[str]
|
| 44 |
+
If the text editor cannot be determined from the environment variable ``EDITOR``, attempt to use these text editors in the order provided.
|
| 45 |
+
editor_args: Sequence[str]
|
| 46 |
+
Additional CLI arguments that are passed along to the editor-launch command.
|
| 47 |
+
path: Union[str, Path]
|
| 48 |
+
If specified, the path to the file that should be opened.
|
| 49 |
+
Text editors typically display this, so a custom path may result in a better user-interface.
|
| 50 |
+
Defaults to a temporary text file.
|
| 51 |
+
encoding: str
|
| 52 |
+
File encoding to use.
|
| 53 |
+
save: bool
|
| 54 |
+
**Require** the user to save before exiting the editor. Otherwise raises :exc:`EditorDidNotSaveError`.
|
| 55 |
+
required: bool
|
| 56 |
+
**Require** for the saved text to be different from ``initial_text``. Otherwise raises :exc:`EditorDidNotChangeError`.
|
| 57 |
+
|
| 58 |
+
Raises
|
| 59 |
+
------
|
| 60 |
+
EditorError
|
| 61 |
+
Base editor error exception. Explicitly raised if editor subcommand
|
| 62 |
+
returned a non-zero exit code.
|
| 63 |
+
EditorNotFoundError
|
| 64 |
+
A suitable text editor could not be found.
|
| 65 |
+
EditorDidNotSaveError
|
| 66 |
+
The user exited the text-editor without saving and ``save=True``.
|
| 67 |
+
EditorDidNotChangeError
|
| 68 |
+
The user did not change the file contents and ``required=True``.
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
-------
|
| 72 |
+
str
|
| 73 |
+
The resulting text that was saved by the text editor.
|
| 74 |
+
"""
|
| 75 |
+
import shutil
|
| 76 |
+
import subprocess
|
| 77 |
+
|
| 78 |
+
for editor in (os.environ.get("EDITOR"), *fallback_editors):
|
| 79 |
+
if editor and shutil.which(editor):
|
| 80 |
+
break
|
| 81 |
+
else:
|
| 82 |
+
raise EditorNotFoundError
|
| 83 |
+
|
| 84 |
+
if path:
|
| 85 |
+
path = Path(path)
|
| 86 |
+
path.parent.mkdir(exist_ok=True, parents=True)
|
| 87 |
+
else:
|
| 88 |
+
path = Path(tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False).name)
|
| 89 |
+
path.write_text(initial_text, encoding=encoding)
|
| 90 |
+
past_time = time.time() - 5 # arbitrarily set time to 5 seconds ago; some systems only have 1 second precision.
|
| 91 |
+
os.utime(path, (past_time, past_time)) # Set access and modification time
|
| 92 |
+
start_stat = path.stat()
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
subprocess.check_call([editor, path, *editor_args])
|
| 96 |
+
end_stat = path.stat()
|
| 97 |
+
if save and end_stat.st_mtime <= start_stat.st_mtime:
|
| 98 |
+
raise EditorDidNotSaveError
|
| 99 |
+
edited_text = path.read_text(encoding=encoding)
|
| 100 |
+
except subprocess.CalledProcessError as e:
|
| 101 |
+
raise EditorError(f"{editor} exited with status {e.returncode}") from e
|
| 102 |
+
finally:
|
| 103 |
+
path.unlink(missing_ok=True)
|
| 104 |
+
|
| 105 |
+
if required and edited_text == initial_text:
|
| 106 |
+
raise EditorDidNotChangeError
|
| 107 |
+
|
| 108 |
+
return edited_text
|
.venv/lib/python3.10/site-packages/cyclopts/_env_var.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any, get_args
|
| 4 |
+
|
| 5 |
+
from cyclopts._convert import resolve, token_count
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _is_path(type_) -> bool:
|
| 9 |
+
if type_ is Path:
|
| 10 |
+
return True
|
| 11 |
+
|
| 12 |
+
for inner_type in get_args(type_):
|
| 13 |
+
inner_type = resolve(inner_type)
|
| 14 |
+
if _is_path(inner_type):
|
| 15 |
+
return True
|
| 16 |
+
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def env_var_split(
|
| 21 |
+
type_: Any,
|
| 22 |
+
val: str,
|
| 23 |
+
*,
|
| 24 |
+
delimiter: str | None = None,
|
| 25 |
+
) -> list[str]:
|
| 26 |
+
"""Type-dependent environment variable value splitting.
|
| 27 |
+
|
| 28 |
+
Converts a single string into a list of strings. Splits when:
|
| 29 |
+
|
| 30 |
+
* The ``type_`` is some variant of ``Iterable[pathlib.Path]`` objects.
|
| 31 |
+
If Windows, split on ``;``, otherwise split on ``:``.
|
| 32 |
+
|
| 33 |
+
* Otherwise, if the ``type_`` is an ``Iterable``, split on whitespace.
|
| 34 |
+
Leading/trailing whitespace of each output element will be stripped.
|
| 35 |
+
|
| 36 |
+
This function is the default value for :attr:`cyclopts.App.env_var_split`.
|
| 37 |
+
|
| 38 |
+
Parameters
|
| 39 |
+
----------
|
| 40 |
+
type_: type
|
| 41 |
+
Type hint that we will eventually coerce into.
|
| 42 |
+
val: str
|
| 43 |
+
String to split.
|
| 44 |
+
delimiter: str | None
|
| 45 |
+
Delimiter to split ``val`` on.
|
| 46 |
+
If None, defaults to whitespace.
|
| 47 |
+
|
| 48 |
+
Returns
|
| 49 |
+
-------
|
| 50 |
+
list[str]
|
| 51 |
+
List of individual string tokens.
|
| 52 |
+
"""
|
| 53 |
+
type_ = resolve(type_)
|
| 54 |
+
count, consume_all = token_count(type_)
|
| 55 |
+
|
| 56 |
+
if count > 1 or consume_all:
|
| 57 |
+
return val.split(os.pathsep) if _is_path(type_) else val.split(delimiter)
|
| 58 |
+
else:
|
| 59 |
+
return [val]
|
.venv/lib/python3.10/site-packages/cyclopts/_markup.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Markup and format conversion utilities.
|
| 2 |
+
|
| 3 |
+
Pure utility layer for text processing across help and docs systems.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import io
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Optional
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from rich.console import Console
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def extract_text(obj: Any, console: Optional["Console"] = None, preserve_markup: bool = False) -> str:
|
| 14 |
+
"""Extract text from Rich renderables or any object.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
obj : Any
|
| 19 |
+
Object to convert to text.
|
| 20 |
+
console : Console | None
|
| 21 |
+
Console for rendering Rich objects.
|
| 22 |
+
preserve_markup : bool
|
| 23 |
+
If True, preserve original markdown/RST markup when available.
|
| 24 |
+
When False, always render to plain text.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
str
|
| 29 |
+
Text representation (plain or with markup preserved).
|
| 30 |
+
"""
|
| 31 |
+
if obj is None:
|
| 32 |
+
return ""
|
| 33 |
+
|
| 34 |
+
if hasattr(obj, "primary_renderable"):
|
| 35 |
+
primary = getattr(obj, "primary_renderable", None)
|
| 36 |
+
if primary is not None:
|
| 37 |
+
if preserve_markup and hasattr(primary, "markup"):
|
| 38 |
+
return primary.markup.rstrip()
|
| 39 |
+
return extract_text(primary, console, preserve_markup=preserve_markup)
|
| 40 |
+
|
| 41 |
+
if hasattr(obj, "plain"):
|
| 42 |
+
return obj.plain.rstrip()
|
| 43 |
+
|
| 44 |
+
if preserve_markup and hasattr(obj, "markup"):
|
| 45 |
+
return obj.markup.rstrip()
|
| 46 |
+
|
| 47 |
+
if hasattr(obj, "__rich_console__"):
|
| 48 |
+
from rich.console import Console
|
| 49 |
+
|
| 50 |
+
plain_console = Console(
|
| 51 |
+
file=io.StringIO(),
|
| 52 |
+
width=console.width if console else 120,
|
| 53 |
+
force_terminal=False,
|
| 54 |
+
no_color=True,
|
| 55 |
+
highlight=False,
|
| 56 |
+
markup=False,
|
| 57 |
+
emoji=False,
|
| 58 |
+
)
|
| 59 |
+
with plain_console.capture() as capture:
|
| 60 |
+
plain_console.print(obj, end="")
|
| 61 |
+
return capture.get().rstrip()
|
| 62 |
+
|
| 63 |
+
return str(obj).rstrip()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def escape_rst(text: str | None) -> str:
|
| 67 |
+
"""Escape special reStructuredText characters in text.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
text : str | None
|
| 72 |
+
Text to escape. Can be None.
|
| 73 |
+
|
| 74 |
+
Returns
|
| 75 |
+
-------
|
| 76 |
+
str
|
| 77 |
+
Escaped text safe for RST.
|
| 78 |
+
"""
|
| 79 |
+
if not text:
|
| 80 |
+
return ""
|
| 81 |
+
return text.replace("\\", "\\\\")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def escape_markdown(text: str | None) -> str | None:
|
| 85 |
+
"""Escape special markdown characters in text.
|
| 86 |
+
|
| 87 |
+
If the text appears to already contain markdown formatting (bold, italic,
|
| 88 |
+
code, links, or headings), it is returned unchanged. Otherwise, pipe
|
| 89 |
+
characters are escaped for table compatibility.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
text : str | None
|
| 94 |
+
Text to escape. Can be None.
|
| 95 |
+
|
| 96 |
+
Returns
|
| 97 |
+
-------
|
| 98 |
+
str | None
|
| 99 |
+
Escaped text safe for markdown, or None if input was None.
|
| 100 |
+
"""
|
| 101 |
+
if not text:
|
| 102 |
+
return text
|
| 103 |
+
|
| 104 |
+
if any(pattern in text for pattern in ["**", "``", "`", "](", "#"]):
|
| 105 |
+
return text
|
| 106 |
+
|
| 107 |
+
text = text.replace("|", "\\|")
|
| 108 |
+
return text
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def escape_html(text: str | None) -> str:
|
| 112 |
+
"""Escape special HTML characters in text.
|
| 113 |
+
|
| 114 |
+
Parameters
|
| 115 |
+
----------
|
| 116 |
+
text : str | None
|
| 117 |
+
Text to escape. Can be None.
|
| 118 |
+
|
| 119 |
+
Returns
|
| 120 |
+
-------
|
| 121 |
+
str
|
| 122 |
+
Escaped text safe for HTML.
|
| 123 |
+
"""
|
| 124 |
+
if not text:
|
| 125 |
+
return ""
|
| 126 |
+
|
| 127 |
+
text = text.replace("&", "&")
|
| 128 |
+
text = text.replace("<", "<")
|
| 129 |
+
text = text.replace(">", ">")
|
| 130 |
+
text = text.replace('"', """)
|
| 131 |
+
text = text.replace("'", "'")
|
| 132 |
+
return text
|
.venv/lib/python3.10/site-packages/cyclopts/_path_type.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""":class:`StdioPath` - A Path subclass that treats ``-`` as stdin/stdout.
|
| 2 |
+
|
| 3 |
+
Requires Python 3.12+ for proper Path subclassing support.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import io
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import IO, TYPE_CHECKING
|
| 10 |
+
|
| 11 |
+
from cyclopts.parameter import Parameter
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from collections.abc import Buffer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _NonClosingIOWrapper:
|
| 18 |
+
"""Wrapper around an IO stream that doesn't close on context exit.
|
| 19 |
+
|
| 20 |
+
This is used to wrap stdin/stdout so they can be used as context managers
|
| 21 |
+
without being closed when the context exits.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, stream: IO, detach_on_exit: bool = False):
|
| 25 |
+
self._stream = stream
|
| 26 |
+
self._detach_on_exit = detach_on_exit
|
| 27 |
+
|
| 28 |
+
def __enter__(self):
|
| 29 |
+
return self._stream
|
| 30 |
+
|
| 31 |
+
def __exit__(self, *args):
|
| 32 |
+
# Flush any buffered data (important for TextIOWrapper)
|
| 33 |
+
self._stream.flush()
|
| 34 |
+
if self._detach_on_exit:
|
| 35 |
+
self._stream.detach() # Detach TextIOWrapper without closing underlying buffer
|
| 36 |
+
|
| 37 |
+
def __getattr__(self, name):
|
| 38 |
+
return getattr(self._stream, name)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@Parameter(allow_leading_hyphen=True)
|
| 42 |
+
class StdioPath(Path):
|
| 43 |
+
"""A :class:`~pathlib.Path` subclass that treats ``-`` as stdin/stdout."""
|
| 44 |
+
|
| 45 |
+
STDIO_STRING: str = "-"
|
| 46 |
+
"""The string that represents stdin/stdout. Override in subclasses for custom behavior."""
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def is_stdio(self) -> bool:
|
| 50 |
+
"""Return True if this represents stdin/stdout.
|
| 51 |
+
|
| 52 |
+
Override this property in subclasses for custom matching logic
|
| 53 |
+
(e.g., matching multiple strings or using pattern matching).
|
| 54 |
+
"""
|
| 55 |
+
return str(self) == self.STDIO_STRING
|
| 56 |
+
|
| 57 |
+
def __repr__(self):
|
| 58 |
+
return f"{type(self).__name__}({str(self)!r})"
|
| 59 |
+
|
| 60 |
+
def exists(self, *, follow_symlinks: bool = True) -> bool:
|
| 61 |
+
"""Return True if path exists. Always True for stdio."""
|
| 62 |
+
return True if self.is_stdio else super().exists(follow_symlinks=follow_symlinks)
|
| 63 |
+
|
| 64 |
+
def open( # pyright: ignore[reportIncompatibleMethodOverride]
|
| 65 |
+
self,
|
| 66 |
+
mode: str = "r",
|
| 67 |
+
buffering: int = -1,
|
| 68 |
+
encoding: str | None = None,
|
| 69 |
+
errors: str | None = None,
|
| 70 |
+
newline: str | None = None,
|
| 71 |
+
):
|
| 72 |
+
"""Open the file or return stdin/stdout.
|
| 73 |
+
|
| 74 |
+
For stdio paths, returns a wrapper around the appropriate stream
|
| 75 |
+
(stdin for reading, stdout for writing) that doesn't close on context exit.
|
| 76 |
+
For regular paths, behaves like the standard Path.open().
|
| 77 |
+
"""
|
| 78 |
+
if self.is_stdio:
|
| 79 |
+
is_binary = "b" in mode
|
| 80 |
+
is_write = "w" in mode or "a" in mode
|
| 81 |
+
# Always get the buffer stream
|
| 82 |
+
buffer_stream = sys.stdout.buffer if is_write else sys.stdin.buffer
|
| 83 |
+
if is_binary:
|
| 84 |
+
stream = _NonClosingIOWrapper(buffer_stream)
|
| 85 |
+
else:
|
| 86 |
+
# For text mode, wrap the binary stream with TextIOWrapper
|
| 87 |
+
text_stream = io.TextIOWrapper(
|
| 88 |
+
buffer_stream,
|
| 89 |
+
encoding=encoding or "utf-8",
|
| 90 |
+
errors=errors or "strict",
|
| 91 |
+
newline=newline,
|
| 92 |
+
)
|
| 93 |
+
stream = _NonClosingIOWrapper(text_stream, detach_on_exit=True)
|
| 94 |
+
return stream
|
| 95 |
+
return super().open(mode, buffering, encoding, errors, newline)
|
| 96 |
+
|
| 97 |
+
def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str:
|
| 98 |
+
"""Read entire contents as text."""
|
| 99 |
+
if self.is_stdio:
|
| 100 |
+
wrapper = io.TextIOWrapper(
|
| 101 |
+
sys.stdin.buffer,
|
| 102 |
+
encoding=encoding or "utf-8",
|
| 103 |
+
errors=errors or "strict",
|
| 104 |
+
newline=newline,
|
| 105 |
+
)
|
| 106 |
+
try:
|
| 107 |
+
return wrapper.read()
|
| 108 |
+
finally:
|
| 109 |
+
wrapper.detach() # Detach without closing stdin.buffer
|
| 110 |
+
# newline parameter added in Python 3.13
|
| 111 |
+
if sys.version_info >= (3, 13):
|
| 112 |
+
return super().read_text(encoding=encoding, errors=errors, newline=newline)
|
| 113 |
+
else:
|
| 114 |
+
return super().read_text(encoding=encoding, errors=errors)
|
| 115 |
+
|
| 116 |
+
def read_bytes(self) -> bytes:
|
| 117 |
+
"""Read entire contents as bytes."""
|
| 118 |
+
if self.is_stdio:
|
| 119 |
+
return sys.stdin.buffer.read()
|
| 120 |
+
return super().read_bytes()
|
| 121 |
+
|
| 122 |
+
def write_text(
|
| 123 |
+
self,
|
| 124 |
+
data: str,
|
| 125 |
+
encoding: str | None = None,
|
| 126 |
+
errors: str | None = None,
|
| 127 |
+
newline: str | None = None,
|
| 128 |
+
) -> int:
|
| 129 |
+
"""Write text data."""
|
| 130 |
+
if self.is_stdio:
|
| 131 |
+
wrapper = io.TextIOWrapper(
|
| 132 |
+
sys.stdout.buffer,
|
| 133 |
+
encoding=encoding or "utf-8",
|
| 134 |
+
errors=errors or "strict",
|
| 135 |
+
newline=newline,
|
| 136 |
+
)
|
| 137 |
+
try:
|
| 138 |
+
wrapper.write(data)
|
| 139 |
+
wrapper.flush()
|
| 140 |
+
# TextIOWrapper doesn't return bytes written, so calculate from encoded data
|
| 141 |
+
# Apply same newline translation that TextIOWrapper does
|
| 142 |
+
if newline is None or newline == "":
|
| 143 |
+
encoded_data = data
|
| 144 |
+
else:
|
| 145 |
+
encoded_data = data.replace("\n", newline)
|
| 146 |
+
return len(encoded_data.encode(encoding or "utf-8", errors or "strict"))
|
| 147 |
+
finally:
|
| 148 |
+
wrapper.detach() # Detach without closing stdout.buffer
|
| 149 |
+
return super().write_text(data, encoding=encoding, errors=errors, newline=newline)
|
| 150 |
+
|
| 151 |
+
def write_bytes(self, data: "Buffer") -> int:
|
| 152 |
+
"""Write binary data."""
|
| 153 |
+
if self.is_stdio:
|
| 154 |
+
return sys.stdout.buffer.write(data)
|
| 155 |
+
return super().write_bytes(data)
|
.venv/lib/python3.10/site-packages/cyclopts/_result_action.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from collections.abc import Callable, Iterable
|
| 3 |
+
from typing import Any, Literal, cast
|
| 4 |
+
|
| 5 |
+
from cyclopts.utils import is_iterable
|
| 6 |
+
|
| 7 |
+
ResultActionSingle = (
|
| 8 |
+
Literal[
|
| 9 |
+
"return_value",
|
| 10 |
+
"call_if_callable",
|
| 11 |
+
"print_non_int_return_int_as_exit_code",
|
| 12 |
+
"print_str_return_int_as_exit_code",
|
| 13 |
+
"print_str_return_zero",
|
| 14 |
+
"print_non_none_return_int_as_exit_code",
|
| 15 |
+
"print_non_none_return_zero",
|
| 16 |
+
"return_int_as_exit_code_else_zero",
|
| 17 |
+
"print_non_int_sys_exit",
|
| 18 |
+
"sys_exit",
|
| 19 |
+
"return_none",
|
| 20 |
+
"return_zero",
|
| 21 |
+
"print_return_zero",
|
| 22 |
+
"sys_exit_zero",
|
| 23 |
+
"print_sys_exit_zero",
|
| 24 |
+
]
|
| 25 |
+
| Callable[[Any], Any]
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
ResultAction = ResultActionSingle | Iterable[ResultActionSingle]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def handle_result_action(
|
| 32 |
+
result: Any,
|
| 33 |
+
action: ResultAction,
|
| 34 |
+
print_fn: Callable[[Any], None],
|
| 35 |
+
) -> Any:
|
| 36 |
+
"""Handle command result based on result_action.
|
| 37 |
+
|
| 38 |
+
When ``action`` is a sequence, actions are applied left-to-right in a pipeline,
|
| 39 |
+
where each action receives the result of the previous action. For example,
|
| 40 |
+
with ``result_action=[uppercase, add_greeting]``:
|
| 41 |
+
|
| 42 |
+
result → uppercase(result) → add_greeting(uppercase(result))
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
result : Any
|
| 47 |
+
The command's return value.
|
| 48 |
+
action : ResultAction
|
| 49 |
+
The action (or sequence of actions) to take with the result.
|
| 50 |
+
If a sequence, actions are chained left-to-right.
|
| 51 |
+
print_fn : Callable[[Any], None]
|
| 52 |
+
Function to call to print output (e.g., console.print).
|
| 53 |
+
|
| 54 |
+
Returns
|
| 55 |
+
-------
|
| 56 |
+
Any
|
| 57 |
+
Processed result based on action (may call sys.exit() and not return).
|
| 58 |
+
"""
|
| 59 |
+
if is_iterable(action):
|
| 60 |
+
for single_action in cast(Iterable[ResultActionSingle], action):
|
| 61 |
+
result = handle_result_action(result, single_action, print_fn)
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
if callable(action):
|
| 65 |
+
return action(result)
|
| 66 |
+
|
| 67 |
+
match action:
|
| 68 |
+
case "print_non_int_sys_exit":
|
| 69 |
+
if isinstance(result, bool):
|
| 70 |
+
sys.exit(0 if result else 1)
|
| 71 |
+
elif isinstance(result, int):
|
| 72 |
+
sys.exit(result)
|
| 73 |
+
elif result is not None:
|
| 74 |
+
print_fn(result)
|
| 75 |
+
sys.exit(0)
|
| 76 |
+
else:
|
| 77 |
+
sys.exit(0)
|
| 78 |
+
case "return_value":
|
| 79 |
+
return result
|
| 80 |
+
case "call_if_callable":
|
| 81 |
+
if callable(result):
|
| 82 |
+
return result()
|
| 83 |
+
return result
|
| 84 |
+
case "sys_exit":
|
| 85 |
+
if isinstance(result, bool):
|
| 86 |
+
sys.exit(0 if result else 1)
|
| 87 |
+
elif isinstance(result, int):
|
| 88 |
+
sys.exit(result)
|
| 89 |
+
else:
|
| 90 |
+
sys.exit(0)
|
| 91 |
+
case "print_non_int_return_int_as_exit_code":
|
| 92 |
+
if isinstance(result, bool):
|
| 93 |
+
return 0 if result else 1
|
| 94 |
+
elif isinstance(result, int):
|
| 95 |
+
return result
|
| 96 |
+
elif result is not None:
|
| 97 |
+
print_fn(result)
|
| 98 |
+
return 0
|
| 99 |
+
else:
|
| 100 |
+
return 0
|
| 101 |
+
case "print_str_return_int_as_exit_code":
|
| 102 |
+
if isinstance(result, str):
|
| 103 |
+
print_fn(result)
|
| 104 |
+
return 0
|
| 105 |
+
elif isinstance(result, bool):
|
| 106 |
+
return 0 if result else 1
|
| 107 |
+
elif isinstance(result, int):
|
| 108 |
+
return result
|
| 109 |
+
else:
|
| 110 |
+
return 0
|
| 111 |
+
case "print_str_return_zero":
|
| 112 |
+
if isinstance(result, str):
|
| 113 |
+
print_fn(result)
|
| 114 |
+
return 0
|
| 115 |
+
case "print_non_none_return_int_as_exit_code":
|
| 116 |
+
if result is not None:
|
| 117 |
+
print_fn(result)
|
| 118 |
+
if isinstance(result, bool):
|
| 119 |
+
return 0 if result else 1
|
| 120 |
+
elif isinstance(result, int):
|
| 121 |
+
return result
|
| 122 |
+
return 0
|
| 123 |
+
case "print_non_none_return_zero":
|
| 124 |
+
if result is not None:
|
| 125 |
+
print_fn(result)
|
| 126 |
+
return 0
|
| 127 |
+
case "return_int_as_exit_code_else_zero":
|
| 128 |
+
if isinstance(result, bool):
|
| 129 |
+
return 0 if result else 1
|
| 130 |
+
elif isinstance(result, int):
|
| 131 |
+
return result
|
| 132 |
+
else:
|
| 133 |
+
return 0
|
| 134 |
+
case "return_none":
|
| 135 |
+
return None
|
| 136 |
+
case "return_zero":
|
| 137 |
+
return 0
|
| 138 |
+
case "print_return_zero":
|
| 139 |
+
print_fn(result)
|
| 140 |
+
return 0
|
| 141 |
+
case "sys_exit_zero":
|
| 142 |
+
sys.exit(0)
|
| 143 |
+
case "print_sys_exit_zero":
|
| 144 |
+
print_fn(result)
|
| 145 |
+
sys.exit(0)
|
| 146 |
+
case _:
|
| 147 |
+
raise ValueError
|
.venv/lib/python3.10/site-packages/cyclopts/_run.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import sys
|
| 3 |
+
from collections.abc import Callable, Coroutine
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload
|
| 6 |
+
|
| 7 |
+
from cyclopts._result_action import ResultAction
|
| 8 |
+
|
| 9 |
+
if sys.version_info < (3, 11): # pragma: no cover
|
| 10 |
+
from typing_extensions import assert_never
|
| 11 |
+
else: # pragma: no cover
|
| 12 |
+
from typing import assert_never
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING:
|
| 15 |
+
from cyclopts.core import App
|
| 16 |
+
|
| 17 |
+
V = TypeVar("V")
|
| 18 |
+
|
| 19 |
+
# App will be lazily imported to avoid circular imports
|
| 20 |
+
App = None # type: ignore[assignment]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _run_maybe_async_command(
|
| 24 |
+
command: Callable,
|
| 25 |
+
bound: inspect.BoundArguments | None = None,
|
| 26 |
+
backend: Literal["asyncio", "trio"] = "asyncio",
|
| 27 |
+
):
|
| 28 |
+
"""Run a command, handling both sync and async cases.
|
| 29 |
+
|
| 30 |
+
If the command is async, an async context will be created to run it.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
command : Callable
|
| 35 |
+
The command to execute.
|
| 36 |
+
bound : inspect.BoundArguments | None
|
| 37 |
+
Bound arguments for the command. If None, command is called with no arguments.
|
| 38 |
+
backend : Literal["asyncio", "trio"]
|
| 39 |
+
The async backend to use if the command is async.
|
| 40 |
+
|
| 41 |
+
Returns
|
| 42 |
+
-------
|
| 43 |
+
return_value: Any
|
| 44 |
+
The value the command function returns.
|
| 45 |
+
"""
|
| 46 |
+
if not inspect.iscoroutinefunction(command):
|
| 47 |
+
if bound is None:
|
| 48 |
+
return command()
|
| 49 |
+
else:
|
| 50 |
+
return command(*bound.args, **bound.kwargs)
|
| 51 |
+
|
| 52 |
+
if backend == "asyncio":
|
| 53 |
+
import asyncio
|
| 54 |
+
|
| 55 |
+
if bound is None:
|
| 56 |
+
return asyncio.run(command())
|
| 57 |
+
else:
|
| 58 |
+
return asyncio.run(command(*bound.args, **bound.kwargs))
|
| 59 |
+
elif backend == "trio":
|
| 60 |
+
import trio
|
| 61 |
+
|
| 62 |
+
if bound is None:
|
| 63 |
+
return trio.run(command)
|
| 64 |
+
else:
|
| 65 |
+
return trio.run(partial(command, *bound.args, **bound.kwargs))
|
| 66 |
+
else: # pragma: no cover
|
| 67 |
+
assert_never(backend)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@overload
|
| 71 |
+
def run(callable: Callable[..., Coroutine[None, None, V]], /, *, result_action: Literal["return_value"]) -> V: ...
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@overload
|
| 75 |
+
def run(callable: Callable[..., V], /, *, result_action: Literal["return_value"]) -> V: ...
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@overload
|
| 79 |
+
def run(
|
| 80 |
+
callable: Callable[..., Coroutine[None, None, Any]], /, *, result_action: ResultAction | None = None
|
| 81 |
+
) -> Any: ...
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@overload
|
| 85 |
+
def run(callable: Callable[..., Any], /, *, result_action: ResultAction | None = None) -> Any: ...
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def run(callable, /, *, result_action: ResultAction | None = None):
|
| 89 |
+
"""Run the given callable as a CLI command.
|
| 90 |
+
|
| 91 |
+
The callable may also be a coroutine function.
|
| 92 |
+
This function is syntax sugar for very simple use cases, and is roughly equivalent to:
|
| 93 |
+
|
| 94 |
+
.. code-block:: python
|
| 95 |
+
|
| 96 |
+
from cyclopts import App
|
| 97 |
+
|
| 98 |
+
app = App()
|
| 99 |
+
app.default(callable)
|
| 100 |
+
app()
|
| 101 |
+
|
| 102 |
+
Parameters
|
| 103 |
+
----------
|
| 104 |
+
callable
|
| 105 |
+
The function to execute as a CLI command.
|
| 106 |
+
result_action
|
| 107 |
+
How to handle the command's return value. If not specified, uses the default
|
| 108 |
+
``"print_non_int_sys_exit"`` which calls :func:`sys.exit` with the appropriate code.
|
| 109 |
+
Can be set to ``"return_value"`` to return the result directly for testing/embedding.
|
| 110 |
+
|
| 111 |
+
Example usage:
|
| 112 |
+
|
| 113 |
+
.. code-block:: python
|
| 114 |
+
|
| 115 |
+
import cyclopts
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def main(name: str, age: int):
|
| 119 |
+
print(f"Hello {name}, you are {age} years old.")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
cyclopts.run(main)
|
| 123 |
+
"""
|
| 124 |
+
global App
|
| 125 |
+
if App is None:
|
| 126 |
+
from cyclopts.core import App as _App
|
| 127 |
+
|
| 128 |
+
App = _App
|
| 129 |
+
|
| 130 |
+
app = App(result_action=result_action)
|
| 131 |
+
app.default(callable)
|
| 132 |
+
return app()
|
.venv/lib/python3.10/site-packages/cyclopts/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# file generated by vcs-versioning
|
| 2 |
+
# don't change, don't track in version control
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
"__version__",
|
| 7 |
+
"__version_tuple__",
|
| 8 |
+
"version",
|
| 9 |
+
"version_tuple",
|
| 10 |
+
"__commit_id__",
|
| 11 |
+
"commit_id",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
version: str
|
| 15 |
+
__version__: str
|
| 16 |
+
__version_tuple__: tuple[int | str, ...]
|
| 17 |
+
version_tuple: tuple[int | str, ...]
|
| 18 |
+
commit_id: str | None
|
| 19 |
+
__commit_id__: str | None
|
| 20 |
+
|
| 21 |
+
__version__ = version = '4.11.0'
|
| 22 |
+
__version_tuple__ = version_tuple = (4, 11, 0)
|
| 23 |
+
|
| 24 |
+
__commit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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import sys
|
| 3 |
+
import typing
|
| 4 |
+
from collections.abc import Iterable, Sequence
|
| 5 |
+
from enum import Flag
|
| 6 |
+
from types import UnionType
|
| 7 |
+
from typing import Annotated, Any, Union, get_args, get_origin
|
| 8 |
+
|
| 9 |
+
import attrs
|
| 10 |
+
|
| 11 |
+
from cyclopts.utils import is_class_and_subclass
|
| 12 |
+
|
| 13 |
+
if sys.version_info < (3, 11): # pragma: no cover
|
| 14 |
+
from typing_extensions import NotRequired, Required
|
| 15 |
+
else: # pragma: no cover
|
| 16 |
+
from typing import NotRequired, Required
|
| 17 |
+
|
| 18 |
+
if sys.version_info >= (3, 12): # pragma: no cover
|
| 19 |
+
from typing import TypeAliasType
|
| 20 |
+
else: # pragma: no cover
|
| 21 |
+
TypeAliasType = None
|
| 22 |
+
|
| 23 |
+
# from types import NoneType is available >=3.10
|
| 24 |
+
NoneType = type(None)
|
| 25 |
+
AnnotatedType = type(Annotated[int, 0])
|
| 26 |
+
|
| 27 |
+
ITERABLE_TYPES = {
|
| 28 |
+
Iterable,
|
| 29 |
+
typing.Sequence,
|
| 30 |
+
Sequence,
|
| 31 |
+
frozenset,
|
| 32 |
+
list,
|
| 33 |
+
set,
|
| 34 |
+
tuple,
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def is_nonetype(hint):
|
| 39 |
+
return hint is NoneType
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def is_union(type_: type | None) -> bool:
|
| 43 |
+
"""Checks if a type is a union."""
|
| 44 |
+
# Direct checks are faster than checking if the type is in a set that contains the union-types.
|
| 45 |
+
if type_ is Union or type_ is UnionType:
|
| 46 |
+
return True
|
| 47 |
+
|
| 48 |
+
# The ``get_origin`` call is relatively expensive, so we'll check common types
|
| 49 |
+
# that are passed in here to see if we can avoid calling ``get_origin``.
|
| 50 |
+
if type_ is str or type_ is int or type_ is float or type_ is bool or is_annotated(type_):
|
| 51 |
+
return False
|
| 52 |
+
origin = get_origin(type_)
|
| 53 |
+
return origin is Union or origin is UnionType
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def is_pydantic(hint) -> bool:
|
| 57 |
+
return hasattr(hint, "__pydantic_core_schema__")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_pydantic_secret(hint) -> bool:
|
| 61 |
+
"""Check if a type is a Pydantic secret type (SecretStr, SecretBytes, Secret, etc.)."""
|
| 62 |
+
return (
|
| 63 |
+
hasattr(hint, "__module__")
|
| 64 |
+
and hint.__module__ == "pydantic.types"
|
| 65 |
+
and hasattr(hint, "get_secret_value")
|
| 66 |
+
and callable(getattr(hint, "get_secret_value", None))
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def is_dataclass(hint) -> bool:
|
| 71 |
+
return hasattr(hint, "__dataclass_fields__")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def is_namedtuple(hint) -> bool:
|
| 75 |
+
return is_class_and_subclass(hint, tuple) and hasattr(hint, "_fields")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def is_attrs(hint) -> bool:
|
| 79 |
+
return attrs.has(hint)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def is_enum_flag(hint) -> bool:
|
| 83 |
+
"""Check if a type hint is an enum.Flag subclass."""
|
| 84 |
+
return is_class_and_subclass(hint, Flag)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def is_annotated(hint) -> bool:
|
| 88 |
+
return type(hint) is AnnotatedType
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def is_iterable_type(hint) -> bool:
|
| 92 |
+
"""Check if a type hint is a collection/iterable type (list, set, tuple, etc.).
|
| 93 |
+
|
| 94 |
+
Handles Annotated, Optional, TypeAlias, and NewType wrappers.
|
| 95 |
+
"""
|
| 96 |
+
hint = resolve(hint)
|
| 97 |
+
origin = get_origin(hint)
|
| 98 |
+
return is_class_and_subclass(origin, tuple(ITERABLE_TYPES))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def contains_hint(hint, target_type) -> bool:
|
| 102 |
+
"""Indicates if ``target_type`` is in a possibly annotated/unioned ``hint``.
|
| 103 |
+
|
| 104 |
+
E.g. ``contains_hint(Union[int, str], str) == True``
|
| 105 |
+
"""
|
| 106 |
+
hint = resolve(hint)
|
| 107 |
+
if is_union(hint):
|
| 108 |
+
return any(contains_hint(x, target_type) for x in get_args(hint))
|
| 109 |
+
else:
|
| 110 |
+
return is_class_and_subclass(hint, target_type)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def is_typeddict(hint) -> bool:
|
| 114 |
+
"""Determine if a type annotation is a TypedDict.
|
| 115 |
+
|
| 116 |
+
This is surprisingly hard! Modified from Beartype's implementation:
|
| 117 |
+
|
| 118 |
+
https://github.com/beartype/beartype/blob/main/beartype/_util/hint/pep/proposal/utilpep589.py
|
| 119 |
+
"""
|
| 120 |
+
hint = resolve(hint)
|
| 121 |
+
if is_union(hint):
|
| 122 |
+
return any(is_typeddict(x) for x in get_args(hint))
|
| 123 |
+
|
| 124 |
+
if not is_class_and_subclass(hint, dict):
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
return (
|
| 128 |
+
hasattr(hint, "__annotations__")
|
| 129 |
+
and hasattr(hint, "__total__")
|
| 130 |
+
and hasattr(hint, "__required_keys__")
|
| 131 |
+
and hasattr(hint, "__optional_keys__")
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def resolve(
|
| 136 |
+
type_: Any,
|
| 137 |
+
) -> type:
|
| 138 |
+
"""Perform all simplifying resolutions."""
|
| 139 |
+
if type_ is inspect.Parameter.empty:
|
| 140 |
+
return str
|
| 141 |
+
|
| 142 |
+
type_prev = None
|
| 143 |
+
while type_ != type_prev:
|
| 144 |
+
type_prev = type_
|
| 145 |
+
type_ = resolve_type_alias(type_)
|
| 146 |
+
type_ = resolve_annotated(type_)
|
| 147 |
+
type_ = resolve_optional(type_)
|
| 148 |
+
type_ = resolve_required(type_)
|
| 149 |
+
type_ = resolve_new_type(type_)
|
| 150 |
+
return type_
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def resolve_optional(type_: Any) -> Any:
|
| 154 |
+
"""Only resolves Union's of None + one other type (i.e. Optional)."""
|
| 155 |
+
type_ = resolve_type_alias(type_)
|
| 156 |
+
# Python will automatically flatten out nested unions when possible.
|
| 157 |
+
# So we don't need to loop over resolution.
|
| 158 |
+
if not is_union(type_):
|
| 159 |
+
return type_
|
| 160 |
+
|
| 161 |
+
non_none_types = [t for t in get_args(type_) if t is not NoneType]
|
| 162 |
+
if not non_none_types: # pragma: no cover
|
| 163 |
+
# This should never happen; python simplifies:
|
| 164 |
+
# ``Union[None, None] -> NoneType``
|
| 165 |
+
raise ValueError("Union type cannot be all NoneType")
|
| 166 |
+
elif len(non_none_types) == 1:
|
| 167 |
+
type_ = non_none_types[0]
|
| 168 |
+
elif len(non_none_types) > 1:
|
| 169 |
+
return Union[tuple(resolve_optional(x) for x in non_none_types)] # pyright: ignore # noqa: UP007
|
| 170 |
+
else:
|
| 171 |
+
raise NotImplementedError
|
| 172 |
+
|
| 173 |
+
return type_
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def resolve_annotated(type_: Any) -> type:
|
| 177 |
+
type_ = resolve_type_alias(type_)
|
| 178 |
+
if is_annotated(type_):
|
| 179 |
+
type_ = get_args(type_)[0]
|
| 180 |
+
return type_
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def get_annotated_discriminator(annotation) -> Any:
|
| 184 |
+
"""Return the ``discriminator`` metadata from an ``Annotated[...]`` hint, else ``None``.
|
| 185 |
+
|
| 186 |
+
Only inspects ``Annotated`` hints — for other parameterized types (``list[X]``,
|
| 187 |
+
``dict[K, V]``, etc.) this returns ``None`` so that an incidental
|
| 188 |
+
``.discriminator`` attribute on a type parameter cannot spuriously match.
|
| 189 |
+
"""
|
| 190 |
+
if not is_annotated(annotation):
|
| 191 |
+
return None
|
| 192 |
+
for meta in get_args(annotation)[1:]:
|
| 193 |
+
try:
|
| 194 |
+
return meta.discriminator
|
| 195 |
+
except AttributeError:
|
| 196 |
+
pass
|
| 197 |
+
return None
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def resolve_required(type_: Any) -> type:
|
| 201 |
+
if get_origin(type_) in (Required, NotRequired):
|
| 202 |
+
type_ = get_args(type_)[0]
|
| 203 |
+
return type_
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def resolve_new_type(type_: Any) -> type:
|
| 207 |
+
try:
|
| 208 |
+
return resolve_new_type(type_.__supertype__)
|
| 209 |
+
except AttributeError:
|
| 210 |
+
return type_
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def resolve_type_alias(type_: Any) -> Any:
|
| 214 |
+
"""Resolve TypeAliasType (Python 3.12+ 'type' statement) to its underlying type."""
|
| 215 |
+
if TypeAliasType is not None and isinstance(type_, TypeAliasType):
|
| 216 |
+
return type_.__value__
|
| 217 |
+
return type_
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def get_hint_name(hint) -> str:
|
| 221 |
+
if isinstance(hint, str):
|
| 222 |
+
return hint
|
| 223 |
+
if is_nonetype(hint):
|
| 224 |
+
return "None"
|
| 225 |
+
if hint is Any:
|
| 226 |
+
return "Any"
|
| 227 |
+
if is_union(hint):
|
| 228 |
+
return "|".join(get_hint_name(arg) for arg in get_args(hint))
|
| 229 |
+
if origin := get_origin(hint):
|
| 230 |
+
out = get_hint_name(origin)
|
| 231 |
+
if args := get_args(hint):
|
| 232 |
+
out += "[" + ", ".join(get_hint_name(arg) for arg in args) + "]"
|
| 233 |
+
return out
|
| 234 |
+
if hasattr(hint, "__name__"):
|
| 235 |
+
return hint.__name__
|
| 236 |
+
if getattr(hint, "_name", None) is not None:
|
| 237 |
+
return hint._name
|
| 238 |
+
return str(hint)
|
.venv/lib/python3.10/site-packages/cyclopts/app_stack.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
from itertools import chain
|
| 4 |
+
from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
|
| 5 |
+
|
| 6 |
+
from cyclopts.group_extractors import inverse_groups_from_app
|
| 7 |
+
from cyclopts.parameter import Parameter
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from cyclopts.core import App
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
V = TypeVar("V")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AppStack:
|
| 17 |
+
def __init__(self, app):
|
| 18 |
+
# the ``stack`` is guaranteed to have the self-referencing app at the top of the stack.
|
| 19 |
+
self.stack: list[list[App]] = [[app]]
|
| 20 |
+
# Stack of overrides passed to parse_args/call that should be propagated
|
| 21 |
+
self.overrides_stack: list[dict[str, Any]] = [{}]
|
| 22 |
+
|
| 23 |
+
@contextmanager
|
| 24 |
+
def __call__(self, apps: Sequence["App"] | Sequence[str], overrides: dict[str, Any] | None = None):
|
| 25 |
+
# set `overrides` default-values with current overrides so that they properly propagate down the call-stack.
|
| 26 |
+
overrides = self.overrides | (overrides or {})
|
| 27 |
+
|
| 28 |
+
self.overrides_stack.append(overrides or {})
|
| 29 |
+
|
| 30 |
+
if not apps:
|
| 31 |
+
try:
|
| 32 |
+
yield
|
| 33 |
+
finally:
|
| 34 |
+
self.overrides_stack.pop()
|
| 35 |
+
return
|
| 36 |
+
|
| 37 |
+
# Convert strings to Apps if needed
|
| 38 |
+
if isinstance(apps[0], str):
|
| 39 |
+
str_apps = cast(Sequence[str], apps)
|
| 40 |
+
_, apps_tuple, _ = self.stack[0][0].parse_commands(str_apps, include_parent_meta=True)
|
| 41 |
+
resolved_apps: list[App] = list(apps_tuple)
|
| 42 |
+
else:
|
| 43 |
+
resolved_apps = cast(list["App"], list(apps))
|
| 44 |
+
del apps
|
| 45 |
+
|
| 46 |
+
if not resolved_apps:
|
| 47 |
+
try:
|
| 48 |
+
yield
|
| 49 |
+
finally:
|
| 50 |
+
self.overrides_stack.pop()
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
so_far = []
|
| 54 |
+
app_ids = {id(app) for app in resolved_apps}
|
| 55 |
+
for app in resolved_apps:
|
| 56 |
+
if app._meta_parent is None:
|
| 57 |
+
# Do not include the prior meta-app.
|
| 58 |
+
while so_far and so_far[-1]._meta_parent is not None:
|
| 59 |
+
so_far.pop()
|
| 60 |
+
|
| 61 |
+
so_far.append(app)
|
| 62 |
+
app.app_stack.stack.append(so_far.copy())
|
| 63 |
+
# Also push the overrides onto this app's stack
|
| 64 |
+
app.app_stack.overrides_stack.append(overrides or {})
|
| 65 |
+
|
| 66 |
+
# Also traverse the app's meta app
|
| 67 |
+
meta_app = app
|
| 68 |
+
while (meta_app := meta_app._meta) is not None:
|
| 69 |
+
if id(meta_app) in app_ids:
|
| 70 |
+
# It will be handled conventionally
|
| 71 |
+
continue
|
| 72 |
+
meta_subapps = so_far.copy()
|
| 73 |
+
meta_subapps.append(meta_app)
|
| 74 |
+
meta_app.app_stack.stack.append(meta_subapps)
|
| 75 |
+
# Also push the overrides onto the meta app's stack
|
| 76 |
+
meta_app.app_stack.overrides_stack.append(overrides or {})
|
| 77 |
+
try:
|
| 78 |
+
yield
|
| 79 |
+
finally:
|
| 80 |
+
for app in resolved_apps:
|
| 81 |
+
app.app_stack.stack.pop()
|
| 82 |
+
app.app_stack.overrides_stack.pop()
|
| 83 |
+
# Also pop from meta apps
|
| 84 |
+
meta_app = app
|
| 85 |
+
while (meta_app := meta_app._meta) is not None:
|
| 86 |
+
if id(meta_app) in app_ids:
|
| 87 |
+
continue
|
| 88 |
+
meta_app.app_stack.stack.pop()
|
| 89 |
+
meta_app.app_stack.overrides_stack.pop()
|
| 90 |
+
# Pop overrides from stack
|
| 91 |
+
self.overrides_stack.pop()
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def overrides(self) -> dict:
|
| 95 |
+
out = {}
|
| 96 |
+
for overrides_frame in reversed(self.overrides_stack):
|
| 97 |
+
for key, value in overrides_frame.items():
|
| 98 |
+
if value is not None:
|
| 99 |
+
out.setdefault(key, value)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def default_parameter(self) -> Parameter:
|
| 104 |
+
"""default_parameter has special resolution since it needs to include the command groups in the derivation."""
|
| 105 |
+
cparams = []
|
| 106 |
+
for child_app in chain.from_iterable(self.stack):
|
| 107 |
+
if child_app._meta_parent:
|
| 108 |
+
continue
|
| 109 |
+
cparams.extend([group.default_parameter for group in child_app.app_stack.command_groups])
|
| 110 |
+
cparams.append(child_app.default_parameter)
|
| 111 |
+
|
| 112 |
+
return Parameter.combine(*cparams)
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def current_frame(self) -> list["App"]:
|
| 116 |
+
if not self.stack:
|
| 117 |
+
raise ValueError
|
| 118 |
+
|
| 119 |
+
return self.stack[-1]
|
| 120 |
+
|
| 121 |
+
@overload
|
| 122 |
+
def resolve(self, attribute: str) -> Any: ...
|
| 123 |
+
|
| 124 |
+
@overload
|
| 125 |
+
def resolve(self, attribute: str, override: V) -> V: ...
|
| 126 |
+
|
| 127 |
+
@overload
|
| 128 |
+
def resolve(self, attribute: str, override: V | None, fallback: V) -> V: ...
|
| 129 |
+
|
| 130 |
+
@overload
|
| 131 |
+
def resolve(self, attribute: str, override: V | None = None, *, fallback: V) -> V: ...
|
| 132 |
+
|
| 133 |
+
def resolve(self, attribute: str, override: V | None = None, fallback: V | None = None) -> V | None:
|
| 134 |
+
"""Resolve an attribute from the App hierarchy."""
|
| 135 |
+
if override is not None:
|
| 136 |
+
return override
|
| 137 |
+
|
| 138 |
+
# Check if we have a stored override from parent invocations (most recent first)
|
| 139 |
+
for overrides_frame in reversed(self.overrides_stack):
|
| 140 |
+
if attribute in overrides_frame:
|
| 141 |
+
value = overrides_frame[attribute]
|
| 142 |
+
if value is not None:
|
| 143 |
+
return value
|
| 144 |
+
|
| 145 |
+
# `reversed` so that "closer" apps have higher priority.
|
| 146 |
+
for app in reversed(list(chain.from_iterable(self.stack))):
|
| 147 |
+
result = getattr(app, attribute)
|
| 148 |
+
if result is not None:
|
| 149 |
+
return result
|
| 150 |
+
|
| 151 |
+
# Check parenting meta app(s)
|
| 152 |
+
meta_app = app
|
| 153 |
+
while (meta_app := meta_app._meta_parent) is not None:
|
| 154 |
+
result = getattr(meta_app, attribute)
|
| 155 |
+
if result is not None:
|
| 156 |
+
return result
|
| 157 |
+
|
| 158 |
+
return fallback
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def command_groups(self) -> list:
|
| 162 |
+
command_app = self.current_frame[-1]
|
| 163 |
+
try:
|
| 164 |
+
current_app: App | None = self.current_frame[-2]
|
| 165 |
+
except IndexError:
|
| 166 |
+
current_app = None
|
| 167 |
+
|
| 168 |
+
while current_app is not None:
|
| 169 |
+
try:
|
| 170 |
+
return next(x for x in inverse_groups_from_app(current_app) if x[0] is command_app)[1]
|
| 171 |
+
except StopIteration:
|
| 172 |
+
current_app = current_app._meta_parent
|
| 173 |
+
return []
|
.venv/lib/python3.10/site-packages/cyclopts/argument/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Argument and ArgumentCollection classes for CLI parsing."""
|
| 2 |
+
|
| 3 |
+
from cyclopts.token import Token
|
| 4 |
+
|
| 5 |
+
from ._argument import Argument
|
| 6 |
+
from ._collection import (
|
| 7 |
+
ArgumentCollection,
|
| 8 |
+
_resolve_groups_from_callable,
|
| 9 |
+
update_argument_collection,
|
| 10 |
+
)
|
| 11 |
+
from .utils import get_choices_from_hint, resolve_parameter_name
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"Argument",
|
| 15 |
+
"ArgumentCollection",
|
| 16 |
+
"Token",
|
| 17 |
+
"_resolve_groups_from_callable",
|
| 18 |
+
"get_choices_from_hint",
|
| 19 |
+
"resolve_parameter_name",
|
| 20 |
+
"update_argument_collection",
|
| 21 |
+
]
|
.venv/lib/python3.10/site-packages/cyclopts/argument/_argument.py
ADDED
|
@@ -0,0 +1,1178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Argument class and related functionality."""
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import json
|
| 5 |
+
import operator
|
| 6 |
+
import re
|
| 7 |
+
import sys
|
| 8 |
+
from collections.abc import Callable, Sequence
|
| 9 |
+
from contextlib import suppress
|
| 10 |
+
from functools import partial, reduce
|
| 11 |
+
from typing import TYPE_CHECKING, Any, get_args, get_origin
|
| 12 |
+
|
| 13 |
+
from attrs import define, field
|
| 14 |
+
|
| 15 |
+
from cyclopts._convert import (
|
| 16 |
+
_validate_json_extra_keys,
|
| 17 |
+
convert,
|
| 18 |
+
instantiate_from_dict,
|
| 19 |
+
token_count,
|
| 20 |
+
)
|
| 21 |
+
from cyclopts.annotations import (
|
| 22 |
+
ITERABLE_TYPES,
|
| 23 |
+
contains_hint,
|
| 24 |
+
get_annotated_discriminator,
|
| 25 |
+
is_attrs,
|
| 26 |
+
is_dataclass,
|
| 27 |
+
is_enum_flag,
|
| 28 |
+
is_namedtuple,
|
| 29 |
+
is_nonetype,
|
| 30 |
+
is_pydantic,
|
| 31 |
+
is_typeddict,
|
| 32 |
+
is_union,
|
| 33 |
+
resolve,
|
| 34 |
+
resolve_annotated,
|
| 35 |
+
resolve_optional,
|
| 36 |
+
)
|
| 37 |
+
from cyclopts.exceptions import (
|
| 38 |
+
CoercionError,
|
| 39 |
+
CycloptsError,
|
| 40 |
+
MissingArgumentError,
|
| 41 |
+
MixedArgumentError,
|
| 42 |
+
RepeatArgumentError,
|
| 43 |
+
ValidationError,
|
| 44 |
+
)
|
| 45 |
+
from cyclopts.field_info import (
|
| 46 |
+
FieldInfo,
|
| 47 |
+
_attrs_field_infos,
|
| 48 |
+
_generic_class_field_infos,
|
| 49 |
+
_pydantic_field_infos,
|
| 50 |
+
_typed_dict_field_infos,
|
| 51 |
+
get_field_infos,
|
| 52 |
+
signature_parameters,
|
| 53 |
+
)
|
| 54 |
+
from cyclopts.parameter import ITERATIVE_BOOL_IMPLICIT_VALUE, Parameter
|
| 55 |
+
from cyclopts.token import Token
|
| 56 |
+
from cyclopts.utils import UNSET, grouper, is_builtin, parse_version
|
| 57 |
+
|
| 58 |
+
from .utils import (
|
| 59 |
+
enum_flag_from_dict,
|
| 60 |
+
get_choices_from_hint,
|
| 61 |
+
missing_keys_factory,
|
| 62 |
+
startswith,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if TYPE_CHECKING:
|
| 66 |
+
from cyclopts.argument._collection import ArgumentCollection
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@define(kw_only=True)
|
| 70 |
+
class Argument:
|
| 71 |
+
"""Encapsulates functionality and additional contextual information for parsing a parameter.
|
| 72 |
+
|
| 73 |
+
An argument is defined as anything that would have its own entry in the help page.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
tokens: list[Token] = field(factory=list)
|
| 77 |
+
"""
|
| 78 |
+
List of :class:`.Token` parsed from various sources.
|
| 79 |
+
Do not directly mutate; see :meth:`append`.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
field_info: FieldInfo = field(factory=FieldInfo)
|
| 83 |
+
"""
|
| 84 |
+
Additional information about the parameter from surrounding python syntax.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
parameter: Parameter = field(factory=Parameter)
|
| 88 |
+
"""
|
| 89 |
+
Fully resolved user-provided :class:`.Parameter`.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
hint: Any = field(default=str, converter=resolve)
|
| 93 |
+
"""
|
| 94 |
+
The type hint for this argument; may be different from :attr:`.FieldInfo.annotation`.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
index: int | None = field(default=None)
|
| 98 |
+
"""
|
| 99 |
+
Associated python positional index for argument.
|
| 100 |
+
If ``None``, then cannot be assigned positionally.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
keys: tuple[str, ...] = field(default=())
|
| 104 |
+
"""
|
| 105 |
+
**Python** keys that lead to this leaf.
|
| 106 |
+
|
| 107 |
+
``self.parameter.name`` and ``self.keys`` can naively disagree!
|
| 108 |
+
For example, a ``self.parameter.name="--foo.bar.baz"`` could be aliased to "--fizz".
|
| 109 |
+
The resulting ``self.keys`` would be ``("bar", "baz")``.
|
| 110 |
+
|
| 111 |
+
This is populated based on type-hints and class-structure, not ``Parameter.name``.
|
| 112 |
+
|
| 113 |
+
.. code-block:: python
|
| 114 |
+
|
| 115 |
+
from cyclopts import App, Parameter
|
| 116 |
+
from dataclasses import dataclass
|
| 117 |
+
from typing import Annotated
|
| 118 |
+
|
| 119 |
+
app = App()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class User:
|
| 124 |
+
id: int
|
| 125 |
+
name: Annotated[str, Parameter(name="--fullname")]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@app.default
|
| 129 |
+
def main(user: User):
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
for argument in app.assemble_argument_collection():
|
| 134 |
+
print(f"name: {argument.name:16} hint: {str(argument.hint):16} keys: {str(argument.keys)}")
|
| 135 |
+
|
| 136 |
+
.. code-block:: bash
|
| 137 |
+
|
| 138 |
+
$ my-script
|
| 139 |
+
name: --user.id hint: <class 'int'> keys: ('id',)
|
| 140 |
+
name: --fullname hint: <class 'str'> keys: ('name',)
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
_value: Any = field(alias="value", default=UNSET)
|
| 144 |
+
"""
|
| 145 |
+
Converted value from last :meth:`convert` call.
|
| 146 |
+
This value may be stale if fields have changed since last :meth:`convert` call.
|
| 147 |
+
:class:`.UNSET` if :meth:`convert` has not yet been called with tokens.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
_accepts_keywords: bool = field(default=False, init=False, repr=False)
|
| 151 |
+
|
| 152 |
+
_default: Any = field(default=None, init=False, repr=False)
|
| 153 |
+
_lookup: dict[str, FieldInfo] = field(factory=dict, init=False, repr=False)
|
| 154 |
+
|
| 155 |
+
children: "ArgumentCollection" = field(init=False, repr=False)
|
| 156 |
+
"""
|
| 157 |
+
Collection of other :class:`Argument` that eventually culminate into the python variable represented by :attr:`field_info`.
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
_marked_converted: bool = field(default=False, init=False, repr=False)
|
| 161 |
+
_mark_converted_override: bool = field(default=False, init=False, repr=False)
|
| 162 |
+
|
| 163 |
+
_missing_keys_checker: Callable | None = field(default=None, init=False, repr=False)
|
| 164 |
+
|
| 165 |
+
_internal_converter: Callable | None = field(default=None, init=False, repr=False)
|
| 166 |
+
|
| 167 |
+
_enum_flag_type: Any | None = field(default=None, init=False, repr=False)
|
| 168 |
+
|
| 169 |
+
def __attrs_post_init__(self):
|
| 170 |
+
from cyclopts.argument._collection import ArgumentCollection
|
| 171 |
+
|
| 172 |
+
self.children = ArgumentCollection()
|
| 173 |
+
|
| 174 |
+
hint = resolve(self.hint)
|
| 175 |
+
hints = get_args(hint) if is_union(hint) else (hint,)
|
| 176 |
+
|
| 177 |
+
if self.parameter.count:
|
| 178 |
+
# Perform type-annotation validation.
|
| 179 |
+
resolved_hint = resolve_optional(hint)
|
| 180 |
+
# Technically, bool is a subclass of int, so we need to explicitly check.
|
| 181 |
+
if resolved_hint is bool or not (
|
| 182 |
+
resolved_hint is int or (isinstance(resolved_hint, type) and issubclass(resolved_hint, int))
|
| 183 |
+
):
|
| 184 |
+
raise ValueError(
|
| 185 |
+
f"Parameter(count=True) requires an int type hint, got {self.hint}. "
|
| 186 |
+
f"Use 'Annotated[int, Parameter(count=True)]' for counting flags."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
if self.parameter.requires_equals and self.parameter.consume_multiple:
|
| 190 |
+
raise ValueError(
|
| 191 |
+
"Parameter(requires_equals=True) and Parameter(consume_multiple=...) cannot be used together. "
|
| 192 |
+
"requires_equals enforces '--option=value' syntax, which is incompatible with "
|
| 193 |
+
"consume_multiple's space-separated value consumption."
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
if not self.parse:
|
| 197 |
+
# Validate that non-parsed parameters are keyword-only or have defaults
|
| 198 |
+
is_keyword_only = self.field_info.kind is self.field_info.KEYWORD_ONLY
|
| 199 |
+
has_default = self.field_info.default is not self.field_info.empty
|
| 200 |
+
if not (is_keyword_only or has_default):
|
| 201 |
+
raise ValueError(
|
| 202 |
+
f"Non-parsed parameter '{self.field_info.name}' must be a KEYWORD_ONLY function parameter "
|
| 203 |
+
"or have a default value."
|
| 204 |
+
)
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
if self.parameter.accepts_keys is False:
|
| 208 |
+
return
|
| 209 |
+
|
| 210 |
+
for hint in hints:
|
| 211 |
+
origin = get_origin(hint)
|
| 212 |
+
hint_origin = {hint, origin}
|
| 213 |
+
|
| 214 |
+
field_infos = get_field_infos(hint)
|
| 215 |
+
if dict in hint_origin:
|
| 216 |
+
self._accepts_keywords = True
|
| 217 |
+
key_type, val_type = str, str
|
| 218 |
+
args = get_args(hint)
|
| 219 |
+
with suppress(IndexError):
|
| 220 |
+
key_type = args[0]
|
| 221 |
+
val_type = args[1]
|
| 222 |
+
if key_type is not str:
|
| 223 |
+
raise TypeError('Dictionary type annotations must have "str" keys.')
|
| 224 |
+
self._default = val_type
|
| 225 |
+
elif is_typeddict(hint):
|
| 226 |
+
self._missing_keys_checker = missing_keys_factory(_typed_dict_field_infos)
|
| 227 |
+
self._accepts_keywords = True
|
| 228 |
+
self._update_lookup(field_infos)
|
| 229 |
+
elif is_dataclass(hint):
|
| 230 |
+
self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos)
|
| 231 |
+
self._accepts_keywords = True
|
| 232 |
+
self._update_lookup(field_infos)
|
| 233 |
+
elif is_namedtuple(hint):
|
| 234 |
+
self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos)
|
| 235 |
+
self._accepts_keywords = True
|
| 236 |
+
if not hasattr(hint, "__annotations__"):
|
| 237 |
+
raise ValueError("Cyclopts cannot handle collections.namedtuple without type annotations.")
|
| 238 |
+
self._update_lookup(field_infos)
|
| 239 |
+
elif is_attrs(hint):
|
| 240 |
+
self._missing_keys_checker = missing_keys_factory(_attrs_field_infos)
|
| 241 |
+
self._accepts_keywords = True
|
| 242 |
+
self._update_lookup(field_infos)
|
| 243 |
+
elif is_pydantic(hint):
|
| 244 |
+
self._missing_keys_checker = missing_keys_factory(_pydantic_field_infos)
|
| 245 |
+
self._accepts_keywords = True
|
| 246 |
+
self._update_lookup(field_infos)
|
| 247 |
+
elif is_enum_flag(hint):
|
| 248 |
+
self._enum_flag_type = hint
|
| 249 |
+
self._accepts_keywords = True
|
| 250 |
+
self._update_lookup(field_infos)
|
| 251 |
+
elif not is_builtin(hint) and field_infos:
|
| 252 |
+
self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos)
|
| 253 |
+
self._accepts_keywords = True
|
| 254 |
+
self._update_lookup(field_infos)
|
| 255 |
+
elif self.parameter.accepts_keys is None:
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
if self.parameter.accepts_keys is None:
|
| 259 |
+
continue
|
| 260 |
+
|
| 261 |
+
self._accepts_keywords = True
|
| 262 |
+
self._missing_keys_checker = missing_keys_factory(_generic_class_field_infos)
|
| 263 |
+
for i, field_info in enumerate(signature_parameters(hint.__init__).values()):
|
| 264 |
+
if i == 0 and field_info.name == "self":
|
| 265 |
+
continue
|
| 266 |
+
if field_info.kind is field_info.VAR_KEYWORD:
|
| 267 |
+
self._default = field_info.annotation
|
| 268 |
+
else:
|
| 269 |
+
self._update_lookup({field_info.name: field_info})
|
| 270 |
+
|
| 271 |
+
def _update_lookup(self, field_infos: dict[str, FieldInfo]):
|
| 272 |
+
from typing import Literal
|
| 273 |
+
|
| 274 |
+
discriminator = get_annotated_discriminator(self.field_info.annotation)
|
| 275 |
+
|
| 276 |
+
for key, field_info in field_infos.items():
|
| 277 |
+
if existing_field_info := self._lookup.get(key):
|
| 278 |
+
if existing_field_info == field_info:
|
| 279 |
+
pass
|
| 280 |
+
elif discriminator and discriminator in field_info.names and discriminator in existing_field_info.names:
|
| 281 |
+
existing_field_info.annotation = Literal[existing_field_info.annotation, field_info.annotation]
|
| 282 |
+
existing_field_info.default = FieldInfo.empty
|
| 283 |
+
else:
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
else:
|
| 286 |
+
self._lookup[key] = field_info
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def value(self):
|
| 290 |
+
"""Converted value from last :meth:`convert` call.
|
| 291 |
+
|
| 292 |
+
This value may be stale if fields have changed since last :meth:`convert` call.
|
| 293 |
+
:class:`.UNSET` if :meth:`convert` has not yet been called with tokens.
|
| 294 |
+
"""
|
| 295 |
+
return self._value
|
| 296 |
+
|
| 297 |
+
@value.setter
|
| 298 |
+
def value(self, val):
|
| 299 |
+
if self._marked:
|
| 300 |
+
self._mark_converted_override = True
|
| 301 |
+
self._marked = True
|
| 302 |
+
self._value = val
|
| 303 |
+
|
| 304 |
+
@property
|
| 305 |
+
def _marked(self):
|
| 306 |
+
"""If ``True``, then this node in the tree has already been converted and ``value`` has been populated."""
|
| 307 |
+
return self._marked_converted | self._mark_converted_override
|
| 308 |
+
|
| 309 |
+
@_marked.setter
|
| 310 |
+
def _marked(self, value: bool):
|
| 311 |
+
self._marked_converted = value
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def _accepts_arbitrary_keywords(self) -> bool:
|
| 315 |
+
args = get_args(self.hint) if is_union(self.hint) else (self.hint,)
|
| 316 |
+
return any(dict in (arg, get_origin(arg)) for arg in args)
|
| 317 |
+
|
| 318 |
+
@property
|
| 319 |
+
def show_default(self) -> bool | Callable[[Any], str]:
|
| 320 |
+
"""Show the default value on the help page."""
|
| 321 |
+
if self.required:
|
| 322 |
+
return False
|
| 323 |
+
elif self.parameter.show_default is None:
|
| 324 |
+
return self.field_info.default not in (None, self.field_info.empty)
|
| 325 |
+
elif (self.field_info.default is self.field_info.empty) or not self.parameter.show_default:
|
| 326 |
+
return False
|
| 327 |
+
else:
|
| 328 |
+
return self.parameter.show_default
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def _use_pydantic_type_adapter(self) -> bool:
|
| 332 |
+
return bool(
|
| 333 |
+
is_pydantic(self.hint)
|
| 334 |
+
or (
|
| 335 |
+
is_union(self.hint)
|
| 336 |
+
and (
|
| 337 |
+
any(is_pydantic(x) for x in get_args(self.hint))
|
| 338 |
+
or get_annotated_discriminator(self.field_info.annotation)
|
| 339 |
+
)
|
| 340 |
+
)
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def _type_hint_for_key(self, key: str):
|
| 344 |
+
try:
|
| 345 |
+
return self._lookup[key].annotation
|
| 346 |
+
except KeyError:
|
| 347 |
+
if self._default is None:
|
| 348 |
+
raise
|
| 349 |
+
return self._default
|
| 350 |
+
|
| 351 |
+
def _should_attempt_json_dict(self, tokens: Sequence[Token | str] | None = None) -> bool:
|
| 352 |
+
"""When parsing, should attempt to parse the token(s) as json dict data."""
|
| 353 |
+
if tokens is None:
|
| 354 |
+
tokens = self.tokens
|
| 355 |
+
if not tokens:
|
| 356 |
+
return False
|
| 357 |
+
value = tokens[0].value if isinstance(tokens[0], Token) else tokens[0]
|
| 358 |
+
if not value.strip().startswith("{"):
|
| 359 |
+
return False
|
| 360 |
+
|
| 361 |
+
if self._accepts_keywords:
|
| 362 |
+
if self.parameter.json_dict is not None:
|
| 363 |
+
return self.parameter.json_dict
|
| 364 |
+
if contains_hint(self.field_info.annotation, str):
|
| 365 |
+
return False
|
| 366 |
+
return True
|
| 367 |
+
|
| 368 |
+
hint = resolve(self.hint)
|
| 369 |
+
origin = get_origin(hint)
|
| 370 |
+
if origin in ITERABLE_TYPES:
|
| 371 |
+
args = get_args(hint)
|
| 372 |
+
if args and args[0] is not str:
|
| 373 |
+
return True
|
| 374 |
+
|
| 375 |
+
return False
|
| 376 |
+
|
| 377 |
+
def _should_attempt_json_list(
|
| 378 |
+
self, tokens: Sequence[Token | str] | Token | str | None = None, keys: tuple[str, ...] = ()
|
| 379 |
+
) -> bool:
|
| 380 |
+
"""When parsing, should attempt to parse the token(s) as json list data."""
|
| 381 |
+
if tokens is None:
|
| 382 |
+
tokens = self.tokens
|
| 383 |
+
if not tokens:
|
| 384 |
+
return False
|
| 385 |
+
_, consume_all = self.token_count(keys)
|
| 386 |
+
if not consume_all:
|
| 387 |
+
return False
|
| 388 |
+
if isinstance(tokens, Token):
|
| 389 |
+
value = tokens.value
|
| 390 |
+
elif isinstance(tokens, str):
|
| 391 |
+
value = tokens
|
| 392 |
+
else:
|
| 393 |
+
value = tokens[0].value if isinstance(tokens[0], Token) else tokens[0]
|
| 394 |
+
if not value.strip().startswith("["):
|
| 395 |
+
return False
|
| 396 |
+
if self.parameter.json_list is not None:
|
| 397 |
+
return self.parameter.json_list
|
| 398 |
+
for arg in get_args(self.field_info.annotation) or (str,):
|
| 399 |
+
if contains_hint(arg, str):
|
| 400 |
+
return False
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
def match(
|
| 404 |
+
self,
|
| 405 |
+
term: str | int,
|
| 406 |
+
*,
|
| 407 |
+
transform: Callable[[str], str] | None = None,
|
| 408 |
+
delimiter: str = ".",
|
| 409 |
+
) -> tuple[tuple[str, ...], Any]:
|
| 410 |
+
"""Match a name search-term, or a positional integer index.
|
| 411 |
+
|
| 412 |
+
Raises
|
| 413 |
+
------
|
| 414 |
+
ValueError
|
| 415 |
+
If no match is found.
|
| 416 |
+
|
| 417 |
+
Returns
|
| 418 |
+
-------
|
| 419 |
+
tuple[str, ...]
|
| 420 |
+
Leftover keys after matching to this argument.
|
| 421 |
+
Used if this argument accepts_arbitrary_keywords.
|
| 422 |
+
Any
|
| 423 |
+
Implicit value.
|
| 424 |
+
:obj:`~.UNSET` if no implicit value is applicable.
|
| 425 |
+
"""
|
| 426 |
+
if not self.parse:
|
| 427 |
+
raise ValueError
|
| 428 |
+
return (
|
| 429 |
+
self._match_index(term)
|
| 430 |
+
if isinstance(term, int)
|
| 431 |
+
else self._match_name(term, transform=transform, delimiter=delimiter)
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
def _normalize_trailing_keys(self, trailing: tuple[str, ...]) -> tuple[str, ...]:
|
| 435 |
+
"""Map kebab-case segments back to their canonical Python field names.
|
| 436 |
+
|
| 437 |
+
Walks the type hint segment-by-segment:
|
| 438 |
+
|
| 439 |
+
* Dynamic ``dict`` keys pass through unchanged (advance to the value type).
|
| 440 |
+
* Segments addressing a structured type (pydantic / dataclass / attrs /
|
| 441 |
+
TypedDict / NamedTuple) are looked up in a ``{name_transform(name): name}``
|
| 442 |
+
map built from the type's field_infos; on hit, the segment is replaced
|
| 443 |
+
with the canonical name and the walk advances to that field's annotation.
|
| 444 |
+
* On miss or when the hint is unwalkable (plain scalar, unresolved forward
|
| 445 |
+
ref, etc.) remaining segments pass through unchanged — this preserves the
|
| 446 |
+
existing raw-snake_case behavior as a backward-compat fallback.
|
| 447 |
+
"""
|
| 448 |
+
name_transform = self.parameter.name_transform
|
| 449 |
+
if name_transform is None or not trailing:
|
| 450 |
+
return trailing
|
| 451 |
+
|
| 452 |
+
# Seed from ``self.hint`` (not ``field_info.annotation``): for
|
| 453 |
+
# ``**kwargs: SubConfig``, the annotation is ``SubConfig`` but the hint
|
| 454 |
+
# is ``dict[str, SubConfig]`` — we need the wrapped form so the first
|
| 455 |
+
# trailing segment is routed as a dict key rather than a field name.
|
| 456 |
+
hint = resolve(self.hint)
|
| 457 |
+
out: list[str] = []
|
| 458 |
+
i = 0
|
| 459 |
+
while i < len(trailing):
|
| 460 |
+
segment = trailing[i]
|
| 461 |
+
hint = resolve_optional(hint)
|
| 462 |
+
|
| 463 |
+
if get_origin(hint) is dict:
|
| 464 |
+
out.append(segment)
|
| 465 |
+
args = get_args(hint)
|
| 466 |
+
hint = args[1] if len(args) > 1 else str
|
| 467 |
+
i += 1
|
| 468 |
+
continue
|
| 469 |
+
|
| 470 |
+
field_infos = {}
|
| 471 |
+
try:
|
| 472 |
+
field_infos = get_field_infos(hint)
|
| 473 |
+
except Exception:
|
| 474 |
+
pass
|
| 475 |
+
if not field_infos:
|
| 476 |
+
out.extend(trailing[i:])
|
| 477 |
+
break
|
| 478 |
+
|
| 479 |
+
# Build a kebab→canonical map from ``fi.names`` only. Cyclopts's
|
| 480 |
+
# field_info extractors populate ``names`` with exactly the names
|
| 481 |
+
# the underlying library accepts (e.g. pydantic omits the python
|
| 482 |
+
# name when ``populate_by_name=False``); trust that.
|
| 483 |
+
name_map: dict[str, tuple[str, Any]] = {}
|
| 484 |
+
for canonical_name, fi in field_infos.items():
|
| 485 |
+
for alias in fi.names:
|
| 486 |
+
name_map.setdefault(name_transform(alias), (canonical_name, fi.annotation))
|
| 487 |
+
|
| 488 |
+
match = name_map.get(segment)
|
| 489 |
+
if match is None:
|
| 490 |
+
out.extend(trailing[i:])
|
| 491 |
+
break
|
| 492 |
+
canonical_name, next_hint = match
|
| 493 |
+
out.append(canonical_name)
|
| 494 |
+
hint = resolve(next_hint)
|
| 495 |
+
i += 1
|
| 496 |
+
|
| 497 |
+
return tuple(out)
|
| 498 |
+
|
| 499 |
+
def _match_name(
|
| 500 |
+
self,
|
| 501 |
+
term: str,
|
| 502 |
+
*,
|
| 503 |
+
transform: Callable[[str], str] | None = None,
|
| 504 |
+
delimiter: str = ".",
|
| 505 |
+
) -> tuple[tuple[str, ...], Any]:
|
| 506 |
+
"""Check how well this argument matches a token keyword identifier.
|
| 507 |
+
|
| 508 |
+
Parameters
|
| 509 |
+
----------
|
| 510 |
+
term: str
|
| 511 |
+
Something like "--foo"
|
| 512 |
+
transform: Callable
|
| 513 |
+
Function that converts the cyclopts Parameter name(s) into
|
| 514 |
+
something that should be compared against ``term``.
|
| 515 |
+
|
| 516 |
+
Raises
|
| 517 |
+
------
|
| 518 |
+
ValueError
|
| 519 |
+
If no match found.
|
| 520 |
+
|
| 521 |
+
Returns
|
| 522 |
+
-------
|
| 523 |
+
tuple[str, ...]
|
| 524 |
+
Leftover keys after matching to this argument.
|
| 525 |
+
Used if this argument accepts_arbitrary_keywords.
|
| 526 |
+
Any
|
| 527 |
+
Implicit value.
|
| 528 |
+
"""
|
| 529 |
+
if self.field_info.kind is self.field_info.VAR_KEYWORD:
|
| 530 |
+
return self._normalize_trailing_keys(tuple(term.lstrip("-").split(delimiter))), UNSET
|
| 531 |
+
|
| 532 |
+
trailing = term
|
| 533 |
+
implicit_value = UNSET
|
| 534 |
+
|
| 535 |
+
assert self.parameter.name
|
| 536 |
+
for name in self.parameter.name:
|
| 537 |
+
if transform:
|
| 538 |
+
name = transform(name)
|
| 539 |
+
if startswith(term, name):
|
| 540 |
+
trailing = term[len(name) :]
|
| 541 |
+
implicit_value = True if self.hint is bool or self.hint in ITERATIVE_BOOL_IMPLICIT_VALUE else UNSET
|
| 542 |
+
if trailing:
|
| 543 |
+
if trailing[0] == delimiter:
|
| 544 |
+
trailing = trailing[1:]
|
| 545 |
+
break
|
| 546 |
+
else:
|
| 547 |
+
return (), implicit_value
|
| 548 |
+
else:
|
| 549 |
+
hint = resolve_annotated(self.field_info.annotation)
|
| 550 |
+
if is_union(hint):
|
| 551 |
+
hints = get_args(hint)
|
| 552 |
+
else:
|
| 553 |
+
hints = (hint,)
|
| 554 |
+
for hint in hints:
|
| 555 |
+
hint = resolve_annotated(hint)
|
| 556 |
+
double_break = False
|
| 557 |
+
for name in self.parameter.get_negatives(hint):
|
| 558 |
+
if transform:
|
| 559 |
+
name = transform(name)
|
| 560 |
+
if startswith(term, name):
|
| 561 |
+
trailing = term[len(name) :]
|
| 562 |
+
if hint in ITERATIVE_BOOL_IMPLICIT_VALUE:
|
| 563 |
+
implicit_value = False
|
| 564 |
+
elif is_nonetype(hint) or hint is None:
|
| 565 |
+
implicit_value = None
|
| 566 |
+
else:
|
| 567 |
+
hint = resolve_optional(hint)
|
| 568 |
+
implicit_value = (get_origin(hint) or hint)()
|
| 569 |
+
if trailing:
|
| 570 |
+
if trailing[0] == delimiter:
|
| 571 |
+
trailing = trailing[1:]
|
| 572 |
+
double_break = True
|
| 573 |
+
break
|
| 574 |
+
else:
|
| 575 |
+
return (), implicit_value
|
| 576 |
+
if double_break:
|
| 577 |
+
break
|
| 578 |
+
else:
|
| 579 |
+
raise ValueError
|
| 580 |
+
|
| 581 |
+
if not self._accepts_arbitrary_keywords:
|
| 582 |
+
raise ValueError
|
| 583 |
+
|
| 584 |
+
return self._normalize_trailing_keys(tuple(trailing.split(delimiter))), implicit_value
|
| 585 |
+
|
| 586 |
+
def _match_index(self, index: int) -> tuple[tuple[str, ...], Any]:
|
| 587 |
+
if self.index is None:
|
| 588 |
+
raise ValueError
|
| 589 |
+
elif self.field_info.kind is self.field_info.VAR_POSITIONAL:
|
| 590 |
+
if index < self.index:
|
| 591 |
+
raise ValueError
|
| 592 |
+
elif index != self.index:
|
| 593 |
+
raise ValueError
|
| 594 |
+
return (), UNSET
|
| 595 |
+
|
| 596 |
+
def append(self, token: Token):
|
| 597 |
+
"""Safely add a :class:`Token`."""
|
| 598 |
+
if not self.parse:
|
| 599 |
+
raise ValueError
|
| 600 |
+
|
| 601 |
+
if any(x.address == token.address for x in self.tokens):
|
| 602 |
+
if self.parameter.allow_repeating is False:
|
| 603 |
+
raise RepeatArgumentError(token=token)
|
| 604 |
+
_, consume_all = self.token_count(token.keys)
|
| 605 |
+
if self.parameter.allow_repeating is True:
|
| 606 |
+
if not consume_all:
|
| 607 |
+
# "last wins" for scalar types — remove old tokens with same address
|
| 608 |
+
self.tokens = [x for x in self.tokens if x.address != token.address]
|
| 609 |
+
elif not consume_all and not self.parameter.count:
|
| 610 |
+
raise RepeatArgumentError(token=token)
|
| 611 |
+
|
| 612 |
+
if self.tokens:
|
| 613 |
+
if bool(token.keys) ^ any(x.keys for x in self.tokens):
|
| 614 |
+
raise MixedArgumentError(argument=self)
|
| 615 |
+
self.tokens.append(token)
|
| 616 |
+
|
| 617 |
+
@property
|
| 618 |
+
def has_tokens(self) -> bool:
|
| 619 |
+
"""This argument, or a child argument, has at least 1 parsed token.""" # noqa: D404
|
| 620 |
+
return bool(self.tokens) or any(x.has_tokens for x in self.children)
|
| 621 |
+
|
| 622 |
+
@property
|
| 623 |
+
def children_recursive(self) -> "ArgumentCollection":
|
| 624 |
+
from cyclopts.argument._collection import ArgumentCollection
|
| 625 |
+
|
| 626 |
+
out = ArgumentCollection()
|
| 627 |
+
for child in self.children:
|
| 628 |
+
out.append(child)
|
| 629 |
+
out.extend(child.children_recursive)
|
| 630 |
+
return out
|
| 631 |
+
|
| 632 |
+
def _convert_pydantic(self):
|
| 633 |
+
if self.has_tokens:
|
| 634 |
+
import pydantic
|
| 635 |
+
|
| 636 |
+
unstructured_data = self._json()
|
| 637 |
+
try:
|
| 638 |
+
return pydantic.TypeAdapter(self.field_info.annotation).validate_python(unstructured_data)
|
| 639 |
+
except pydantic.ValidationError as e:
|
| 640 |
+
self._handle_pydantic_validation_error(e)
|
| 641 |
+
else:
|
| 642 |
+
return UNSET
|
| 643 |
+
|
| 644 |
+
def _convert(self, converter: Callable | None = None):
|
| 645 |
+
from cyclopts.argument._collection import update_argument_collection
|
| 646 |
+
|
| 647 |
+
if self.parameter.converter:
|
| 648 |
+
# Resolve string converters to methods on the type
|
| 649 |
+
if isinstance(self.parameter.converter, str):
|
| 650 |
+
converter = getattr(self.hint, self.parameter.converter)
|
| 651 |
+
else:
|
| 652 |
+
converter = self.parameter.converter
|
| 653 |
+
elif converter is None:
|
| 654 |
+
converter = partial(convert, name_transform=self.parameter.name_transform)
|
| 655 |
+
|
| 656 |
+
assert converter is not None # Ensure converter is set at this point
|
| 657 |
+
|
| 658 |
+
def safe_converter(hint, tokens):
|
| 659 |
+
if isinstance(tokens, dict):
|
| 660 |
+
try:
|
| 661 |
+
return converter(hint, tokens) # pyright: ignore
|
| 662 |
+
except (AssertionError, ValueError, TypeError) as e:
|
| 663 |
+
raise CoercionError(msg=e.args[0] if e.args else None, argument=self, target_type=hint) from e
|
| 664 |
+
else:
|
| 665 |
+
try:
|
| 666 |
+
# Detect bound methods (classmethods/instance methods)
|
| 667 |
+
if inspect.ismethod(converter):
|
| 668 |
+
# Call with just tokens - cls/self already bound
|
| 669 |
+
return converter(tokens) # pyright: ignore[reportCallIssue]
|
| 670 |
+
else:
|
| 671 |
+
# Regular function - pass type and tokens
|
| 672 |
+
return converter(hint, tokens) # pyright: ignore[reportCallIssue]
|
| 673 |
+
except (AssertionError, ValueError, TypeError) as e:
|
| 674 |
+
token = tokens[0] if len(tokens) == 1 else None
|
| 675 |
+
raise CoercionError(
|
| 676 |
+
msg=e.args[0] if e.args else None, argument=self, target_type=hint, token=token
|
| 677 |
+
) from e
|
| 678 |
+
|
| 679 |
+
if not self.parse:
|
| 680 |
+
out = UNSET
|
| 681 |
+
elif self.parameter.count:
|
| 682 |
+
out = sum(token.implicit_value for token in self.tokens if token.implicit_value is not UNSET)
|
| 683 |
+
elif not self.children:
|
| 684 |
+
positional: list[Token] = []
|
| 685 |
+
keyword = {}
|
| 686 |
+
|
| 687 |
+
def expand_tokens(tokens):
|
| 688 |
+
for token in tokens:
|
| 689 |
+
if self._should_attempt_json_list(token):
|
| 690 |
+
try:
|
| 691 |
+
parsed_json = json.loads(token.value)
|
| 692 |
+
except json.JSONDecodeError as e:
|
| 693 |
+
raise CoercionError(token=token, target_type=self.hint) from e
|
| 694 |
+
|
| 695 |
+
if not isinstance(parsed_json, list):
|
| 696 |
+
raise CoercionError(token=token, target_type=self.hint)
|
| 697 |
+
|
| 698 |
+
if not parsed_json:
|
| 699 |
+
yield token.evolve(value="", implicit_value=[])
|
| 700 |
+
else:
|
| 701 |
+
for element in parsed_json:
|
| 702 |
+
if element is None:
|
| 703 |
+
yield token.evolve(value="", implicit_value=element)
|
| 704 |
+
elif isinstance(element, dict):
|
| 705 |
+
yield token.evolve(value=json.dumps(element))
|
| 706 |
+
else:
|
| 707 |
+
yield token.evolve(value=str(element))
|
| 708 |
+
else:
|
| 709 |
+
yield token
|
| 710 |
+
|
| 711 |
+
expanded_tokens = list(expand_tokens(self.tokens))
|
| 712 |
+
for token in expanded_tokens:
|
| 713 |
+
resolved_hint = resolve_optional(self.hint)
|
| 714 |
+
if token.implicit_value is not UNSET and isinstance(
|
| 715 |
+
token.implicit_value, get_origin(resolved_hint) or resolved_hint
|
| 716 |
+
):
|
| 717 |
+
assert len(expanded_tokens) == 1
|
| 718 |
+
return token.implicit_value
|
| 719 |
+
|
| 720 |
+
if token.keys:
|
| 721 |
+
lookup = keyword
|
| 722 |
+
for key in token.keys[:-1]:
|
| 723 |
+
lookup = lookup.setdefault(key, {})
|
| 724 |
+
lookup.setdefault(token.keys[-1], []).append(token)
|
| 725 |
+
else:
|
| 726 |
+
positional.append(token)
|
| 727 |
+
|
| 728 |
+
if positional and keyword: # pragma: no cover
|
| 729 |
+
raise MixedArgumentError(argument=self)
|
| 730 |
+
|
| 731 |
+
if positional:
|
| 732 |
+
if self.field_info and self.field_info.kind is self.field_info.VAR_POSITIONAL:
|
| 733 |
+
hint = get_args(self.hint)[0]
|
| 734 |
+
tokens_per_element, _ = self.token_count()
|
| 735 |
+
out = tuple(safe_converter(hint, values) for values in grouper(positional, tokens_per_element))
|
| 736 |
+
else:
|
| 737 |
+
out = safe_converter(self.hint, tuple(positional))
|
| 738 |
+
elif keyword:
|
| 739 |
+
if self.field_info and self.field_info.kind is self.field_info.VAR_KEYWORD and not self.keys:
|
| 740 |
+
out = {key: safe_converter(get_args(self.hint)[1], value) for key, value in keyword.items()}
|
| 741 |
+
else:
|
| 742 |
+
out = safe_converter(self.hint, keyword)
|
| 743 |
+
elif self.required:
|
| 744 |
+
raise MissingArgumentError(argument=self)
|
| 745 |
+
else:
|
| 746 |
+
return UNSET
|
| 747 |
+
else:
|
| 748 |
+
data = {}
|
| 749 |
+
out = UNSET
|
| 750 |
+
|
| 751 |
+
if self._enum_flag_type:
|
| 752 |
+
out = self._enum_flag_type(0)
|
| 753 |
+
|
| 754 |
+
if self._enum_flag_type and self.tokens:
|
| 755 |
+
converted_flags = safe_converter(self._enum_flag_type, self.tokens)
|
| 756 |
+
out |= reduce(operator.or_, converted_flags) if isinstance(converted_flags, list) else converted_flags
|
| 757 |
+
|
| 758 |
+
if self._should_attempt_json_dict():
|
| 759 |
+
while self.tokens:
|
| 760 |
+
token = self.tokens.pop(0)
|
| 761 |
+
try:
|
| 762 |
+
parsed_json = json.loads(token.value)
|
| 763 |
+
except json.JSONDecodeError as e:
|
| 764 |
+
raise CoercionError(token=token, target_type=self.hint) from e
|
| 765 |
+
_validate_json_extra_keys(parsed_json, self.hint, token)
|
| 766 |
+
update_argument_collection(
|
| 767 |
+
{self.name.lstrip("-"): parsed_json},
|
| 768 |
+
token.source,
|
| 769 |
+
self.children_recursive,
|
| 770 |
+
root_keys=(),
|
| 771 |
+
allow_unknown=False,
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
if self._use_pydantic_type_adapter:
|
| 775 |
+
return self._convert_pydantic()
|
| 776 |
+
|
| 777 |
+
if self.tokens and not self._enum_flag_type:
|
| 778 |
+
positional_tokens = [token for token in self.tokens if not token.keys]
|
| 779 |
+
if positional_tokens:
|
| 780 |
+
return safe_converter(self.hint, tuple(positional_tokens))
|
| 781 |
+
|
| 782 |
+
for child in self.children:
|
| 783 |
+
assert len(child.keys) == (len(self.keys) + 1)
|
| 784 |
+
if child.has_tokens:
|
| 785 |
+
data[child.keys[-1]] = child.convert_and_validate(converter=converter)
|
| 786 |
+
elif child.required:
|
| 787 |
+
obj = data
|
| 788 |
+
for k in child.keys:
|
| 789 |
+
try:
|
| 790 |
+
obj = obj[k]
|
| 791 |
+
except Exception:
|
| 792 |
+
raise MissingArgumentError(argument=child) from None
|
| 793 |
+
child._marked = True
|
| 794 |
+
|
| 795 |
+
self._run_missing_keys_checker(data)
|
| 796 |
+
|
| 797 |
+
if self._enum_flag_type:
|
| 798 |
+
out |= enum_flag_from_dict(self._enum_flag_type, data, self.parameter.name_transform)
|
| 799 |
+
if not out:
|
| 800 |
+
out = UNSET
|
| 801 |
+
elif data:
|
| 802 |
+
out = instantiate_from_dict(self.hint, data)
|
| 803 |
+
elif self.required:
|
| 804 |
+
raise MissingArgumentError(argument=self) # pragma: no cover
|
| 805 |
+
else:
|
| 806 |
+
out = UNSET
|
| 807 |
+
|
| 808 |
+
return out
|
| 809 |
+
|
| 810 |
+
def convert(self, converter: Callable | None = None):
|
| 811 |
+
"""Converts :attr:`tokens` into :attr:`value`.
|
| 812 |
+
|
| 813 |
+
Parameters
|
| 814 |
+
----------
|
| 815 |
+
converter: Callable | None
|
| 816 |
+
Converter function to use. Overrides ``self.parameter.converter``
|
| 817 |
+
|
| 818 |
+
Returns
|
| 819 |
+
-------
|
| 820 |
+
Any
|
| 821 |
+
The converted data. Same as :attr:`value`.
|
| 822 |
+
"""
|
| 823 |
+
if not self._marked:
|
| 824 |
+
try:
|
| 825 |
+
self.value = self._convert(converter=converter)
|
| 826 |
+
except CoercionError as e:
|
| 827 |
+
if e.argument is None:
|
| 828 |
+
e.argument = self
|
| 829 |
+
if e.target_type is None:
|
| 830 |
+
e.target_type = self.hint
|
| 831 |
+
raise
|
| 832 |
+
except CycloptsError as e:
|
| 833 |
+
if e.argument is None:
|
| 834 |
+
e.argument = self
|
| 835 |
+
raise
|
| 836 |
+
|
| 837 |
+
return self.value
|
| 838 |
+
|
| 839 |
+
def validate(self, value):
|
| 840 |
+
"""Validates provided value.
|
| 841 |
+
|
| 842 |
+
Parameters
|
| 843 |
+
----------
|
| 844 |
+
value:
|
| 845 |
+
Value to validate.
|
| 846 |
+
|
| 847 |
+
Returns
|
| 848 |
+
-------
|
| 849 |
+
Any
|
| 850 |
+
The converted data. Same as :attr:`value`.
|
| 851 |
+
"""
|
| 852 |
+
assert isinstance(self.parameter.validator, tuple)
|
| 853 |
+
|
| 854 |
+
# Only use pydantic validation if pydantic v2+ is available.
|
| 855 |
+
# Pydantic v1 has an incompatible API (e.g. no TypeAdapter).
|
| 856 |
+
if "pydantic" in sys.modules:
|
| 857 |
+
import pydantic
|
| 858 |
+
|
| 859 |
+
pydantic_version = parse_version(pydantic.__version__)
|
| 860 |
+
if pydantic_version < (2,):
|
| 861 |
+
pydantic = None
|
| 862 |
+
else:
|
| 863 |
+
pydantic = None
|
| 864 |
+
|
| 865 |
+
def validate_pydantic(hint, val):
|
| 866 |
+
if not pydantic:
|
| 867 |
+
return
|
| 868 |
+
if self._use_pydantic_type_adapter:
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
try:
|
| 872 |
+
pydantic.TypeAdapter(hint).validate_python(val)
|
| 873 |
+
except pydantic.ValidationError as e:
|
| 874 |
+
self._handle_pydantic_validation_error(e)
|
| 875 |
+
except pydantic.PydanticUserError:
|
| 876 |
+
pass
|
| 877 |
+
|
| 878 |
+
try:
|
| 879 |
+
if not self.keys and self.field_info and self.field_info.kind is self.field_info.VAR_KEYWORD:
|
| 880 |
+
hint = get_args(self.hint)[1]
|
| 881 |
+
for validator in self.parameter.validator:
|
| 882 |
+
for val in value.values():
|
| 883 |
+
validator(hint, val)
|
| 884 |
+
validate_pydantic(dict[str, self.field_info.annotation], value)
|
| 885 |
+
elif self.field_info and self.field_info.kind is self.field_info.VAR_POSITIONAL:
|
| 886 |
+
hint = get_args(self.hint)[0]
|
| 887 |
+
for validator in self.parameter.validator:
|
| 888 |
+
for val in value:
|
| 889 |
+
validator(hint, val)
|
| 890 |
+
validate_pydantic(tuple[self.field_info.annotation, ...], value)
|
| 891 |
+
else:
|
| 892 |
+
for validator in self.parameter.validator:
|
| 893 |
+
validator(self.hint, value)
|
| 894 |
+
validate_pydantic(self.field_info.annotation, value)
|
| 895 |
+
except (AssertionError, ValueError, TypeError) as e:
|
| 896 |
+
raise ValidationError(exception_message=e.args[0] if e.args else "", argument=self) from e
|
| 897 |
+
|
| 898 |
+
def convert_and_validate(self, converter: Callable | None = None):
|
| 899 |
+
"""Converts and validates :attr:`tokens` into :attr:`value`.
|
| 900 |
+
|
| 901 |
+
Parameters
|
| 902 |
+
----------
|
| 903 |
+
converter: Callable | None
|
| 904 |
+
Converter function to use. Overrides ``self.parameter.converter``
|
| 905 |
+
|
| 906 |
+
Returns
|
| 907 |
+
-------
|
| 908 |
+
Any
|
| 909 |
+
The converted data. Same as :attr:`value`.
|
| 910 |
+
"""
|
| 911 |
+
val = self.convert(converter=converter)
|
| 912 |
+
if val is not UNSET:
|
| 913 |
+
self.validate(val)
|
| 914 |
+
elif self.field_info.default is not FieldInfo.empty:
|
| 915 |
+
self.validate(self.field_info.default)
|
| 916 |
+
return val
|
| 917 |
+
|
| 918 |
+
def token_count(self, keys: tuple[str, ...] = ()):
|
| 919 |
+
"""The number of string tokens this argument consumes.
|
| 920 |
+
|
| 921 |
+
Parameters
|
| 922 |
+
----------
|
| 923 |
+
keys: tuple[str, ...]
|
| 924 |
+
The **python** keys into this argument.
|
| 925 |
+
If provided, returns the number of string tokens that specific
|
| 926 |
+
data type within the argument consumes.
|
| 927 |
+
|
| 928 |
+
Returns
|
| 929 |
+
-------
|
| 930 |
+
int
|
| 931 |
+
Number of string tokens to create 1 element.
|
| 932 |
+
consume_all: bool
|
| 933 |
+
:obj:`True` if this data type is iterable.
|
| 934 |
+
"""
|
| 935 |
+
if self.parameter.count:
|
| 936 |
+
return 0, False
|
| 937 |
+
|
| 938 |
+
# Check for explicit n_tokens override
|
| 939 |
+
# This applies to values at any level: root values (keys=()) or nested values (keys=(...))
|
| 940 |
+
# For example, **kwargs: Annotated[str, Parameter(n_tokens=2)] means each kwarg value needs 2 tokens
|
| 941 |
+
if self.parameter.n_tokens is not None:
|
| 942 |
+
if self.parameter.n_tokens == -1:
|
| 943 |
+
return 1, True
|
| 944 |
+
else:
|
| 945 |
+
# Determine consume_all based on the hint at the requested level
|
| 946 |
+
# by recursively calling token_count on the hint
|
| 947 |
+
if len(keys) > 1:
|
| 948 |
+
hint = self._default
|
| 949 |
+
elif len(keys) == 1:
|
| 950 |
+
hint = self._type_hint_for_key(keys[0])
|
| 951 |
+
else:
|
| 952 |
+
hint = self.hint
|
| 953 |
+
|
| 954 |
+
# Recursively call token_count to get the consume_all behavior
|
| 955 |
+
# We ignore the token count from the recursive call and use our explicit n_tokens
|
| 956 |
+
_, consume_all_from_type = token_count(hint)
|
| 957 |
+
return self.parameter.n_tokens, consume_all_from_type
|
| 958 |
+
|
| 959 |
+
if len(keys) > 1:
|
| 960 |
+
hint = self._default
|
| 961 |
+
elif len(keys) == 1:
|
| 962 |
+
hint = self._type_hint_for_key(keys[0])
|
| 963 |
+
else:
|
| 964 |
+
hint = self.hint
|
| 965 |
+
if self._enum_flag_type and not keys:
|
| 966 |
+
return 1, True
|
| 967 |
+
tokens_per_element, consume_all = token_count(hint)
|
| 968 |
+
return tokens_per_element, consume_all
|
| 969 |
+
|
| 970 |
+
@property
|
| 971 |
+
def negatives(self):
|
| 972 |
+
"""Negative flags from :meth:`.Parameter.get_negatives`."""
|
| 973 |
+
return self.parameter.get_negatives(resolve_annotated(self.field_info.annotation))
|
| 974 |
+
|
| 975 |
+
@property
|
| 976 |
+
def name(self) -> str:
|
| 977 |
+
"""The **first** provided name this argument goes by."""
|
| 978 |
+
return self.names[0]
|
| 979 |
+
|
| 980 |
+
@property
|
| 981 |
+
def names(self) -> tuple[str, ...]:
|
| 982 |
+
"""Names the argument goes by (both positive and negative)."""
|
| 983 |
+
import itertools
|
| 984 |
+
|
| 985 |
+
assert isinstance(self.parameter.name, tuple)
|
| 986 |
+
return tuple(itertools.chain(self.parameter.name, self.negatives))
|
| 987 |
+
|
| 988 |
+
def env_var_split(self, value: str, delimiter: str | None = None) -> list[str]:
|
| 989 |
+
"""Split a given value with :meth:`.Parameter.env_var_split`."""
|
| 990 |
+
return self.parameter.env_var_split(self.hint, value, delimiter=delimiter)
|
| 991 |
+
|
| 992 |
+
@property
|
| 993 |
+
def show(self) -> bool:
|
| 994 |
+
"""Show this argument on the help page.
|
| 995 |
+
|
| 996 |
+
If an argument has child arguments, don't show it on the help-page.
|
| 997 |
+
Returns False for arguments that won't be parsed (including underscore-prefixed params).
|
| 998 |
+
"""
|
| 999 |
+
if self.children:
|
| 1000 |
+
return False
|
| 1001 |
+
if self.parameter.show is not None:
|
| 1002 |
+
# User explicitly set show
|
| 1003 |
+
return self.parameter.show
|
| 1004 |
+
# Default to whether this argument is parsed
|
| 1005 |
+
return self.parse
|
| 1006 |
+
|
| 1007 |
+
@property
|
| 1008 |
+
def parse(self) -> bool:
|
| 1009 |
+
"""Whether this argument should be parsed from CLI tokens.
|
| 1010 |
+
|
| 1011 |
+
If ``Parameter.parse`` is a regex pattern, parse if the pattern matches
|
| 1012 |
+
the field name; otherwise don't parse.
|
| 1013 |
+
"""
|
| 1014 |
+
if self.parameter.parse is None:
|
| 1015 |
+
return True
|
| 1016 |
+
if isinstance(self.parameter.parse, re.Pattern):
|
| 1017 |
+
return bool(self.parameter.parse.search(self.field_info.name))
|
| 1018 |
+
return bool(self.parameter.parse)
|
| 1019 |
+
|
| 1020 |
+
@property
|
| 1021 |
+
def required(self) -> bool:
|
| 1022 |
+
"""Whether or not this argument requires a user-provided value."""
|
| 1023 |
+
if self.parameter.required is None:
|
| 1024 |
+
return self.field_info.required
|
| 1025 |
+
else:
|
| 1026 |
+
return self.parameter.required
|
| 1027 |
+
|
| 1028 |
+
def is_positional_only(self) -> bool:
|
| 1029 |
+
return self.field_info.is_positional_only
|
| 1030 |
+
|
| 1031 |
+
def is_var_positional(self) -> bool:
|
| 1032 |
+
return self.field_info.kind == self.field_info.VAR_POSITIONAL
|
| 1033 |
+
|
| 1034 |
+
def is_flag(self) -> bool:
|
| 1035 |
+
"""Check if this argument is a flag (consumes no CLI tokens).
|
| 1036 |
+
|
| 1037 |
+
Flags are arguments that don't consume command-line tokens after the option name.
|
| 1038 |
+
They typically have implicit values (e.g., `--verbose` for bool, `--no-items` for list).
|
| 1039 |
+
|
| 1040 |
+
Returns
|
| 1041 |
+
-------
|
| 1042 |
+
bool
|
| 1043 |
+
True if the argument consumes zero tokens from the command line.
|
| 1044 |
+
|
| 1045 |
+
Examples
|
| 1046 |
+
--------
|
| 1047 |
+
>>> from cyclopts import Parameter
|
| 1048 |
+
>>> bool_arg = Argument(hint=bool, parameter=Parameter(name="--verbose"))
|
| 1049 |
+
>>> bool_arg.is_flag()
|
| 1050 |
+
True
|
| 1051 |
+
>>> str_arg = Argument(hint=str, parameter=Parameter(name="--name"))
|
| 1052 |
+
>>> str_arg.is_flag()
|
| 1053 |
+
False
|
| 1054 |
+
"""
|
| 1055 |
+
return self.token_count() == (0, False)
|
| 1056 |
+
|
| 1057 |
+
def get_choices(self, force: bool = False) -> tuple[str, ...] | None:
|
| 1058 |
+
"""Extract completion choices from type hint.
|
| 1059 |
+
|
| 1060 |
+
Extracts choices from Literal types, Enum types, and Union types containing them.
|
| 1061 |
+
Respects the Parameter.show_choices setting unless force=True.
|
| 1062 |
+
|
| 1063 |
+
Parameters
|
| 1064 |
+
----------
|
| 1065 |
+
force : bool
|
| 1066 |
+
If True, return choices even when show_choices=False.
|
| 1067 |
+
Used by shell completion to always provide choices.
|
| 1068 |
+
|
| 1069 |
+
Returns
|
| 1070 |
+
-------
|
| 1071 |
+
tuple[str, ...] | None
|
| 1072 |
+
Tuple of choice strings if choices exist and should be shown, None otherwise.
|
| 1073 |
+
|
| 1074 |
+
Examples
|
| 1075 |
+
--------
|
| 1076 |
+
>>> argument = Argument(hint=Literal["dev", "staging", "prod"], parameter=Parameter(show_choices=True))
|
| 1077 |
+
>>> argument.get_choices()
|
| 1078 |
+
('dev', 'staging', 'prod')
|
| 1079 |
+
>>> argument = Argument(hint=Literal["dev", "staging", "prod"], parameter=Parameter(show_choices=False))
|
| 1080 |
+
>>> argument.get_choices() # Returns None for help text
|
| 1081 |
+
>>> argument.get_choices(force=True) # Returns choices for completion
|
| 1082 |
+
('dev', 'staging', 'prod')
|
| 1083 |
+
"""
|
| 1084 |
+
if not force and not self.parameter.show_choices:
|
| 1085 |
+
return None
|
| 1086 |
+
choices = get_choices_from_hint(self.hint, self.parameter.name_transform)
|
| 1087 |
+
return tuple(choices) if choices else None
|
| 1088 |
+
|
| 1089 |
+
def _json(self) -> dict:
|
| 1090 |
+
"""Convert argument to be json-like for pydantic.
|
| 1091 |
+
|
| 1092 |
+
All values will be str/list/dict. JSON-serialized strings (from sources
|
| 1093 |
+
like config files or environment variables) are deserialized back to their
|
| 1094 |
+
original dict/list structure.
|
| 1095 |
+
"""
|
| 1096 |
+
out = {}
|
| 1097 |
+
if self._accepts_keywords:
|
| 1098 |
+
for token in self.tokens:
|
| 1099 |
+
node = out
|
| 1100 |
+
for key in token.keys[:-1]:
|
| 1101 |
+
node = node.setdefault(key, {})
|
| 1102 |
+
node[token.keys[-1]] = token.value if token.implicit_value is UNSET else token.implicit_value
|
| 1103 |
+
for child in self.children:
|
| 1104 |
+
child._marked = True
|
| 1105 |
+
if not child.has_tokens:
|
| 1106 |
+
continue
|
| 1107 |
+
keys = child.keys[len(self.keys) :]
|
| 1108 |
+
if child._accepts_keywords:
|
| 1109 |
+
result = child._json()
|
| 1110 |
+
if result:
|
| 1111 |
+
out[keys[0]] = result
|
| 1112 |
+
elif (get_origin(child.hint) or child.hint) in ITERABLE_TYPES:
|
| 1113 |
+
for token in child.tokens:
|
| 1114 |
+
if token.implicit_value is not UNSET:
|
| 1115 |
+
out.setdefault(keys[-1], []).extend(token.implicit_value)
|
| 1116 |
+
else:
|
| 1117 |
+
value = token.value
|
| 1118 |
+
# Deserialize JSON strings (from update_argument_collection) back to dict/list
|
| 1119 |
+
if isinstance(value, str) and value.strip() and value.strip()[0] in ("{", "["):
|
| 1120 |
+
try:
|
| 1121 |
+
value = json.loads(value)
|
| 1122 |
+
except json.JSONDecodeError:
|
| 1123 |
+
pass
|
| 1124 |
+
out.setdefault(keys[-1], []).append(value)
|
| 1125 |
+
else:
|
| 1126 |
+
token = child.tokens[0]
|
| 1127 |
+
out[keys[0]] = token.value if token.implicit_value is UNSET else token.implicit_value
|
| 1128 |
+
return out
|
| 1129 |
+
|
| 1130 |
+
def _run_missing_keys_checker(self, data):
|
| 1131 |
+
if not self._missing_keys_checker or (not self.required and not data):
|
| 1132 |
+
return
|
| 1133 |
+
if not (missing_keys := self._missing_keys_checker(self, data)):
|
| 1134 |
+
return
|
| 1135 |
+
missing_key = missing_keys[0]
|
| 1136 |
+
keys = self.keys + (missing_key,)
|
| 1137 |
+
missing_arguments = self.children.filter_by(keys_prefix=keys)
|
| 1138 |
+
if missing_arguments:
|
| 1139 |
+
raise MissingArgumentError(argument=missing_arguments[0])
|
| 1140 |
+
else:
|
| 1141 |
+
missing_description = self.field_info.names[0] + "->" + "->".join(keys)
|
| 1142 |
+
raise ValueError(
|
| 1143 |
+
f'Required field "{missing_description}" is not accessible by Cyclopts; possibly due to conflicting POSITIONAL/KEYWORD requirements.'
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
def _handle_pydantic_validation_error(self, exc):
|
| 1147 |
+
import pydantic
|
| 1148 |
+
|
| 1149 |
+
error = exc.errors()[0]
|
| 1150 |
+
if error["type"] == "missing":
|
| 1151 |
+
loc = error["loc"]
|
| 1152 |
+
|
| 1153 |
+
# Pydantic includes list indices in loc for list-element errors
|
| 1154 |
+
# (e.g. ("animals", 0, "dog", "name")). Cyclopts doesn't model list
|
| 1155 |
+
# items as individual Arguments, so no prefix-match can correctly
|
| 1156 |
+
# map — fall through to the native pydantic error, which shows the
|
| 1157 |
+
# full nested path.
|
| 1158 |
+
if not any(isinstance(part, int) for part in loc):
|
| 1159 |
+
candidate = tuple(loc)
|
| 1160 |
+
while candidate:
|
| 1161 |
+
missing_arguments = self.children_recursive.filter_by(keys_prefix=self.keys + candidate)
|
| 1162 |
+
# An Argument that already has tokens cannot be "missing";
|
| 1163 |
+
# the stripping heuristic has wandered into a populated sibling.
|
| 1164 |
+
missing_arguments = [a for a in missing_arguments if not a.tokens]
|
| 1165 |
+
if missing_arguments:
|
| 1166 |
+
raise MissingArgumentError(argument=missing_arguments[0]) from exc
|
| 1167 |
+
if len(candidate) == 1:
|
| 1168 |
+
break
|
| 1169 |
+
# For discriminated unions pydantic prepends the discriminator
|
| 1170 |
+
# value (e.g. loc=("cat", "rainbow")). Strip leading elements
|
| 1171 |
+
# until we find a real child Argument.
|
| 1172 |
+
candidate = candidate[1:]
|
| 1173 |
+
# Fall through to ValidationError.
|
| 1174 |
+
|
| 1175 |
+
if isinstance(exc, pydantic.ValidationError):
|
| 1176 |
+
raise ValidationError(exception_message=str(exc), argument=self) from exc
|
| 1177 |
+
else:
|
| 1178 |
+
raise exc
|
.venv/lib/python3.10/site-packages/cyclopts/argument/_collection.py
ADDED
|
@@ -0,0 +1,767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ArgumentCollection class and related functionality."""
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import itertools
|
| 5 |
+
import json
|
| 6 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 7 |
+
from typing import TYPE_CHECKING, Any, SupportsIndex, TypeVar, overload
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from cyclopts.core import App
|
| 11 |
+
|
| 12 |
+
from cyclopts.exceptions import (
|
| 13 |
+
UnknownOptionError,
|
| 14 |
+
)
|
| 15 |
+
from cyclopts.field_info import (
|
| 16 |
+
signature_parameters,
|
| 17 |
+
)
|
| 18 |
+
from cyclopts.group import Group
|
| 19 |
+
from cyclopts.parameter import Parameter
|
| 20 |
+
from cyclopts.token import Token
|
| 21 |
+
from cyclopts.utils import UNSET, is_iterable
|
| 22 |
+
|
| 23 |
+
from ._argument import Argument
|
| 24 |
+
from .utils import (
|
| 25 |
+
KIND_PARENT_CHILD_REASSIGNMENT,
|
| 26 |
+
PARAMETER_SUBKEY_BLOCKER,
|
| 27 |
+
extract_docstring_help,
|
| 28 |
+
resolve_parameter_name,
|
| 29 |
+
to_cli_option_name,
|
| 30 |
+
walk_leaves,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
T = TypeVar("T")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ArgumentCollection(list[Argument]):
|
| 37 |
+
"""A list-like container for :class:`Argument`."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, *args):
|
| 40 |
+
super().__init__(*args)
|
| 41 |
+
|
| 42 |
+
def copy(self) -> "ArgumentCollection":
|
| 43 |
+
"""Returns a shallow copy of the :class:`ArgumentCollection`."""
|
| 44 |
+
return type(self)(self)
|
| 45 |
+
|
| 46 |
+
@overload
|
| 47 |
+
def __getitem__(self, term: SupportsIndex, /) -> Argument: ...
|
| 48 |
+
@overload
|
| 49 |
+
def __getitem__(self, term: slice, /) -> list[Argument]: ...
|
| 50 |
+
@overload
|
| 51 |
+
def __getitem__(self, term: str, /) -> Argument: ...
|
| 52 |
+
def __getitem__(
|
| 53 |
+
self,
|
| 54 |
+
term: str | SupportsIndex | slice,
|
| 55 |
+
) -> Argument | list[Argument]:
|
| 56 |
+
if isinstance(term, (SupportsIndex, slice)):
|
| 57 |
+
return super().__getitem__(term)
|
| 58 |
+
|
| 59 |
+
return self.get(term)
|
| 60 |
+
|
| 61 |
+
def __contains__(self, item: object, /) -> bool:
|
| 62 |
+
"""Check if an argument or argument name exists in the collection.
|
| 63 |
+
|
| 64 |
+
Parameters
|
| 65 |
+
----------
|
| 66 |
+
item : Argument | str
|
| 67 |
+
Either an Argument object or a string name/alias to search for.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
bool
|
| 72 |
+
True if the item is in the collection.
|
| 73 |
+
|
| 74 |
+
Examples
|
| 75 |
+
--------
|
| 76 |
+
>>> argument_collection = ArgumentCollection(
|
| 77 |
+
... [
|
| 78 |
+
... Argument(parameter=Parameter(name="--foo")),
|
| 79 |
+
... Argument(parameter=Parameter(name=("--bar", "-b"))),
|
| 80 |
+
... ]
|
| 81 |
+
... )
|
| 82 |
+
>>> "--foo" in argument_collection
|
| 83 |
+
True
|
| 84 |
+
>>> "-b" in argument_collection # Alias matching
|
| 85 |
+
True
|
| 86 |
+
>>> "--baz" in argument_collection
|
| 87 |
+
False
|
| 88 |
+
"""
|
| 89 |
+
if isinstance(item, str):
|
| 90 |
+
try:
|
| 91 |
+
self[item]
|
| 92 |
+
return True
|
| 93 |
+
except KeyError:
|
| 94 |
+
return False
|
| 95 |
+
else:
|
| 96 |
+
return super().__contains__(item)
|
| 97 |
+
|
| 98 |
+
@overload
|
| 99 |
+
def get(
|
| 100 |
+
self,
|
| 101 |
+
term: str | int,
|
| 102 |
+
default: type[UNSET] = ...,
|
| 103 |
+
*,
|
| 104 |
+
transform: Callable[[str], str] | None = None,
|
| 105 |
+
delimiter: str = ".",
|
| 106 |
+
) -> Argument: ...
|
| 107 |
+
@overload
|
| 108 |
+
def get(
|
| 109 |
+
self,
|
| 110 |
+
term: str | int,
|
| 111 |
+
default: T,
|
| 112 |
+
*,
|
| 113 |
+
transform: Callable[[str], str] | None = None,
|
| 114 |
+
delimiter: str = ".",
|
| 115 |
+
) -> Argument | T: ...
|
| 116 |
+
def get(
|
| 117 |
+
self,
|
| 118 |
+
term: str | int,
|
| 119 |
+
default: Any = UNSET,
|
| 120 |
+
*,
|
| 121 |
+
transform: Callable[[str], str] | None = None,
|
| 122 |
+
delimiter: str = ".",
|
| 123 |
+
) -> Argument | Any:
|
| 124 |
+
"""Get an :class:`Argument` by name or index.
|
| 125 |
+
|
| 126 |
+
This is a convenience wrapper around :meth:`match` that returns just
|
| 127 |
+
the :class:`Argument` object instead of a tuple.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
----------
|
| 131 |
+
term : str | int
|
| 132 |
+
Either a string keyword or an integer positional index.
|
| 133 |
+
default : Any
|
| 134 |
+
Default value to return if term not found. If :data:`~cyclopts.utils.UNSET` (default),
|
| 135 |
+
will raise :exc:`KeyError`/:exc:`IndexError`.
|
| 136 |
+
transform : Callable[[str], str] | None
|
| 137 |
+
Optional function to transform string terms before matching.
|
| 138 |
+
delimiter : str
|
| 139 |
+
Delimiter for nested field access.
|
| 140 |
+
|
| 141 |
+
Returns
|
| 142 |
+
-------
|
| 143 |
+
Argument | None
|
| 144 |
+
The matched :class:`Argument`, or ``default`` if provided and not found.
|
| 145 |
+
|
| 146 |
+
Raises
|
| 147 |
+
------
|
| 148 |
+
:exc:`KeyError`
|
| 149 |
+
If ``term`` is a string and not found (when ``default`` is :data:`~cyclopts.utils.UNSET`).
|
| 150 |
+
:exc:`IndexError`
|
| 151 |
+
If ``term`` is an int and is out-of-range (when ``default`` is :data:`~cyclopts.utils.UNSET`).
|
| 152 |
+
|
| 153 |
+
See Also
|
| 154 |
+
--------
|
| 155 |
+
:meth:`match` : Returns a tuple of (:class:`Argument`, keys, value) with more detailed information.
|
| 156 |
+
"""
|
| 157 |
+
try:
|
| 158 |
+
argument, _, _ = self.match(term, transform=transform, delimiter=delimiter)
|
| 159 |
+
return argument
|
| 160 |
+
except ValueError:
|
| 161 |
+
if default is UNSET:
|
| 162 |
+
if isinstance(term, str):
|
| 163 |
+
raise KeyError(f"No such Argument: {term}") from None
|
| 164 |
+
else:
|
| 165 |
+
raise IndexError(f"Argument index {term} out of range") from None
|
| 166 |
+
return default
|
| 167 |
+
|
| 168 |
+
def match(
|
| 169 |
+
self,
|
| 170 |
+
term: str | int,
|
| 171 |
+
*,
|
| 172 |
+
transform: Callable[[str], str] | None = None,
|
| 173 |
+
delimiter: str = ".",
|
| 174 |
+
) -> tuple[Argument, tuple[str, ...], Any]:
|
| 175 |
+
"""Matches CLI keyword or index to their :class:`Argument`.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
term: str | int
|
| 180 |
+
One of:
|
| 181 |
+
|
| 182 |
+
* :obj:`str` keyword like ``"--foo"`` or ``"-f"`` or ``"--foo.bar.baz"``.
|
| 183 |
+
|
| 184 |
+
* :obj:`int` global positional index.
|
| 185 |
+
|
| 186 |
+
Raises
|
| 187 |
+
------
|
| 188 |
+
ValueError
|
| 189 |
+
If the provided ``term`` doesn't match.
|
| 190 |
+
|
| 191 |
+
Returns
|
| 192 |
+
-------
|
| 193 |
+
Argument
|
| 194 |
+
Matched :class:`Argument`.
|
| 195 |
+
tuple[str, ...]
|
| 196 |
+
Python keys into :class:`Argument`. Non-empty iff :class:`Argument` accepts keys.
|
| 197 |
+
Any
|
| 198 |
+
Implicit value (if a flag). :obj:`~.UNSET` otherwise.
|
| 199 |
+
"""
|
| 200 |
+
best_match_argument, best_match_keys, best_implicit_value = None, None, UNSET
|
| 201 |
+
for argument in self:
|
| 202 |
+
try:
|
| 203 |
+
match_keys, implicit_value = argument.match(term, transform=transform, delimiter=delimiter)
|
| 204 |
+
except ValueError:
|
| 205 |
+
continue
|
| 206 |
+
if best_match_keys is None or len(match_keys) < len(best_match_keys):
|
| 207 |
+
best_match_keys = match_keys
|
| 208 |
+
best_match_argument = argument
|
| 209 |
+
best_implicit_value = implicit_value
|
| 210 |
+
if not match_keys:
|
| 211 |
+
break
|
| 212 |
+
|
| 213 |
+
if best_match_argument is None or best_match_keys is None:
|
| 214 |
+
raise ValueError(f"No Argument matches {term!r}")
|
| 215 |
+
|
| 216 |
+
return best_match_argument, best_match_keys, best_implicit_value
|
| 217 |
+
|
| 218 |
+
def _set_marks(self, val: bool):
|
| 219 |
+
for argument in self:
|
| 220 |
+
argument._marked = val
|
| 221 |
+
|
| 222 |
+
def _convert(self):
|
| 223 |
+
"""Convert and validate all elements."""
|
| 224 |
+
self._set_marks(False)
|
| 225 |
+
for argument in sorted(self, key=lambda x: x.keys):
|
| 226 |
+
if argument._marked:
|
| 227 |
+
continue
|
| 228 |
+
argument.convert_and_validate()
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def _from_type(
|
| 232 |
+
cls,
|
| 233 |
+
field_info,
|
| 234 |
+
keys: tuple[str, ...],
|
| 235 |
+
*default_parameters: Parameter | None,
|
| 236 |
+
group_lookup: dict[str, Group],
|
| 237 |
+
group_arguments: Group,
|
| 238 |
+
group_parameters: Group,
|
| 239 |
+
parse_docstring: bool = True,
|
| 240 |
+
docstring_lookup: dict[tuple[str, ...], Parameter] | None = None,
|
| 241 |
+
positional_index: int | None = None,
|
| 242 |
+
_resolve_groups: bool = True,
|
| 243 |
+
):
|
| 244 |
+
from cyclopts.parameter import get_parameters
|
| 245 |
+
|
| 246 |
+
out = cls()
|
| 247 |
+
|
| 248 |
+
if docstring_lookup is None:
|
| 249 |
+
docstring_lookup = {}
|
| 250 |
+
|
| 251 |
+
cyclopts_parameters_no_group = []
|
| 252 |
+
|
| 253 |
+
hint = field_info.hint
|
| 254 |
+
hint, hint_parameters = get_parameters(hint)
|
| 255 |
+
cyclopts_parameters_no_group.extend(hint_parameters)
|
| 256 |
+
|
| 257 |
+
if not keys:
|
| 258 |
+
if field_info.kind is field_info.VAR_KEYWORD:
|
| 259 |
+
hint = dict[str, hint]
|
| 260 |
+
elif field_info.kind is field_info.VAR_POSITIONAL:
|
| 261 |
+
hint = tuple[hint, ...]
|
| 262 |
+
|
| 263 |
+
if _resolve_groups:
|
| 264 |
+
cyclopts_parameters = []
|
| 265 |
+
for cparam in cyclopts_parameters_no_group:
|
| 266 |
+
resolved_groups = []
|
| 267 |
+
for group in cparam.group: # pyright:ignore
|
| 268 |
+
if isinstance(group, str):
|
| 269 |
+
group = group_lookup[group]
|
| 270 |
+
resolved_groups.append(group)
|
| 271 |
+
cyclopts_parameters.append(group.default_parameter)
|
| 272 |
+
cyclopts_parameters.append(cparam)
|
| 273 |
+
|
| 274 |
+
if resolved_groups:
|
| 275 |
+
has_visible_group = any(g.show for g in resolved_groups)
|
| 276 |
+
all_nameless = all(not g.name for g in resolved_groups)
|
| 277 |
+
|
| 278 |
+
if has_visible_group:
|
| 279 |
+
cyclopts_parameters.append(Parameter(group=resolved_groups))
|
| 280 |
+
elif all_nameless:
|
| 281 |
+
default_group = (
|
| 282 |
+
group_arguments
|
| 283 |
+
if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL)
|
| 284 |
+
else group_parameters
|
| 285 |
+
)
|
| 286 |
+
all_groups = (default_group,) + tuple(resolved_groups)
|
| 287 |
+
cyclopts_parameters.append(Parameter(group=all_groups))
|
| 288 |
+
else:
|
| 289 |
+
cyclopts_parameters.append(Parameter(group=resolved_groups))
|
| 290 |
+
else:
|
| 291 |
+
cyclopts_parameters = cyclopts_parameters_no_group
|
| 292 |
+
|
| 293 |
+
upstream_parameter = Parameter.combine(
|
| 294 |
+
(
|
| 295 |
+
Parameter(group=group_arguments)
|
| 296 |
+
if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL)
|
| 297 |
+
else Parameter(group=group_parameters)
|
| 298 |
+
),
|
| 299 |
+
*default_parameters,
|
| 300 |
+
)
|
| 301 |
+
immediate_parameter = Parameter.combine(*cyclopts_parameters)
|
| 302 |
+
|
| 303 |
+
if keys:
|
| 304 |
+
cparam = Parameter.combine(
|
| 305 |
+
upstream_parameter,
|
| 306 |
+
PARAMETER_SUBKEY_BLOCKER,
|
| 307 |
+
immediate_parameter,
|
| 308 |
+
)
|
| 309 |
+
cparam = Parameter.combine(
|
| 310 |
+
cparam,
|
| 311 |
+
Parameter(
|
| 312 |
+
name=resolve_parameter_name(
|
| 313 |
+
upstream_parameter.name, # pyright: ignore
|
| 314 |
+
(immediate_parameter.name or tuple(cparam.name_transform(x) for x in field_info.names))
|
| 315 |
+
+ cparam.alias, # pyright: ignore
|
| 316 |
+
)
|
| 317 |
+
),
|
| 318 |
+
)
|
| 319 |
+
else:
|
| 320 |
+
cparam = Parameter.combine(
|
| 321 |
+
upstream_parameter,
|
| 322 |
+
immediate_parameter,
|
| 323 |
+
)
|
| 324 |
+
assert isinstance(cparam.alias, tuple)
|
| 325 |
+
if cparam.name:
|
| 326 |
+
if field_info.is_keyword:
|
| 327 |
+
assert isinstance(cparam.name, tuple)
|
| 328 |
+
cparam = Parameter.combine(
|
| 329 |
+
cparam, Parameter(name=resolve_parameter_name(cparam.name + cparam.alias))
|
| 330 |
+
)
|
| 331 |
+
else:
|
| 332 |
+
if field_info.kind in (field_info.POSITIONAL_ONLY, field_info.VAR_POSITIONAL):
|
| 333 |
+
cparam = Parameter.combine(cparam, Parameter(name=(name.upper() for name in field_info.names)))
|
| 334 |
+
elif field_info.kind is field_info.VAR_KEYWORD:
|
| 335 |
+
cparam = Parameter.combine(cparam, Parameter(name=("--[KEYWORD]",)))
|
| 336 |
+
else:
|
| 337 |
+
assert cparam.name_transform is not None
|
| 338 |
+
cparam = Parameter.combine(
|
| 339 |
+
cparam,
|
| 340 |
+
Parameter(
|
| 341 |
+
name=tuple("--" + cparam.name_transform(name) for name in field_info.names)
|
| 342 |
+
+ resolve_parameter_name(cparam.alias)
|
| 343 |
+
),
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
if field_info.is_keyword_only:
|
| 347 |
+
positional_index = None
|
| 348 |
+
|
| 349 |
+
argument = Argument(field_info=field_info, parameter=cparam, keys=keys, hint=hint)
|
| 350 |
+
|
| 351 |
+
if positional_index is not None:
|
| 352 |
+
if not argument._accepts_keywords or argument._enum_flag_type:
|
| 353 |
+
argument.index = positional_index
|
| 354 |
+
positional_index += 1
|
| 355 |
+
|
| 356 |
+
out.append(argument)
|
| 357 |
+
if argument._accepts_keywords:
|
| 358 |
+
hint_docstring_lookup = extract_docstring_help(argument.hint) if parse_docstring else {}
|
| 359 |
+
hint_docstring_lookup.update(docstring_lookup)
|
| 360 |
+
|
| 361 |
+
for sub_field_name, sub_field_info in argument._lookup.items():
|
| 362 |
+
updated_kind = KIND_PARENT_CHILD_REASSIGNMENT[(argument.field_info.kind, sub_field_info.kind)]
|
| 363 |
+
if updated_kind is None:
|
| 364 |
+
continue
|
| 365 |
+
|
| 366 |
+
sub_field_info.kind = updated_kind
|
| 367 |
+
|
| 368 |
+
if sub_field_info.is_keyword_only:
|
| 369 |
+
positional_index = None
|
| 370 |
+
|
| 371 |
+
subkey_docstring_lookup = {
|
| 372 |
+
k[1:]: v for k, v in hint_docstring_lookup.items() if k[0] == sub_field_name and len(k) > 1
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
subkey_argument_collection = cls._from_type(
|
| 376 |
+
sub_field_info,
|
| 377 |
+
keys + (sub_field_name,),
|
| 378 |
+
cparam,
|
| 379 |
+
(
|
| 380 |
+
Parameter(help=sub_field_info.help)
|
| 381 |
+
if sub_field_info.help
|
| 382 |
+
else hint_docstring_lookup.get((sub_field_name,))
|
| 383 |
+
),
|
| 384 |
+
Parameter(required=argument.required & sub_field_info.required),
|
| 385 |
+
group_lookup=group_lookup,
|
| 386 |
+
group_arguments=group_arguments,
|
| 387 |
+
group_parameters=group_parameters,
|
| 388 |
+
parse_docstring=parse_docstring,
|
| 389 |
+
docstring_lookup=subkey_docstring_lookup,
|
| 390 |
+
positional_index=positional_index,
|
| 391 |
+
_resolve_groups=_resolve_groups,
|
| 392 |
+
)
|
| 393 |
+
if subkey_argument_collection:
|
| 394 |
+
argument.children.append(subkey_argument_collection[0])
|
| 395 |
+
out.extend(subkey_argument_collection)
|
| 396 |
+
|
| 397 |
+
if positional_index is not None:
|
| 398 |
+
positional_index = subkey_argument_collection._max_index
|
| 399 |
+
if positional_index is not None:
|
| 400 |
+
positional_index += 1
|
| 401 |
+
|
| 402 |
+
return out
|
| 403 |
+
|
| 404 |
+
@classmethod
|
| 405 |
+
def _from_callable(
|
| 406 |
+
cls,
|
| 407 |
+
func: Callable,
|
| 408 |
+
*default_parameters: Parameter | None,
|
| 409 |
+
group_lookup: dict[str, Group] | None = None,
|
| 410 |
+
group_arguments: Group | None = None,
|
| 411 |
+
group_parameters: Group | None = None,
|
| 412 |
+
parse_docstring: bool = True,
|
| 413 |
+
_resolve_groups: bool = True,
|
| 414 |
+
):
|
| 415 |
+
out = cls()
|
| 416 |
+
|
| 417 |
+
if group_arguments is None:
|
| 418 |
+
group_arguments = Group.create_default_arguments()
|
| 419 |
+
if group_parameters is None:
|
| 420 |
+
group_parameters = Group.create_default_parameters()
|
| 421 |
+
|
| 422 |
+
if _resolve_groups:
|
| 423 |
+
group_lookup = {
|
| 424 |
+
group.name: group
|
| 425 |
+
for group in _resolve_groups_from_callable(
|
| 426 |
+
func,
|
| 427 |
+
*default_parameters,
|
| 428 |
+
group_arguments=group_arguments,
|
| 429 |
+
group_parameters=group_parameters,
|
| 430 |
+
)
|
| 431 |
+
}
|
| 432 |
+
else:
|
| 433 |
+
group_lookup = {}
|
| 434 |
+
|
| 435 |
+
docstring_lookup = extract_docstring_help(func) if parse_docstring else {}
|
| 436 |
+
positional_index = 0
|
| 437 |
+
for field_info in signature_parameters(func).values():
|
| 438 |
+
if parse_docstring:
|
| 439 |
+
subkey_docstring_lookup = {
|
| 440 |
+
k[1:]: v for k, v in docstring_lookup.items() if k[0] == field_info.name and len(k) > 1
|
| 441 |
+
}
|
| 442 |
+
else:
|
| 443 |
+
subkey_docstring_lookup = None
|
| 444 |
+
iparam_argument_collection = cls._from_type(
|
| 445 |
+
field_info,
|
| 446 |
+
(),
|
| 447 |
+
*default_parameters,
|
| 448 |
+
Parameter(help=field_info.help) if field_info.help else docstring_lookup.get((field_info.name,)),
|
| 449 |
+
group_lookup=group_lookup,
|
| 450 |
+
group_arguments=group_arguments,
|
| 451 |
+
group_parameters=group_parameters,
|
| 452 |
+
positional_index=positional_index,
|
| 453 |
+
parse_docstring=parse_docstring,
|
| 454 |
+
docstring_lookup=subkey_docstring_lookup,
|
| 455 |
+
_resolve_groups=_resolve_groups,
|
| 456 |
+
)
|
| 457 |
+
if positional_index is not None:
|
| 458 |
+
positional_index = iparam_argument_collection._max_index
|
| 459 |
+
if positional_index is not None:
|
| 460 |
+
positional_index += 1
|
| 461 |
+
out.extend(iparam_argument_collection)
|
| 462 |
+
|
| 463 |
+
return out
|
| 464 |
+
|
| 465 |
+
@property
|
| 466 |
+
def groups(self):
|
| 467 |
+
groups = []
|
| 468 |
+
for argument in self:
|
| 469 |
+
assert isinstance(argument.parameter.group, tuple)
|
| 470 |
+
for group in argument.parameter.group:
|
| 471 |
+
if group not in groups:
|
| 472 |
+
groups.append(group)
|
| 473 |
+
return groups
|
| 474 |
+
|
| 475 |
+
@property
|
| 476 |
+
def _root_arguments(self):
|
| 477 |
+
for argument in self:
|
| 478 |
+
if not argument.keys:
|
| 479 |
+
yield argument
|
| 480 |
+
|
| 481 |
+
@property
|
| 482 |
+
def _max_index(self) -> int | None:
|
| 483 |
+
return max((x.index for x in self if x.index is not None), default=None)
|
| 484 |
+
|
| 485 |
+
def filter_by(
|
| 486 |
+
self,
|
| 487 |
+
*,
|
| 488 |
+
group: Group | None = None,
|
| 489 |
+
has_tokens: bool | None = None,
|
| 490 |
+
has_tree_tokens: bool | None = None,
|
| 491 |
+
keys_prefix: tuple[str, ...] | None = None,
|
| 492 |
+
kind: inspect._ParameterKind | None = None,
|
| 493 |
+
parse: bool | None = None,
|
| 494 |
+
show: bool | None = None,
|
| 495 |
+
value_set: bool | None = None,
|
| 496 |
+
) -> "ArgumentCollection":
|
| 497 |
+
"""Filter the :class:`ArgumentCollection`.
|
| 498 |
+
|
| 499 |
+
All non-None filters will be applied.
|
| 500 |
+
|
| 501 |
+
Parameters
|
| 502 |
+
----------
|
| 503 |
+
group: Group | None
|
| 504 |
+
The :class:`.Group` the arguments should be in.
|
| 505 |
+
has_tokens: bool | None
|
| 506 |
+
Immediately has tokens (not including children).
|
| 507 |
+
has_tree_tokens: bool | None
|
| 508 |
+
:class:`Argument` and/or it's children have parsed tokens.
|
| 509 |
+
kind: inspect._ParameterKind | None
|
| 510 |
+
The :attr:`~inspect.Parameter.kind` of the argument.
|
| 511 |
+
parse: bool | None
|
| 512 |
+
If the argument is intended to be parsed or not.
|
| 513 |
+
show: bool | None
|
| 514 |
+
The :class:`Argument` is intended to be show on the help page.
|
| 515 |
+
value_set: bool | None
|
| 516 |
+
The converted value is set.
|
| 517 |
+
"""
|
| 518 |
+
ac = self.copy()
|
| 519 |
+
cls = type(self)
|
| 520 |
+
|
| 521 |
+
if group is not None:
|
| 522 |
+
ac = cls(x for x in ac if group in x.parameter.group) # pyright: ignore
|
| 523 |
+
if kind is not None:
|
| 524 |
+
ac = cls(x for x in ac if x.field_info.kind == kind)
|
| 525 |
+
if has_tokens is not None:
|
| 526 |
+
ac = cls(x for x in ac if not (bool(x.tokens) ^ bool(has_tokens)))
|
| 527 |
+
if has_tree_tokens is not None:
|
| 528 |
+
ac = cls(x for x in ac if not (bool(x.tokens) ^ bool(has_tree_tokens)))
|
| 529 |
+
if keys_prefix is not None:
|
| 530 |
+
ac = cls(x for x in ac if x.keys[: len(keys_prefix)] == keys_prefix)
|
| 531 |
+
if show is not None:
|
| 532 |
+
ac = cls(x for x in ac if not (x.show ^ bool(show)))
|
| 533 |
+
if value_set is not None:
|
| 534 |
+
ac = cls(x for x in ac if ((x.value is UNSET) ^ bool(value_set)))
|
| 535 |
+
if parse is not None:
|
| 536 |
+
ac = cls(x for x in ac if not (x.parse ^ parse))
|
| 537 |
+
|
| 538 |
+
return ac
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _resolve_groups_from_callable(
|
| 542 |
+
func: Callable[..., Any],
|
| 543 |
+
*default_parameters: Parameter | None,
|
| 544 |
+
group_arguments: Group | None = None,
|
| 545 |
+
group_parameters: Group | None = None,
|
| 546 |
+
) -> list[Group]:
|
| 547 |
+
argument_collection = ArgumentCollection._from_callable(
|
| 548 |
+
func,
|
| 549 |
+
*default_parameters,
|
| 550 |
+
group_arguments=group_arguments,
|
| 551 |
+
group_parameters=group_parameters,
|
| 552 |
+
parse_docstring=False,
|
| 553 |
+
_resolve_groups=False,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
resolved_groups = []
|
| 557 |
+
if group_arguments is not None:
|
| 558 |
+
resolved_groups.append(group_arguments)
|
| 559 |
+
if group_parameters is not None:
|
| 560 |
+
resolved_groups.append(group_parameters)
|
| 561 |
+
|
| 562 |
+
for argument in argument_collection:
|
| 563 |
+
for group in argument.parameter.group: # pyright: ignore
|
| 564 |
+
if not isinstance(group, Group):
|
| 565 |
+
continue
|
| 566 |
+
|
| 567 |
+
if any(group != x and x._name == group._name for x in resolved_groups):
|
| 568 |
+
raise ValueError("Cannot register 2 distinct Group objects with same name.")
|
| 569 |
+
|
| 570 |
+
if group.default_parameter is not None and group.default_parameter.group:
|
| 571 |
+
raise ValueError("Group.default_parameter cannot have a specified group.") # pragma: no cover
|
| 572 |
+
|
| 573 |
+
try:
|
| 574 |
+
next(x for x in resolved_groups if x._name == group._name)
|
| 575 |
+
except StopIteration:
|
| 576 |
+
resolved_groups.append(group)
|
| 577 |
+
|
| 578 |
+
for argument in argument_collection:
|
| 579 |
+
for group in argument.parameter.group: # pyright: ignore
|
| 580 |
+
if not isinstance(group, str):
|
| 581 |
+
continue
|
| 582 |
+
try:
|
| 583 |
+
next(x for x in resolved_groups if x.name == group)
|
| 584 |
+
except StopIteration:
|
| 585 |
+
resolved_groups.append(Group(group))
|
| 586 |
+
|
| 587 |
+
return resolved_groups
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _meta_arguments(apps: Sequence["App"]) -> ArgumentCollection:
|
| 591 |
+
argument_collection = ArgumentCollection()
|
| 592 |
+
for app in apps:
|
| 593 |
+
if app._meta is None:
|
| 594 |
+
continue
|
| 595 |
+
argument_collection.extend(app._meta.assemble_argument_collection())
|
| 596 |
+
return argument_collection
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def _is_valid_option_key(option_key: str, arguments: "ArgumentCollection") -> bool:
|
| 600 |
+
"""Check if option_key corresponds to a valid root argument.
|
| 601 |
+
|
| 602 |
+
When processing nested config keys like {"p": {"timeout": 3}}, the fallback
|
| 603 |
+
alias matching needs to verify that "p" is actually a valid parameter before
|
| 604 |
+
matching nested fields. This prevents unknown keys like "np" from incorrectly
|
| 605 |
+
matching against valid nested arguments.
|
| 606 |
+
|
| 607 |
+
If no root argument exists (children-only collection, e.g., from JSON env var
|
| 608 |
+
processing), returns True since the option_key is implicitly valid.
|
| 609 |
+
|
| 610 |
+
Parameters
|
| 611 |
+
----------
|
| 612 |
+
option_key : str
|
| 613 |
+
The top-level config key to validate (e.g., "p" from {"p": {"timeout": 3}}).
|
| 614 |
+
arguments : ArgumentCollection
|
| 615 |
+
The argument collection to validate against.
|
| 616 |
+
|
| 617 |
+
Returns
|
| 618 |
+
-------
|
| 619 |
+
bool
|
| 620 |
+
True if option_key is valid, False otherwise.
|
| 621 |
+
"""
|
| 622 |
+
root_arg = next((arg for arg in arguments if arg.keys == ()), None)
|
| 623 |
+
if not root_arg:
|
| 624 |
+
return True # Children-only collection, implicitly valid
|
| 625 |
+
cli_parent = to_cli_option_name(option_key)
|
| 626 |
+
return bool(
|
| 627 |
+
(root_arg.parameter.name and cli_parent in root_arg.parameter.name) or option_key in root_arg.field_info.names
|
| 628 |
+
)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def update_argument_collection(
|
| 632 |
+
config: dict,
|
| 633 |
+
source: str,
|
| 634 |
+
arguments: ArgumentCollection,
|
| 635 |
+
apps: Sequence["App"] | None = None,
|
| 636 |
+
*,
|
| 637 |
+
root_keys: Iterable[str],
|
| 638 |
+
allow_unknown: bool,
|
| 639 |
+
):
|
| 640 |
+
"""Updates an argument collection with values from a configuration dictionary.
|
| 641 |
+
|
| 642 |
+
This function takes configuration data (typically from JSON, TOML, YAML files
|
| 643 |
+
or environment variables) and populates the corresponding arguments in the
|
| 644 |
+
ArgumentCollection with tokens representing those values.
|
| 645 |
+
|
| 646 |
+
The function handles various naming conventions, including:
|
| 647 |
+
- Exact matches (e.g., "storage_class" matches "storage_class")
|
| 648 |
+
- Transformed matches (e.g., "storage-class" matches "storage_class")
|
| 649 |
+
- Pydantic aliases (e.g., "storageClass" matches field with alias "storageClass")
|
| 650 |
+
|
| 651 |
+
Parameters
|
| 652 |
+
----------
|
| 653 |
+
config : dict
|
| 654 |
+
Configuration dictionary with nested structure mapping to CLI arguments.
|
| 655 |
+
source : str
|
| 656 |
+
Source identifier (e.g., file path or "env") for error messages and tracking.
|
| 657 |
+
arguments : ArgumentCollection
|
| 658 |
+
Collection of arguments to populate with configuration values.
|
| 659 |
+
apps : Optional[Sequence[App]]
|
| 660 |
+
Stack of App instances for meta-argument handling.
|
| 661 |
+
We need to know all the meta-apps leading up to the current application so that we can
|
| 662 |
+
properly detect unknown keys.
|
| 663 |
+
root_keys : Iterable[str]
|
| 664 |
+
Base path keys to prepend to all configuration keys.
|
| 665 |
+
allow_unknown : bool
|
| 666 |
+
If True, ignore unrecognized configuration keys instead of raising errors.
|
| 667 |
+
|
| 668 |
+
Raises
|
| 669 |
+
------
|
| 670 |
+
UnknownOptionError
|
| 671 |
+
If a configuration key doesn't match any argument and allow_unknown is False.
|
| 672 |
+
|
| 673 |
+
Notes
|
| 674 |
+
-----
|
| 675 |
+
Arguments that already have tokens are skipped to preserve command-line
|
| 676 |
+
precedence over configuration files.
|
| 677 |
+
"""
|
| 678 |
+
meta_arguments = _meta_arguments(apps or ())
|
| 679 |
+
|
| 680 |
+
do_not_update = {}
|
| 681 |
+
|
| 682 |
+
for option_key, option_value in config.items():
|
| 683 |
+
for subkeys, value in walk_leaves(option_value):
|
| 684 |
+
cli_option_name = to_cli_option_name(option_key, *subkeys)
|
| 685 |
+
complete_keyword = "".join(f"[{k}]" for k in itertools.chain(root_keys, (option_key,), subkeys))
|
| 686 |
+
|
| 687 |
+
try:
|
| 688 |
+
meta_arguments.match(cli_option_name)
|
| 689 |
+
continue
|
| 690 |
+
except ValueError:
|
| 691 |
+
pass
|
| 692 |
+
|
| 693 |
+
argument = None
|
| 694 |
+
remaining_keys = ()
|
| 695 |
+
try:
|
| 696 |
+
argument, remaining_keys, _ = arguments.match(cli_option_name)
|
| 697 |
+
except ValueError:
|
| 698 |
+
if subkeys and _is_valid_option_key(option_key, arguments):
|
| 699 |
+
for arg in arguments:
|
| 700 |
+
if len(subkeys) != len(arg.keys):
|
| 701 |
+
continue
|
| 702 |
+
|
| 703 |
+
all_match = True
|
| 704 |
+
for i, (subkey, arg_key) in enumerate(zip(subkeys, arg.keys, strict=False)):
|
| 705 |
+
if subkey == arg_key:
|
| 706 |
+
continue
|
| 707 |
+
|
| 708 |
+
if i == len(arg.keys) - 1:
|
| 709 |
+
if subkey not in arg.field_info.names:
|
| 710 |
+
all_match = False
|
| 711 |
+
break
|
| 712 |
+
else:
|
| 713 |
+
parent_keys = arg.keys[: i + 1]
|
| 714 |
+
alias_found = False
|
| 715 |
+
for parent_arg in arguments:
|
| 716 |
+
if parent_arg.keys == parent_keys and subkey in parent_arg.field_info.names:
|
| 717 |
+
alias_found = True
|
| 718 |
+
break
|
| 719 |
+
if not alias_found:
|
| 720 |
+
all_match = False
|
| 721 |
+
break
|
| 722 |
+
|
| 723 |
+
if all_match:
|
| 724 |
+
argument = arg
|
| 725 |
+
remaining_keys = ()
|
| 726 |
+
break
|
| 727 |
+
|
| 728 |
+
if not argument:
|
| 729 |
+
if allow_unknown:
|
| 730 |
+
continue
|
| 731 |
+
if apps and apps[-1]._meta_parent:
|
| 732 |
+
continue
|
| 733 |
+
raise UnknownOptionError(
|
| 734 |
+
token=Token(keyword=complete_keyword, source=source), argument_collection=arguments
|
| 735 |
+
) from None
|
| 736 |
+
|
| 737 |
+
if do_not_update.setdefault(id(argument), bool(argument.tokens)):
|
| 738 |
+
continue
|
| 739 |
+
|
| 740 |
+
if not is_iterable(value):
|
| 741 |
+
value = (value,)
|
| 742 |
+
|
| 743 |
+
if value:
|
| 744 |
+
for i, v in enumerate(value):
|
| 745 |
+
if v is None:
|
| 746 |
+
token = Token(
|
| 747 |
+
keyword=complete_keyword,
|
| 748 |
+
implicit_value=None,
|
| 749 |
+
source=source,
|
| 750 |
+
index=i,
|
| 751 |
+
keys=remaining_keys,
|
| 752 |
+
)
|
| 753 |
+
else:
|
| 754 |
+
if isinstance(v, dict | list):
|
| 755 |
+
# Serialize to JSON string; will be deserialized in Argument._json()
|
| 756 |
+
value_str = json.dumps(v)
|
| 757 |
+
else:
|
| 758 |
+
value_str = str(v)
|
| 759 |
+
token = Token(
|
| 760 |
+
keyword=complete_keyword, value=value_str, source=source, index=i, keys=remaining_keys
|
| 761 |
+
)
|
| 762 |
+
argument.append(token)
|
| 763 |
+
else:
|
| 764 |
+
token = Token(
|
| 765 |
+
keyword=complete_keyword, implicit_value=value, source=source, index=0, keys=remaining_keys
|
| 766 |
+
)
|
| 767 |
+
argument.append(token)
|
.venv/lib/python3.10/site-packages/cyclopts/argument/utils.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helper functions and constants for the argument package."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from collections.abc import Callable, Iterator
|
| 5 |
+
from contextlib import suppress
|
| 6 |
+
from enum import Enum, Flag
|
| 7 |
+
from functools import partial
|
| 8 |
+
from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, get_args, get_origin
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from cyclopts.argument._argument import Argument
|
| 12 |
+
|
| 13 |
+
F = TypeVar("F", bound=Flag)
|
| 14 |
+
|
| 15 |
+
from cyclopts._convert import convert_enum_flag
|
| 16 |
+
from cyclopts.annotations import (
|
| 17 |
+
ITERABLE_TYPES,
|
| 18 |
+
is_class_and_subclass,
|
| 19 |
+
is_union,
|
| 20 |
+
resolve_annotated,
|
| 21 |
+
)
|
| 22 |
+
from cyclopts.field_info import (
|
| 23 |
+
KEYWORD_ONLY,
|
| 24 |
+
POSITIONAL_ONLY,
|
| 25 |
+
POSITIONAL_OR_KEYWORD,
|
| 26 |
+
VAR_KEYWORD,
|
| 27 |
+
VAR_POSITIONAL,
|
| 28 |
+
FieldInfo,
|
| 29 |
+
)
|
| 30 |
+
from cyclopts.parameter import Parameter
|
| 31 |
+
|
| 32 |
+
if sys.version_info >= (3, 12): # pragma: no cover
|
| 33 |
+
from typing import TypeAliasType
|
| 34 |
+
else: # pragma: no cover
|
| 35 |
+
TypeAliasType = None
|
| 36 |
+
|
| 37 |
+
PARAMETER_SUBKEY_BLOCKER = Parameter(
|
| 38 |
+
name=None,
|
| 39 |
+
alias=None,
|
| 40 |
+
converter=None, # pyright: ignore
|
| 41 |
+
validator=None,
|
| 42 |
+
accepts_keys=None,
|
| 43 |
+
consume_multiple=None,
|
| 44 |
+
env_var=None,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
KIND_PARENT_CHILD_REASSIGNMENT = {
|
| 48 |
+
(POSITIONAL_OR_KEYWORD, POSITIONAL_OR_KEYWORD): POSITIONAL_OR_KEYWORD,
|
| 49 |
+
(POSITIONAL_OR_KEYWORD, POSITIONAL_ONLY): POSITIONAL_ONLY,
|
| 50 |
+
(POSITIONAL_OR_KEYWORD, KEYWORD_ONLY): KEYWORD_ONLY,
|
| 51 |
+
(POSITIONAL_OR_KEYWORD, VAR_POSITIONAL): VAR_POSITIONAL,
|
| 52 |
+
(POSITIONAL_OR_KEYWORD, VAR_KEYWORD): VAR_KEYWORD,
|
| 53 |
+
(POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD): POSITIONAL_ONLY,
|
| 54 |
+
(POSITIONAL_ONLY, POSITIONAL_ONLY): POSITIONAL_ONLY,
|
| 55 |
+
(POSITIONAL_ONLY, KEYWORD_ONLY): None,
|
| 56 |
+
(POSITIONAL_ONLY, VAR_POSITIONAL): VAR_POSITIONAL,
|
| 57 |
+
(POSITIONAL_ONLY, VAR_KEYWORD): None,
|
| 58 |
+
(KEYWORD_ONLY, POSITIONAL_OR_KEYWORD): KEYWORD_ONLY,
|
| 59 |
+
(KEYWORD_ONLY, POSITIONAL_ONLY): None,
|
| 60 |
+
(KEYWORD_ONLY, KEYWORD_ONLY): KEYWORD_ONLY,
|
| 61 |
+
(KEYWORD_ONLY, VAR_POSITIONAL): None,
|
| 62 |
+
(KEYWORD_ONLY, VAR_KEYWORD): VAR_KEYWORD,
|
| 63 |
+
(VAR_POSITIONAL, POSITIONAL_OR_KEYWORD): POSITIONAL_ONLY,
|
| 64 |
+
(VAR_POSITIONAL, POSITIONAL_ONLY): POSITIONAL_ONLY,
|
| 65 |
+
(VAR_POSITIONAL, KEYWORD_ONLY): None,
|
| 66 |
+
(VAR_POSITIONAL, VAR_POSITIONAL): VAR_POSITIONAL,
|
| 67 |
+
(VAR_POSITIONAL, VAR_KEYWORD): None,
|
| 68 |
+
(VAR_KEYWORD, POSITIONAL_OR_KEYWORD): KEYWORD_ONLY,
|
| 69 |
+
(VAR_KEYWORD, POSITIONAL_ONLY): None,
|
| 70 |
+
(VAR_KEYWORD, KEYWORD_ONLY): KEYWORD_ONLY,
|
| 71 |
+
(VAR_KEYWORD, VAR_POSITIONAL): None,
|
| 72 |
+
(VAR_KEYWORD, VAR_KEYWORD): VAR_KEYWORD,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_choices_from_hint(type_: type, name_transform: Callable[[str], str]) -> list[str]:
|
| 77 |
+
"""Extract completion choices from a type hint.
|
| 78 |
+
|
| 79 |
+
Recursively extracts choices from Literal types, Enum types, and Union types.
|
| 80 |
+
|
| 81 |
+
Parameters
|
| 82 |
+
----------
|
| 83 |
+
type_ : type
|
| 84 |
+
Type annotation to extract choices from.
|
| 85 |
+
name_transform : Callable[[str], str]
|
| 86 |
+
Function to transform choice names (e.g., for case conversion).
|
| 87 |
+
|
| 88 |
+
Returns
|
| 89 |
+
-------
|
| 90 |
+
list[str]
|
| 91 |
+
List of choice strings extracted from the type hint.
|
| 92 |
+
"""
|
| 93 |
+
get_choices = partial(get_choices_from_hint, name_transform=name_transform)
|
| 94 |
+
choices = []
|
| 95 |
+
_origin = get_origin(type_)
|
| 96 |
+
if isinstance(type_, type) and is_class_and_subclass(type_, Enum):
|
| 97 |
+
choices.extend(name_transform(x) for x in type_.__members__)
|
| 98 |
+
elif is_union(_origin):
|
| 99 |
+
inner_choices = [get_choices(inner) for inner in get_args(type_)]
|
| 100 |
+
for x in inner_choices:
|
| 101 |
+
if x:
|
| 102 |
+
choices.extend(x)
|
| 103 |
+
elif _origin is Literal:
|
| 104 |
+
choices.extend(str(x) for x in get_args(type_))
|
| 105 |
+
elif _origin in ITERABLE_TYPES:
|
| 106 |
+
args = get_args(type_)
|
| 107 |
+
if len(args) == 1 or (_origin is tuple and len(args) == 2 and args[1] is Ellipsis):
|
| 108 |
+
choices.extend(get_choices(args[0]))
|
| 109 |
+
elif _origin is Annotated:
|
| 110 |
+
choices.extend(get_choices(resolve_annotated(type_)))
|
| 111 |
+
elif TypeAliasType is not None and isinstance(type_, TypeAliasType):
|
| 112 |
+
choices.extend(get_choices(type_.__value__))
|
| 113 |
+
return choices
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def startswith(string, prefix):
|
| 117 |
+
def normalize(s):
|
| 118 |
+
return s.replace("_", "-")
|
| 119 |
+
|
| 120 |
+
return normalize(string).startswith(normalize(prefix))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def missing_keys_factory(
|
| 124 |
+
get_field_info: Callable[[Any], dict[str, FieldInfo]],
|
| 125 |
+
) -> Callable[["Argument", dict[str, Any]], list[str]]:
|
| 126 |
+
def inner(argument: "Argument", data: dict[str, Any]) -> list[str]:
|
| 127 |
+
provided_keys = set(data)
|
| 128 |
+
field_info = get_field_info(argument.hint)
|
| 129 |
+
return [k for k, v in field_info.items() if (v.required and k not in provided_keys)]
|
| 130 |
+
|
| 131 |
+
return inner
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def enum_flag_from_dict(
|
| 135 |
+
enum_type: type[F],
|
| 136 |
+
data: dict[str, bool],
|
| 137 |
+
name_transform: Callable[[str], str],
|
| 138 |
+
) -> F:
|
| 139 |
+
"""Convert a dictionary of boolean flags to a Flag enum value.
|
| 140 |
+
|
| 141 |
+
Parameters
|
| 142 |
+
----------
|
| 143 |
+
enum_type : type[F]
|
| 144 |
+
The Flag enum type to convert to.
|
| 145 |
+
data : dict[str, bool]
|
| 146 |
+
Dictionary mapping flag names to boolean values.
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
F
|
| 151 |
+
The combined flag value.
|
| 152 |
+
"""
|
| 153 |
+
return convert_enum_flag(enum_type, (k for k, v in data.items() if v), name_transform)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def extract_docstring_help(f: Callable) -> dict[tuple[str, ...], Parameter]:
|
| 157 |
+
from docstring_parser import parse_from_object
|
| 158 |
+
|
| 159 |
+
with suppress(AttributeError):
|
| 160 |
+
f = f.func # pyright: ignore[reportFunctionMemberAccess]
|
| 161 |
+
|
| 162 |
+
result = {}
|
| 163 |
+
|
| 164 |
+
# For classes, walk through MRO to include base class fields.
|
| 165 |
+
# parse_from_object only extracts docstrings from the **immediate** class's source code,
|
| 166 |
+
# not from inherited fields.
|
| 167 |
+
# From docstring_parser docs:
|
| 168 |
+
#
|
| 169 |
+
# When given a class, only the attribute docstrings of that class are parsed, not its
|
| 170 |
+
# inherited classes. This is a design decision. Separate calls to this function
|
| 171 |
+
# should be performed to get attribute docstrings of parent classes.
|
| 172 |
+
if mro := getattr(f, "__mro__", None):
|
| 173 |
+
# Process base classes first (reversed MRO order), so derived classes can override
|
| 174 |
+
# their parent's docstrings if they redefine the same field with a new docstring.
|
| 175 |
+
for base_class in reversed(mro[:-1]): # Exclude 'object'
|
| 176 |
+
try:
|
| 177 |
+
parsed = parse_from_object(base_class)
|
| 178 |
+
for dparam in parsed.params:
|
| 179 |
+
result[tuple(dparam.arg_name.split("."))] = Parameter(help=dparam.description)
|
| 180 |
+
except (TypeError, AttributeError):
|
| 181 |
+
# Some base classes may not have parseable docstrings (e.g., built-in classes)
|
| 182 |
+
continue
|
| 183 |
+
else:
|
| 184 |
+
# For functions/callables (original behavior)
|
| 185 |
+
try:
|
| 186 |
+
parsed = parse_from_object(f)
|
| 187 |
+
for dparam in parsed.params:
|
| 188 |
+
result[tuple(dparam.arg_name.split("."))] = Parameter(help=dparam.description)
|
| 189 |
+
except (TypeError, AttributeError):
|
| 190 |
+
# parse_from_object may fail for some callables
|
| 191 |
+
pass
|
| 192 |
+
|
| 193 |
+
return result
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def resolve_parameter_name_helper(elem):
|
| 197 |
+
if elem.endswith("*"):
|
| 198 |
+
elem = elem[:-1].rstrip(".")
|
| 199 |
+
if elem and not elem.startswith("-"):
|
| 200 |
+
elem = "--" + elem
|
| 201 |
+
return elem
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def resolve_parameter_name(*argss: tuple[str, ...]) -> tuple[str, ...]:
|
| 205 |
+
"""Resolve parameter names by combining and formatting multiple tuples of strings.
|
| 206 |
+
|
| 207 |
+
Parameters
|
| 208 |
+
----------
|
| 209 |
+
*argss
|
| 210 |
+
Each tuple represents a group of parameter name components.
|
| 211 |
+
|
| 212 |
+
Returns
|
| 213 |
+
-------
|
| 214 |
+
tuple[str, ...]
|
| 215 |
+
A tuple of resolved parameter names.
|
| 216 |
+
"""
|
| 217 |
+
argss = tuple(x for x in argss if x)
|
| 218 |
+
|
| 219 |
+
if len(argss) == 0:
|
| 220 |
+
return ()
|
| 221 |
+
elif len(argss) == 1:
|
| 222 |
+
return tuple("*" if x == "*" else resolve_parameter_name_helper(x) for x in argss[0])
|
| 223 |
+
|
| 224 |
+
out = []
|
| 225 |
+
for a1 in argss[0]:
|
| 226 |
+
a1 = resolve_parameter_name_helper(a1)
|
| 227 |
+
for a2 in argss[1]:
|
| 228 |
+
if a2.startswith("-") or not a1:
|
| 229 |
+
out.append(a2)
|
| 230 |
+
else:
|
| 231 |
+
out.append(a1 + "." + a2)
|
| 232 |
+
|
| 233 |
+
return resolve_parameter_name(tuple(out), *argss[2:])
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def walk_leaves(
|
| 237 |
+
d,
|
| 238 |
+
parent_keys: tuple[str, ...] | None = None,
|
| 239 |
+
) -> Iterator[tuple[tuple[str, ...], Any]]:
|
| 240 |
+
if parent_keys is None:
|
| 241 |
+
parent_keys = ()
|
| 242 |
+
|
| 243 |
+
if isinstance(d, dict):
|
| 244 |
+
for key, value in d.items():
|
| 245 |
+
current_keys = parent_keys + (key,)
|
| 246 |
+
if isinstance(value, dict):
|
| 247 |
+
yield from walk_leaves(value, current_keys)
|
| 248 |
+
else:
|
| 249 |
+
yield current_keys, value
|
| 250 |
+
else:
|
| 251 |
+
yield (), d
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def to_cli_option_name(*keys: str) -> str:
|
| 255 |
+
return "--" + ".".join(keys)
|
.venv/lib/python3.10/site-packages/cyclopts/bind.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import itertools
|
| 3 |
+
import os
|
| 4 |
+
import shlex
|
| 5 |
+
import sys
|
| 6 |
+
from collections.abc import Callable, Iterable, Sequence
|
| 7 |
+
from contextlib import suppress
|
| 8 |
+
from functools import partial
|
| 9 |
+
from typing import TYPE_CHECKING, Any, NamedTuple, get_origin
|
| 10 |
+
|
| 11 |
+
from cyclopts._convert import _bool
|
| 12 |
+
from cyclopts.annotations import resolve_optional
|
| 13 |
+
from cyclopts.argument import Argument, ArgumentCollection
|
| 14 |
+
from cyclopts.exceptions import (
|
| 15 |
+
ArgumentOrderError,
|
| 16 |
+
CoercionError,
|
| 17 |
+
CombinedShortOptionError,
|
| 18 |
+
ConsumeMultipleError,
|
| 19 |
+
CycloptsError,
|
| 20 |
+
MissingArgumentError,
|
| 21 |
+
RequiresEqualsError,
|
| 22 |
+
UnknownOptionError,
|
| 23 |
+
ValidationError,
|
| 24 |
+
)
|
| 25 |
+
from cyclopts.field_info import POSITIONAL_ONLY, POSITIONAL_OR_KEYWORD
|
| 26 |
+
from cyclopts.token import Token
|
| 27 |
+
from cyclopts.utils import UNSET, is_option_like
|
| 28 |
+
|
| 29 |
+
if sys.version_info < (3, 11): # pragma: no cover
|
| 30 |
+
pass
|
| 31 |
+
else: # pragma: no cover
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if TYPE_CHECKING:
|
| 36 |
+
from cyclopts.group import Group
|
| 37 |
+
|
| 38 |
+
CliToken = partial(Token, source="cli")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _KeywordMatch(NamedTuple):
|
| 42 |
+
"""Represents a matched CLI token with its corresponding argument."""
|
| 43 |
+
|
| 44 |
+
matched_token: str
|
| 45 |
+
"""The actual CLI token that was matched (e.g., '-o', '--option')."""
|
| 46 |
+
|
| 47 |
+
argument: Argument
|
| 48 |
+
"""The matched Argument object."""
|
| 49 |
+
|
| 50 |
+
keys: tuple[str, ...]
|
| 51 |
+
"""Leftover keys for nested arguments."""
|
| 52 |
+
|
| 53 |
+
implicit_value: Any
|
| 54 |
+
"""Implicit value if this is a flag, otherwise UNSET."""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def normalize_tokens(tokens: None | str | Iterable[str]) -> list[str]:
|
| 58 |
+
if tokens is None:
|
| 59 |
+
tokens = sys.argv[1:] # Remove the executable
|
| 60 |
+
elif isinstance(tokens, str):
|
| 61 |
+
tokens = shlex.split(tokens)
|
| 62 |
+
else:
|
| 63 |
+
tokens = list(tokens)
|
| 64 |
+
return tokens
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _common_root_keys(argument_collection) -> tuple[str, ...]:
|
| 68 |
+
if not argument_collection:
|
| 69 |
+
return ()
|
| 70 |
+
common = argument_collection[0].keys
|
| 71 |
+
for argument in argument_collection[1:]:
|
| 72 |
+
if not argument.keys:
|
| 73 |
+
return ()
|
| 74 |
+
for i, (common_key, argument_key) in enumerate(zip(common, argument.keys, strict=False)):
|
| 75 |
+
if common_key != argument_key:
|
| 76 |
+
if i == 0:
|
| 77 |
+
return ()
|
| 78 |
+
|
| 79 |
+
common = argument.keys[:i]
|
| 80 |
+
break
|
| 81 |
+
common = common[: len(argument.keys)]
|
| 82 |
+
return common
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _parse_kw_and_flags(
|
| 86 |
+
argument_collection: ArgumentCollection,
|
| 87 |
+
tokens: Sequence[str],
|
| 88 |
+
*,
|
| 89 |
+
end_of_options_delimiter: str = "--",
|
| 90 |
+
stop_at_first_unknown: bool = False,
|
| 91 |
+
) -> tuple[list[str], int | None]:
|
| 92 |
+
"""Extract keyword arguments and flags from the token stream.
|
| 93 |
+
|
| 94 |
+
Returns
|
| 95 |
+
-------
|
| 96 |
+
unused_tokens: list[str]
|
| 97 |
+
Tokens not consumed by any keyword or flag.
|
| 98 |
+
contiguous_positional_count: int | None
|
| 99 |
+
Number of leading contiguous non-option tokens before the first gap
|
| 100 |
+
caused by keyword extraction. ``None`` if all non-option tokens are
|
| 101 |
+
contiguous (i.e. no keywords were interleaved among positional tokens).
|
| 102 |
+
|
| 103 |
+
For example, given ``a b c --bar 8 --baz 10 d``, the unused tokens are
|
| 104 |
+
``['a', 'b', 'c', 'd']`` with original indices ``[0, 1, 2, 6]``.
|
| 105 |
+
The gap between indices 2 and 6 yields ``contiguous_positional_count=3``.
|
| 106 |
+
This is used by ``_parse_pos`` to prevent positional-only list parameters
|
| 107 |
+
from consuming tokens that appeared after keyword arguments.
|
| 108 |
+
"""
|
| 109 |
+
unused_tokens, positional_only_tokens = [], []
|
| 110 |
+
unused_token_original_indices: list[int] = []
|
| 111 |
+
skip_next_iterations = 0
|
| 112 |
+
if end_of_options_delimiter:
|
| 113 |
+
try:
|
| 114 |
+
delimiter_index = tokens.index(end_of_options_delimiter)
|
| 115 |
+
except ValueError:
|
| 116 |
+
pass # end_of_options_delimiter not in token stream
|
| 117 |
+
else:
|
| 118 |
+
positional_only_tokens = tokens[delimiter_index:]
|
| 119 |
+
tokens = tokens[:delimiter_index]
|
| 120 |
+
for i, token in enumerate(tokens):
|
| 121 |
+
# If the previous argument was a keyword, then this is its value
|
| 122 |
+
if skip_next_iterations > 0:
|
| 123 |
+
skip_next_iterations -= 1
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
if not is_option_like(token, allow_numbers=True):
|
| 127 |
+
if stop_at_first_unknown:
|
| 128 |
+
# Stop parsing and return all remaining tokens as unused
|
| 129 |
+
unused_tokens.extend(tokens[i:])
|
| 130 |
+
unused_token_original_indices.extend(range(i, len(tokens)))
|
| 131 |
+
break
|
| 132 |
+
unused_tokens.append(token)
|
| 133 |
+
unused_token_original_indices.append(i)
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
cli_values: list[str] = []
|
| 137 |
+
consume_count = 0
|
| 138 |
+
|
| 139 |
+
# startswith("-") is redundant, but it's cheap safety.
|
| 140 |
+
allow_combined_flags = token.startswith("-") and not token.startswith("--")
|
| 141 |
+
|
| 142 |
+
# Try splitting on "=" for long options or short options that match exactly
|
| 143 |
+
if "=" in token:
|
| 144 |
+
cli_option, cli_value = token.split("=", 1)
|
| 145 |
+
# Try to match the part before "="
|
| 146 |
+
try:
|
| 147 |
+
argument_collection.match(cli_option)
|
| 148 |
+
# Matched! Use the split
|
| 149 |
+
cli_values.append(cli_value)
|
| 150 |
+
consume_count -= 1
|
| 151 |
+
allow_combined_flags = False
|
| 152 |
+
except ValueError:
|
| 153 |
+
# No match - might be GNU-style like "-pfile=value"
|
| 154 |
+
# Don't split, treat whole token as the option
|
| 155 |
+
cli_option = token
|
| 156 |
+
else:
|
| 157 |
+
cli_option = token
|
| 158 |
+
|
| 159 |
+
matches: list[_KeywordMatch] = []
|
| 160 |
+
attached_value: str | None = None # Track value attached to a GNU-style combined option
|
| 161 |
+
try:
|
| 162 |
+
matches.append(_KeywordMatch(cli_option, *argument_collection.match(cli_option)))
|
| 163 |
+
except ValueError:
|
| 164 |
+
# Length has to be greater than 2 (hyphen + character) to be exploded.
|
| 165 |
+
# Also exclude numeric values (e.g., -10, -3.14) from combined flag parsing.
|
| 166 |
+
if allow_combined_flags and len(token) > 2 and is_option_like(token, allow_numbers=False):
|
| 167 |
+
# GNU-style combined short options: process left-to-right
|
| 168 |
+
# Once we hit an option that takes a value, the rest is the value
|
| 169 |
+
chars = cli_option.lstrip("-")
|
| 170 |
+
position = 0
|
| 171 |
+
|
| 172 |
+
while position < len(chars):
|
| 173 |
+
char = chars[position]
|
| 174 |
+
test_flag = f"-{char}"
|
| 175 |
+
|
| 176 |
+
try:
|
| 177 |
+
arg, keys, implicit = argument_collection.match(test_flag)
|
| 178 |
+
|
| 179 |
+
if implicit is not UNSET or arg.parameter.count:
|
| 180 |
+
# This is a flag (boolean or counting) - consume just this character
|
| 181 |
+
matches.append(_KeywordMatch(test_flag, arg, keys, implicit))
|
| 182 |
+
position += 1
|
| 183 |
+
else:
|
| 184 |
+
# This option takes a value - rest of the string is the value
|
| 185 |
+
remainder = chars[position + 1 :]
|
| 186 |
+
matches.append(_KeywordMatch(test_flag, arg, keys, implicit))
|
| 187 |
+
if remainder:
|
| 188 |
+
# Value is attached: -uroot or -fvuroot
|
| 189 |
+
# Store it separately, will be added to cli_values when processing this match
|
| 190 |
+
attached_value = remainder
|
| 191 |
+
consume_count -= 1
|
| 192 |
+
# Stop processing further characters
|
| 193 |
+
break
|
| 194 |
+
|
| 195 |
+
except ValueError:
|
| 196 |
+
# Unknown flag
|
| 197 |
+
if stop_at_first_unknown:
|
| 198 |
+
unused_tokens.extend(tokens[i:])
|
| 199 |
+
return unused_tokens, None
|
| 200 |
+
unused_tokens.append(test_flag)
|
| 201 |
+
unused_token_original_indices.append(i)
|
| 202 |
+
position += 1
|
| 203 |
+
|
| 204 |
+
if not matches:
|
| 205 |
+
# No valid matches found at all
|
| 206 |
+
continue
|
| 207 |
+
else:
|
| 208 |
+
if stop_at_first_unknown:
|
| 209 |
+
# Unknown option, stop parsing and return all remaining tokens
|
| 210 |
+
unused_tokens.extend(tokens[i:])
|
| 211 |
+
return unused_tokens, None
|
| 212 |
+
unused_tokens.append(token)
|
| 213 |
+
unused_token_original_indices.append(i)
|
| 214 |
+
continue
|
| 215 |
+
for match_index, match in enumerate(matches):
|
| 216 |
+
# For GNU-style combined options, add the attached value only when processing
|
| 217 |
+
# the last match (the value-taking option), not for preceding flags
|
| 218 |
+
if attached_value is not None and match_index == len(matches) - 1:
|
| 219 |
+
cli_values.append(attached_value)
|
| 220 |
+
|
| 221 |
+
if match.argument.parameter.count:
|
| 222 |
+
match.argument.append(CliToken(keyword=match.matched_token, implicit_value=1))
|
| 223 |
+
elif match.implicit_value is not UNSET:
|
| 224 |
+
# A flag was parsed
|
| 225 |
+
if cli_values:
|
| 226 |
+
try:
|
| 227 |
+
coerced_value = _bool(cli_values[-1])
|
| 228 |
+
except CoercionError as e:
|
| 229 |
+
if e.token is None:
|
| 230 |
+
e.token = CliToken(keyword=match.matched_token)
|
| 231 |
+
if e.argument is None:
|
| 232 |
+
e.argument = match.argument
|
| 233 |
+
raise
|
| 234 |
+
if coerced_value: # --positive-flag=true or --negative-flag=true or --empty-flag=true
|
| 235 |
+
match.argument.append(
|
| 236 |
+
CliToken(keyword=match.matched_token, implicit_value=match.implicit_value)
|
| 237 |
+
)
|
| 238 |
+
else: # --positive-flag=false or --negative-flag=false or --empty-flag=false
|
| 239 |
+
if isinstance(match.implicit_value, bool):
|
| 240 |
+
match.argument.append(
|
| 241 |
+
CliToken(keyword=match.matched_token, implicit_value=not match.implicit_value)
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
# A negative for a non-bool field doesn't really make sense;
|
| 245 |
+
# e.g. --empty-list=False
|
| 246 |
+
# So we'll just silently skip it, as it may make bash scripting easier.
|
| 247 |
+
pass
|
| 248 |
+
else:
|
| 249 |
+
match.argument.append(CliToken(keyword=match.matched_token, implicit_value=match.implicit_value))
|
| 250 |
+
else:
|
| 251 |
+
# This is a value-taking option (not a flag or counting parameter)
|
| 252 |
+
# Error only if we're trying to combine multiple value-taking options without values
|
| 253 |
+
# (e.g., -fu where both -f and -u take values would be invalid)
|
| 254 |
+
# But -fu where -f is a flag and -u takes a value is valid (GNU-style)
|
| 255 |
+
if len(matches) > 1:
|
| 256 |
+
# Count how many value-taking options we have
|
| 257 |
+
value_taking_count = sum(
|
| 258 |
+
1 for m in matches if m.implicit_value is UNSET and not m.argument.parameter.count
|
| 259 |
+
)
|
| 260 |
+
if value_taking_count > 1:
|
| 261 |
+
raise CombinedShortOptionError(
|
| 262 |
+
msg=f"Cannot combine multiple value-taking options in token {cli_option}"
|
| 263 |
+
)
|
| 264 |
+
tokens_per_element, consume_all = match.argument.token_count(match.keys)
|
| 265 |
+
|
| 266 |
+
if match.argument.parameter.requires_equals and match.matched_token.startswith("--") and not cli_values:
|
| 267 |
+
raise RequiresEqualsError(
|
| 268 |
+
argument=match.argument,
|
| 269 |
+
keyword=match.matched_token,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# Consume the appropriate number of tokens
|
| 273 |
+
# cm_bounds is either None or (min, max) — guaranteed by _consume_multiple_converter
|
| 274 |
+
cm_bounds = match.argument.parameter.consume_multiple
|
| 275 |
+
assert cm_bounds is None or isinstance(cm_bounds, tuple)
|
| 276 |
+
cm_min, cm_max = cm_bounds if cm_bounds is not None else (0, None)
|
| 277 |
+
with suppress(IndexError):
|
| 278 |
+
if consume_all and cm_bounds is not None:
|
| 279 |
+
for j in itertools.count():
|
| 280 |
+
token = tokens[i + 1 + j]
|
| 281 |
+
if not match.argument.parameter.allow_leading_hyphen and is_option_like(token):
|
| 282 |
+
break
|
| 283 |
+
cli_values.append(token)
|
| 284 |
+
skip_next_iterations += 1
|
| 285 |
+
else:
|
| 286 |
+
consume_count += tokens_per_element
|
| 287 |
+
for j in range(consume_count):
|
| 288 |
+
if len(cli_values) == 1 and (
|
| 289 |
+
match.argument._should_attempt_json_dict(cli_values)
|
| 290 |
+
or match.argument._should_attempt_json_list(cli_values, match.keys)
|
| 291 |
+
):
|
| 292 |
+
tokens_per_element = 1
|
| 293 |
+
# Assume that the contents are json and that we shouldn't
|
| 294 |
+
# consume any additional tokens.
|
| 295 |
+
break
|
| 296 |
+
|
| 297 |
+
token = tokens[i + 1 + j]
|
| 298 |
+
if not match.argument.parameter.allow_leading_hyphen and is_option_like(token):
|
| 299 |
+
raise MissingArgumentError(
|
| 300 |
+
argument=match.argument,
|
| 301 |
+
tokens_so_far=cli_values,
|
| 302 |
+
keyword=match.matched_token,
|
| 303 |
+
)
|
| 304 |
+
cli_values.append(token)
|
| 305 |
+
skip_next_iterations += 1
|
| 306 |
+
|
| 307 |
+
if not cli_values:
|
| 308 |
+
# No values were consumed after the keyword
|
| 309 |
+
if consume_all and cm_bounds is not None:
|
| 310 |
+
if cm_min > 0:
|
| 311 |
+
# Minimum count not met — treat as missing argument
|
| 312 |
+
raise ConsumeMultipleError(
|
| 313 |
+
argument=match.argument,
|
| 314 |
+
tokens_so_far=cli_values,
|
| 315 |
+
keyword=match.matched_token,
|
| 316 |
+
min_required=cm_min,
|
| 317 |
+
max_allowed=cm_max,
|
| 318 |
+
actual_count=0,
|
| 319 |
+
)
|
| 320 |
+
# Allow empty iterables (e.g., --urls with no values behaves like --empty-urls)
|
| 321 |
+
hint = resolve_optional(match.argument.hint)
|
| 322 |
+
empty_container = (get_origin(hint) or hint)()
|
| 323 |
+
match.argument.append(
|
| 324 |
+
CliToken(keyword=match.matched_token, implicit_value=empty_container, keys=match.keys)
|
| 325 |
+
)
|
| 326 |
+
else:
|
| 327 |
+
# Non-iterables or consume_multiple=False require at least one value
|
| 328 |
+
raise MissingArgumentError(
|
| 329 |
+
argument=match.argument, tokens_so_far=cli_values, keyword=match.matched_token
|
| 330 |
+
)
|
| 331 |
+
elif len(cli_values) % tokens_per_element:
|
| 332 |
+
# For multi-token elements (e.g., tuples), ensure we have complete sets
|
| 333 |
+
raise MissingArgumentError(
|
| 334 |
+
argument=match.argument, tokens_so_far=cli_values, keyword=match.matched_token
|
| 335 |
+
)
|
| 336 |
+
else:
|
| 337 |
+
# Check min/max count for consume_multiple
|
| 338 |
+
if cm_bounds is not None:
|
| 339 |
+
n_elements = len(cli_values) // max(1, tokens_per_element)
|
| 340 |
+
if n_elements < cm_min:
|
| 341 |
+
raise ConsumeMultipleError(
|
| 342 |
+
argument=match.argument,
|
| 343 |
+
tokens_so_far=cli_values,
|
| 344 |
+
keyword=match.matched_token,
|
| 345 |
+
min_required=cm_min,
|
| 346 |
+
max_allowed=cm_max,
|
| 347 |
+
actual_count=n_elements,
|
| 348 |
+
)
|
| 349 |
+
if cm_max is not None and n_elements > cm_max:
|
| 350 |
+
raise ConsumeMultipleError(
|
| 351 |
+
argument=match.argument,
|
| 352 |
+
tokens_so_far=cli_values,
|
| 353 |
+
keyword=match.matched_token,
|
| 354 |
+
min_required=cm_min,
|
| 355 |
+
max_allowed=cm_max,
|
| 356 |
+
actual_count=n_elements,
|
| 357 |
+
)
|
| 358 |
+
# Normal case: append the consumed values
|
| 359 |
+
for index, cli_value in enumerate(cli_values):
|
| 360 |
+
match.argument.append(
|
| 361 |
+
CliToken(keyword=match.matched_token, value=cli_value, index=index, keys=match.keys)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# Compute the number of contiguous positional (non-option-like) unused tokens
|
| 365 |
+
# before the first gap caused by keyword extraction. This prevents positional-only
|
| 366 |
+
# list parameters from consuming tokens that appeared after keyword arguments.
|
| 367 |
+
# Only set when a gap is detected; None means no gap (all tokens are contiguous).
|
| 368 |
+
contiguous_positional_count: int | None = None
|
| 369 |
+
for j in range(1, len(unused_token_original_indices)):
|
| 370 |
+
if unused_token_original_indices[j] != unused_token_original_indices[j - 1] + 1:
|
| 371 |
+
contiguous_positional_count = j
|
| 372 |
+
break
|
| 373 |
+
|
| 374 |
+
unused_tokens.extend(positional_only_tokens)
|
| 375 |
+
return unused_tokens, contiguous_positional_count
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _future_positional_only_token_count(argument_collection: ArgumentCollection, starting_index: int) -> int:
|
| 379 |
+
n_tokens_to_leave = 0
|
| 380 |
+
for i in itertools.count():
|
| 381 |
+
try:
|
| 382 |
+
argument, _, _ = argument_collection.match(starting_index + i)
|
| 383 |
+
except ValueError:
|
| 384 |
+
break
|
| 385 |
+
if argument.field_info.kind is not POSITIONAL_ONLY:
|
| 386 |
+
break
|
| 387 |
+
future_tokens_per_element, future_consume_all = argument.token_count()
|
| 388 |
+
if future_consume_all:
|
| 389 |
+
raise ValueError("Cannot have 2 all-consuming positional arguments.")
|
| 390 |
+
n_tokens_to_leave += future_tokens_per_element
|
| 391 |
+
return n_tokens_to_leave
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _preprocess_positional_tokens(tokens: Sequence[str], end_of_options_delimiter: str) -> list[tuple[str, bool]]:
|
| 395 |
+
try:
|
| 396 |
+
delimiter_index = tokens.index(end_of_options_delimiter)
|
| 397 |
+
return [(t, False) for t in tokens[:delimiter_index]] + [(t, True) for t in tokens[delimiter_index + 1 :]]
|
| 398 |
+
except ValueError: # delimiter not found
|
| 399 |
+
return [(t, False) for t in tokens]
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _parse_pos(
|
| 403 |
+
argument_collection: ArgumentCollection,
|
| 404 |
+
tokens: list[str],
|
| 405 |
+
*,
|
| 406 |
+
end_of_options_delimiter: str = "--",
|
| 407 |
+
contiguous_positional_count: int | None = None,
|
| 408 |
+
) -> list[str]:
|
| 409 |
+
"""Assign positional tokens to positional parameters.
|
| 410 |
+
|
| 411 |
+
Parameters
|
| 412 |
+
----------
|
| 413 |
+
argument_collection: ArgumentCollection
|
| 414 |
+
Arguments whose keyword/flag tokens have already been consumed.
|
| 415 |
+
tokens: list[str]
|
| 416 |
+
Unused tokens from ``_parse_kw_and_flags``.
|
| 417 |
+
end_of_options_delimiter: str
|
| 418 |
+
Delimiter after which all tokens are forced positional.
|
| 419 |
+
contiguous_positional_count: int | None
|
| 420 |
+
If not ``None``, the number of leading contiguous positional tokens
|
| 421 |
+
that were adjacent in the original CLI input (before keyword extraction
|
| 422 |
+
created a gap). Used to cap how many tokens a ``POSITIONAL_ONLY``
|
| 423 |
+
list/iterable parameter may consume, preventing it from greedily
|
| 424 |
+
swallowing tokens that originally appeared after keyword arguments.
|
| 425 |
+
See ``_parse_kw_and_flags`` for how this value is computed.
|
| 426 |
+
"""
|
| 427 |
+
prior_positional_or_keyword_supplied_as_keyword_arguments = []
|
| 428 |
+
|
| 429 |
+
if not tokens:
|
| 430 |
+
return []
|
| 431 |
+
|
| 432 |
+
tokens_and_force_positional = _preprocess_positional_tokens(tokens, end_of_options_delimiter)
|
| 433 |
+
|
| 434 |
+
for i in itertools.count():
|
| 435 |
+
try:
|
| 436 |
+
argument, _, _ = argument_collection.match(i)
|
| 437 |
+
except ValueError:
|
| 438 |
+
break
|
| 439 |
+
if argument.field_info.kind is POSITIONAL_OR_KEYWORD:
|
| 440 |
+
if argument.tokens and argument.tokens[0].keyword is not None:
|
| 441 |
+
prior_positional_or_keyword_supplied_as_keyword_arguments.append(argument)
|
| 442 |
+
# Continue in case we hit a VAR_POSITIONAL argument.
|
| 443 |
+
continue
|
| 444 |
+
if prior_positional_or_keyword_supplied_as_keyword_arguments:
|
| 445 |
+
token = tokens[0]
|
| 446 |
+
if not argument.parameter.allow_leading_hyphen and is_option_like(token):
|
| 447 |
+
# It's more meaningful to interpret the token as an intended option,
|
| 448 |
+
# rather than an intended positional value for ``argument``.
|
| 449 |
+
raise UnknownOptionError(token=CliToken(value=token), argument_collection=argument_collection)
|
| 450 |
+
else:
|
| 451 |
+
raise ArgumentOrderError(
|
| 452 |
+
argument=argument,
|
| 453 |
+
prior_positional_or_keyword_supplied_as_keyword_arguments=prior_positional_or_keyword_supplied_as_keyword_arguments,
|
| 454 |
+
token=tokens_and_force_positional[0][0],
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
tokens_per_element, consume_all = argument.token_count()
|
| 458 |
+
tokens_per_element = max(1, tokens_per_element)
|
| 459 |
+
|
| 460 |
+
if consume_all and argument.field_info.kind is POSITIONAL_ONLY:
|
| 461 |
+
# POSITIONAL_ONLY parameters can come after a POSITIONAL_ONLY list/iterable.
|
| 462 |
+
# This makes it easier to create programs that do something like:
|
| 463 |
+
# $ python my-program.py input_folder/*.csv output.csv
|
| 464 |
+
|
| 465 |
+
# Need to see how many tokens we need to leave for subsequent POSITIONAL_ONLY parameters.
|
| 466 |
+
n_tokens_to_leave = _future_positional_only_token_count(argument_collection, i + 1)
|
| 467 |
+
|
| 468 |
+
# Cap at the contiguous positional count to prevent consuming tokens
|
| 469 |
+
# that appeared after keyword arguments (issue #763).
|
| 470 |
+
if contiguous_positional_count is not None:
|
| 471 |
+
n_tokens_to_leave = max(
|
| 472 |
+
n_tokens_to_leave, len(tokens_and_force_positional) - contiguous_positional_count
|
| 473 |
+
)
|
| 474 |
+
else:
|
| 475 |
+
n_tokens_to_leave = 0
|
| 476 |
+
|
| 477 |
+
new_tokens = []
|
| 478 |
+
while (len(tokens_and_force_positional) - n_tokens_to_leave) > 0:
|
| 479 |
+
if (len(tokens_and_force_positional) - n_tokens_to_leave) < tokens_per_element:
|
| 480 |
+
raise MissingArgumentError(
|
| 481 |
+
argument=argument,
|
| 482 |
+
tokens_so_far=[x[0] for x in tokens_and_force_positional],
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
for index, (token, force_positional) in enumerate(tokens_and_force_positional[:tokens_per_element]):
|
| 486 |
+
if not force_positional and not argument.parameter.allow_leading_hyphen and is_option_like(token):
|
| 487 |
+
raise UnknownOptionError(token=CliToken(value=token), argument_collection=argument_collection)
|
| 488 |
+
new_tokens.append(CliToken(value=token, index=index))
|
| 489 |
+
tokens_and_force_positional = tokens_and_force_positional[tokens_per_element:]
|
| 490 |
+
if not consume_all:
|
| 491 |
+
break
|
| 492 |
+
argument.tokens[:0] = new_tokens # Prepend the new tokens to the argument.
|
| 493 |
+
if not tokens_and_force_positional:
|
| 494 |
+
break
|
| 495 |
+
|
| 496 |
+
return [x[0] for x in tokens_and_force_positional]
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _parse_env(argument_collection: ArgumentCollection):
|
| 500 |
+
for argument in argument_collection:
|
| 501 |
+
if argument.tokens:
|
| 502 |
+
# Don't check environment variables for parameters that already have values from CLI.
|
| 503 |
+
continue
|
| 504 |
+
assert argument.parameter.env_var is not None
|
| 505 |
+
for env_var_name in argument.parameter.env_var:
|
| 506 |
+
try:
|
| 507 |
+
env_var_value = os.environ[env_var_name]
|
| 508 |
+
except KeyError:
|
| 509 |
+
pass
|
| 510 |
+
else:
|
| 511 |
+
argument.tokens.append(Token(keyword=env_var_name, value=env_var_value, source="env"))
|
| 512 |
+
break
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def _bind(
|
| 516 |
+
argument_collection: ArgumentCollection,
|
| 517 |
+
func: Callable,
|
| 518 |
+
):
|
| 519 |
+
"""Bind the mapping to the function signature."""
|
| 520 |
+
bound = inspect.signature(func).bind_partial()
|
| 521 |
+
for argument in argument_collection._root_arguments:
|
| 522 |
+
if argument.value is not UNSET:
|
| 523 |
+
bound.arguments[argument.field_info.name] = argument.value
|
| 524 |
+
return bound
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def _parse_configs(argument_collection: ArgumentCollection, configs):
|
| 528 |
+
for config in configs:
|
| 529 |
+
# Each ``config`` is a partial that already has apps and commands provided.
|
| 530 |
+
config(argument_collection)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _sort_group(argument_collection) -> list[tuple["Group", ArgumentCollection]]:
|
| 534 |
+
"""Sort groups into "deepest common-root-keys first" order.
|
| 535 |
+
|
| 536 |
+
This is imperfect, but probably works sufficiently well for practical use-cases.
|
| 537 |
+
"""
|
| 538 |
+
out = {}
|
| 539 |
+
# Sort alphabetically by group-name to enfroce some determinism.
|
| 540 |
+
for i, group in enumerate(sorted(argument_collection.groups, key=lambda x: x.name)):
|
| 541 |
+
group_arguments = argument_collection.filter_by(group=group)
|
| 542 |
+
common_root_keys = _common_root_keys(group_arguments)
|
| 543 |
+
# Add i to key so that we don't get collisions.
|
| 544 |
+
out[(common_root_keys, i)] = (group, group_arguments.filter_by(keys_prefix=common_root_keys))
|
| 545 |
+
return [ga for _, ga in sorted(out.items(), reverse=True)]
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def create_bound_arguments(
|
| 549 |
+
func: Callable,
|
| 550 |
+
argument_collection: ArgumentCollection,
|
| 551 |
+
tokens: list[str],
|
| 552 |
+
configs: Iterable[Callable],
|
| 553 |
+
*,
|
| 554 |
+
end_of_options_delimiter: str = "--",
|
| 555 |
+
) -> tuple[inspect.BoundArguments, list[str]]:
|
| 556 |
+
"""Parse and coerce CLI tokens to match a function's signature.
|
| 557 |
+
|
| 558 |
+
Parameters
|
| 559 |
+
----------
|
| 560 |
+
func: Callable
|
| 561 |
+
Function.
|
| 562 |
+
argument_collection: ArgumentCollection
|
| 563 |
+
tokens: list[str]
|
| 564 |
+
CLI tokens to parse and coerce to match ``f``'s signature.
|
| 565 |
+
configs: Iterable[Callable]
|
| 566 |
+
end_of_options_delimiter: str
|
| 567 |
+
Everything after this special token is forced to be supplied as a positional argument.
|
| 568 |
+
|
| 569 |
+
Returns
|
| 570 |
+
-------
|
| 571 |
+
bound: inspect.BoundArguments
|
| 572 |
+
The converted and bound positional and keyword arguments for ``f``.
|
| 573 |
+
|
| 574 |
+
unused_tokens: list[str]
|
| 575 |
+
Remaining tokens that couldn't be matched to ``f``'s signature.
|
| 576 |
+
"""
|
| 577 |
+
unused_tokens = tokens
|
| 578 |
+
|
| 579 |
+
try:
|
| 580 |
+
unused_tokens, contiguous_positional_count = _parse_kw_and_flags(
|
| 581 |
+
argument_collection, unused_tokens, end_of_options_delimiter=end_of_options_delimiter
|
| 582 |
+
)
|
| 583 |
+
unused_tokens = _parse_pos(
|
| 584 |
+
argument_collection,
|
| 585 |
+
unused_tokens,
|
| 586 |
+
end_of_options_delimiter=end_of_options_delimiter,
|
| 587 |
+
contiguous_positional_count=contiguous_positional_count,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
_parse_env(argument_collection)
|
| 591 |
+
_parse_configs(argument_collection, configs)
|
| 592 |
+
|
| 593 |
+
argument_collection._convert()
|
| 594 |
+
groups_with_arguments = _sort_group(argument_collection)
|
| 595 |
+
try:
|
| 596 |
+
for group, group_arguments in groups_with_arguments:
|
| 597 |
+
for validator in group.validator: # pyright: ignore
|
| 598 |
+
validator(group_arguments) # pyright: ignore[reportOptionalCall]
|
| 599 |
+
except (AssertionError, ValueError, TypeError) as e:
|
| 600 |
+
raise ValidationError(exception_message=e.args[0] if e.args else "", group=group) from e # pyright: ignore
|
| 601 |
+
|
| 602 |
+
for argument in argument_collection:
|
| 603 |
+
# if a dict-like argument is missing, raise a MissingArgumentError on the first
|
| 604 |
+
# required child (as opposed generically to the root dict-like object).
|
| 605 |
+
if argument.parse and argument.field_info.required and not argument.keys and not argument.has_tokens:
|
| 606 |
+
raise MissingArgumentError(argument=argument)
|
| 607 |
+
|
| 608 |
+
bound = _bind(argument_collection, func)
|
| 609 |
+
except CycloptsError as e:
|
| 610 |
+
e.root_input_tokens = tokens
|
| 611 |
+
e.unused_tokens = unused_tokens
|
| 612 |
+
raise
|
| 613 |
+
|
| 614 |
+
return bound, unused_tokens
|
.venv/lib/python3.10/site-packages/cyclopts/cli/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cyclopts CLI implementation."""
|
| 2 |
+
|
| 3 |
+
import cyclopts
|
| 4 |
+
|
| 5 |
+
# Create the main CLI app
|
| 6 |
+
app = cyclopts.App(name="cyclopts")
|
| 7 |
+
app.register_install_completion_command(
|
| 8 |
+
help="""\
|
| 9 |
+
Register shell-completion for the cyclopts CLI itself.
|
| 10 |
+
"""
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Explicitly import command modules
|
| 15 |
+
from cyclopts.cli import (
|
| 16 |
+
_complete, # noqa: F401
|
| 17 |
+
docs, # noqa: F401
|
| 18 |
+
run, # noqa: F401
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
__all__ = ["app"]
|
.venv/lib/python3.10/site-packages/cyclopts/cli/_complete.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hidden completion helper command for dynamic shell completion."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import TYPE_CHECKING, Annotated
|
| 5 |
+
|
| 6 |
+
from cyclopts.cli import app
|
| 7 |
+
from cyclopts.loader import load_app_from_script
|
| 8 |
+
from cyclopts.parameter import Parameter
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from cyclopts import App
|
| 12 |
+
|
| 13 |
+
MAX_DESCRIPTION_LENGTH = 60
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _extract_short_description(help_text: str | None) -> str:
|
| 17 |
+
"""Extract first line of help text as a short description.
|
| 18 |
+
|
| 19 |
+
Parameters
|
| 20 |
+
----------
|
| 21 |
+
help_text : str | None
|
| 22 |
+
Full help text to extract from.
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
str
|
| 27 |
+
First line of help text, or empty string if parsing fails.
|
| 28 |
+
"""
|
| 29 |
+
from cyclopts.help.help import docstring_parse
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
parsed = docstring_parse(help_text, "plaintext")
|
| 33 |
+
return parsed.short_description or ""
|
| 34 |
+
except Exception:
|
| 35 |
+
return str(help_text or "").split("\n")[0]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _print_subcommand_completions(app_obj: "App") -> None:
|
| 39 |
+
"""Print completions for subcommands of the given app.
|
| 40 |
+
|
| 41 |
+
Parameters
|
| 42 |
+
----------
|
| 43 |
+
app_obj : App
|
| 44 |
+
Application object to extract subcommands from.
|
| 45 |
+
"""
|
| 46 |
+
from cyclopts.group_extractors import groups_from_app
|
| 47 |
+
|
| 48 |
+
for _, registered_commands in groups_from_app(app_obj):
|
| 49 |
+
for registered_command in registered_commands:
|
| 50 |
+
if registered_command.app.show:
|
| 51 |
+
for name in registered_command.names:
|
| 52 |
+
if not name.startswith("-"):
|
| 53 |
+
short_desc = _extract_short_description(registered_command.app.help)
|
| 54 |
+
|
| 55 |
+
if short_desc:
|
| 56 |
+
print(f"{name}:{short_desc}")
|
| 57 |
+
else:
|
| 58 |
+
print(name)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _print_option_completions(app_obj: "App") -> None:
|
| 62 |
+
"""Print completions for options of the given app's default command.
|
| 63 |
+
|
| 64 |
+
Parameters
|
| 65 |
+
----------
|
| 66 |
+
app_obj : App
|
| 67 |
+
Application object to extract options from.
|
| 68 |
+
"""
|
| 69 |
+
if not app_obj.default_command:
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
arguments = app_obj.assemble_argument_collection(parse_docstring=True)
|
| 74 |
+
for argument in arguments:
|
| 75 |
+
if not argument.is_positional_only() and argument.show:
|
| 76 |
+
for name in argument.names:
|
| 77 |
+
if name.startswith("-"):
|
| 78 |
+
desc = argument.parameter.help or ""
|
| 79 |
+
desc = desc.split("\n")[0][:MAX_DESCRIPTION_LENGTH]
|
| 80 |
+
if desc:
|
| 81 |
+
print(f"{name}:{desc}")
|
| 82 |
+
else:
|
| 83 |
+
print(name)
|
| 84 |
+
except Exception:
|
| 85 |
+
pass
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@app.command(name="_complete", show=False)
|
| 89 |
+
def complete(
|
| 90 |
+
subcommand: Annotated[str, Parameter(allow_leading_hyphen=True)],
|
| 91 |
+
script: Annotated[Path, Parameter(allow_leading_hyphen=True)],
|
| 92 |
+
*words: Annotated[str, Parameter(allow_leading_hyphen=True)],
|
| 93 |
+
) -> None:
|
| 94 |
+
"""Internal completion helper (hidden from users).
|
| 95 |
+
|
| 96 |
+
This command is called by the shell completion system to dynamically
|
| 97 |
+
generate completions for the 'run' command by loading the target script
|
| 98 |
+
and extracting its available commands and options.
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
subcommand : str
|
| 103 |
+
The cyclopts subcommand being completed (e.g., "run").
|
| 104 |
+
script : Path
|
| 105 |
+
Python script path to load for completion extraction.
|
| 106 |
+
words : str
|
| 107 |
+
Current command line words for context-aware completion.
|
| 108 |
+
"""
|
| 109 |
+
if subcommand != "run":
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
app_obj, _ = load_app_from_script(script)
|
| 114 |
+
except (ImportError, SyntaxError, AttributeError, FileNotFoundError):
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
words_list = list(words) if words else []
|
| 118 |
+
|
| 119 |
+
# Complete from root app if no words or only empty string (initial completion)
|
| 120 |
+
if not words_list or (len(words_list) == 1 and not words_list[0]):
|
| 121 |
+
_print_subcommand_completions(app_obj)
|
| 122 |
+
_print_option_completions(app_obj)
|
| 123 |
+
else:
|
| 124 |
+
try:
|
| 125 |
+
_, execution_path, _ = app_obj.parse_commands(words_list)
|
| 126 |
+
current_app = execution_path[-1]
|
| 127 |
+
_print_subcommand_completions(current_app)
|
| 128 |
+
_print_option_completions(current_app)
|
| 129 |
+
except Exception:
|
| 130 |
+
pass
|
.venv/lib/python3.10/site-packages/cyclopts/cli/docs.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate documentation for Cyclopts applications."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Annotated
|
| 5 |
+
|
| 6 |
+
from cyclopts.cli import app
|
| 7 |
+
from cyclopts.docs.types import (
|
| 8 |
+
FORMAT_ALIASES,
|
| 9 |
+
DocFormat,
|
| 10 |
+
normalize_format,
|
| 11 |
+
)
|
| 12 |
+
from cyclopts.group import Group
|
| 13 |
+
from cyclopts.loader import load_app_from_script
|
| 14 |
+
from cyclopts.parameter import Parameter
|
| 15 |
+
from cyclopts.utils import UNSET
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _format_group_validator(argument_collection):
|
| 19 |
+
format_arg = argument_collection.get("--format")
|
| 20 |
+
output_arg = argument_collection.get("--output")
|
| 21 |
+
|
| 22 |
+
if format_arg.value is UNSET:
|
| 23 |
+
if output_arg.value is UNSET:
|
| 24 |
+
raise ValueError('"--format" must be specified when output path is not provided.')
|
| 25 |
+
|
| 26 |
+
if not output_arg.value or not hasattr(output_arg.value, "suffix"):
|
| 27 |
+
raise ValueError('"--output" must be a valid file path when format is not specified.')
|
| 28 |
+
|
| 29 |
+
suffix = output_arg.value.suffix.lower()
|
| 30 |
+
|
| 31 |
+
if not suffix:
|
| 32 |
+
raise ValueError(
|
| 33 |
+
"Output file must have an extension to infer format (e.g., .md, .html, .rst). "
|
| 34 |
+
'Please specify "--format" explicitly or add an extension to the output file.'
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Strip the leading period from suffix to look up in FORMAT_ALIASES
|
| 38 |
+
suffix_key = suffix.lstrip(".")
|
| 39 |
+
|
| 40 |
+
if not suffix_key:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"Invalid file extension. Output file must have a valid extension after the period. "
|
| 43 |
+
'Please specify "--format" explicitly.'
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
inferred_format = FORMAT_ALIASES.get(suffix_key)
|
| 47 |
+
|
| 48 |
+
if inferred_format is None:
|
| 49 |
+
supported_extensions = [f".{ext}" for ext in FORMAT_ALIASES.keys() if len(ext) <= 4]
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f'Cannot infer format from output extension "{suffix}". '
|
| 52 |
+
f"Supported extensions: {', '.join(sorted(set(supported_extensions)))}. "
|
| 53 |
+
f'Please specify "--format" explicitly.'
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
format_arg.value = inferred_format
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
format_group = Group(validator=_format_group_validator)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.command(default_parameter=Parameter(negative=""))
|
| 63 |
+
def generate_docs(
|
| 64 |
+
script: str,
|
| 65 |
+
output: Annotated[Path | None, Parameter(alias="-o", group=format_group)] = None,
|
| 66 |
+
*,
|
| 67 |
+
format: Annotated[
|
| 68 |
+
DocFormat | None,
|
| 69 |
+
Parameter(alias="-f", group=format_group),
|
| 70 |
+
] = None,
|
| 71 |
+
include_hidden: bool = False,
|
| 72 |
+
heading_level: int = 1,
|
| 73 |
+
usage_name: str | None = None,
|
| 74 |
+
):
|
| 75 |
+
"""Generate documentation for a Cyclopts application.
|
| 76 |
+
|
| 77 |
+
Parameters
|
| 78 |
+
----------
|
| 79 |
+
script : str
|
| 80 |
+
Python script path, optionally with ``':app_object'`` notation to specify
|
| 81 |
+
the App object. If not specified, will search for App objects in the
|
| 82 |
+
script's global namespace.
|
| 83 |
+
output : Optional[Path]
|
| 84 |
+
Output file path. If not specified, prints to stdout.
|
| 85 |
+
format : Optional[DocFormat]
|
| 86 |
+
Output format for documentation. If not specified, inferred from output
|
| 87 |
+
file extension.
|
| 88 |
+
include_hidden : bool
|
| 89 |
+
Include hidden commands in documentation.
|
| 90 |
+
heading_level : int
|
| 91 |
+
Starting heading level for markdown format.
|
| 92 |
+
usage_name : Optional[str]
|
| 93 |
+
Replace the app name shown in ``Usage:`` lines with this string. For
|
| 94 |
+
example, ``"uv run cli"`` for an app whose runtime name is ``"cli"``.
|
| 95 |
+
Headings and anchors are unaffected. Default is None.
|
| 96 |
+
"""
|
| 97 |
+
if format is None: # Handled by _format_group_validator
|
| 98 |
+
raise ValueError("Must specify format.")
|
| 99 |
+
format = normalize_format(format)
|
| 100 |
+
app_obj, _ = load_app_from_script(script)
|
| 101 |
+
docs_content = app_obj.generate_docs(
|
| 102 |
+
output_format=format,
|
| 103 |
+
include_hidden=include_hidden,
|
| 104 |
+
heading_level=heading_level,
|
| 105 |
+
usage_name=usage_name,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
if output:
|
| 109 |
+
output.write_text(docs_content)
|
| 110 |
+
else:
|
| 111 |
+
print(docs_content)
|
.venv/lib/python3.10/site-packages/cyclopts/cli/run.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run Cyclopts applications from Python scripts."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Annotated
|
| 5 |
+
|
| 6 |
+
from cyclopts.cli import app
|
| 7 |
+
from cyclopts.loader import load_app_from_script
|
| 8 |
+
from cyclopts.parameter import Parameter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@app.command(help_flags="")
|
| 12 |
+
def run(
|
| 13 |
+
script: Annotated[
|
| 14 |
+
Path,
|
| 15 |
+
Parameter(allow_leading_hyphen=True),
|
| 16 |
+
],
|
| 17 |
+
/,
|
| 18 |
+
*args: Annotated[str, Parameter(allow_leading_hyphen=True)],
|
| 19 |
+
):
|
| 20 |
+
"""Run a Cyclopts application from a Python script with dynamic shell completion.
|
| 21 |
+
|
| 22 |
+
All arguments after the script path are passed to the loaded application.
|
| 23 |
+
|
| 24 |
+
Shell completion is available. Run once to install (persistent):
|
| 25 |
+
``cyclopts --install-completion``
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
script : str
|
| 30 |
+
Python script path with optional ':app_object' notation.
|
| 31 |
+
args : str
|
| 32 |
+
Arguments to pass to the loaded application.
|
| 33 |
+
|
| 34 |
+
Examples
|
| 35 |
+
--------
|
| 36 |
+
Run a script:
|
| 37 |
+
cyclopts run myapp.py --verbose foo bar
|
| 38 |
+
|
| 39 |
+
Specify app object:
|
| 40 |
+
cyclopts run myapp.py:app --help
|
| 41 |
+
"""
|
| 42 |
+
if str(script) in app.help_flags:
|
| 43 |
+
app.help_print()
|
| 44 |
+
return
|
| 45 |
+
app_obj, _ = load_app_from_script(script)
|
| 46 |
+
return app_obj(args)
|
.venv/lib/python3.10/site-packages/cyclopts/command_spec.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lazy-loadable command specification for deferred imports."""
|
| 2 |
+
|
| 3 |
+
import importlib
|
| 4 |
+
from itertools import chain
|
| 5 |
+
from typing import TYPE_CHECKING, Any
|
| 6 |
+
|
| 7 |
+
from attrs import Factory, define, field
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from cyclopts.core import App
|
| 11 |
+
from cyclopts.group import Group
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@define
|
| 15 |
+
class CommandSpec:
|
| 16 |
+
"""Specification for a command that will be lazily loaded on first access.
|
| 17 |
+
|
| 18 |
+
This allows registering commands via import path strings (e.g., "myapp.commands:create")
|
| 19 |
+
without importing them until they're actually used, improving CLI startup time.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
import_path : str
|
| 24 |
+
Import path in the format "module.path:attribute_name".
|
| 25 |
+
The attribute should be either a function or an App instance.
|
| 26 |
+
name : str | tuple[str, ...] | None
|
| 27 |
+
CLI command name. If None, will be derived from the attribute name via name_transform.
|
| 28 |
+
For function imports: used as the name of the wrapper App.
|
| 29 |
+
For App imports: must match the App's internal name, or ValueError is raised at resolution.
|
| 30 |
+
app_kwargs : dict
|
| 31 |
+
Keyword arguments to pass to App() if wrapping a function.
|
| 32 |
+
Raises ValueError if used with App imports (Apps should be configured in their own definition).
|
| 33 |
+
|
| 34 |
+
Examples
|
| 35 |
+
--------
|
| 36 |
+
>>> from cyclopts import App
|
| 37 |
+
>>> app = App()
|
| 38 |
+
>>> # Lazy load - doesn't import myapp.commands until "create" is executed
|
| 39 |
+
>>> app.command("myapp.commands:create_user", name="create")
|
| 40 |
+
>>> app()
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
import_path: str
|
| 44 |
+
name: str | tuple[str, ...] | None = None
|
| 45 |
+
app_kwargs: dict[str, Any] = Factory(dict)
|
| 46 |
+
help: str | None = None
|
| 47 |
+
sort_key: Any = None
|
| 48 |
+
group: "Group | str | tuple[Group | str, ...] | None" = None
|
| 49 |
+
_show: bool | None = field(default=None, alias="show")
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def show(self) -> bool:
|
| 53 |
+
if self._show is None:
|
| 54 |
+
return True
|
| 55 |
+
return self._show
|
| 56 |
+
|
| 57 |
+
_resolved: "App | None" = field(init=False, default=None, repr=False)
|
| 58 |
+
|
| 59 |
+
def resolve(self, parent_app: "App") -> "App":
|
| 60 |
+
"""Import and resolve the command on first access.
|
| 61 |
+
|
| 62 |
+
Parameters
|
| 63 |
+
----------
|
| 64 |
+
parent_app : App
|
| 65 |
+
Parent app to inherit defaults from (help_flags, version_flags, groups).
|
| 66 |
+
Required to match the behavior of direct command registration.
|
| 67 |
+
|
| 68 |
+
Returns
|
| 69 |
+
-------
|
| 70 |
+
App
|
| 71 |
+
The resolved App instance, either imported directly or wrapping a function.
|
| 72 |
+
|
| 73 |
+
Raises
|
| 74 |
+
------
|
| 75 |
+
ValueError
|
| 76 |
+
If import_path is not in the correct format "module.path:attribute_name".
|
| 77 |
+
ImportError
|
| 78 |
+
If the module cannot be imported.
|
| 79 |
+
AttributeError
|
| 80 |
+
If the attribute doesn't exist in the module.
|
| 81 |
+
"""
|
| 82 |
+
if self._resolved is not None:
|
| 83 |
+
return self._resolved
|
| 84 |
+
|
| 85 |
+
# Parse import path
|
| 86 |
+
module_path, _, attr_name = self.import_path.rpartition(":")
|
| 87 |
+
if not module_path or not attr_name:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
f"Invalid import path: {self.import_path!r}. Expected format: 'module.path:attribute_name'"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Import the module and get the attribute
|
| 93 |
+
try:
|
| 94 |
+
module = importlib.import_module(module_path)
|
| 95 |
+
except ImportError as e:
|
| 96 |
+
raise ImportError(f"Cannot import module {module_path!r} from {self.import_path!r}") from e
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
target = getattr(module, attr_name)
|
| 100 |
+
except AttributeError as e:
|
| 101 |
+
raise AttributeError(
|
| 102 |
+
f"Module {module_path!r} has no attribute {attr_name!r} (from import path {self.import_path!r})"
|
| 103 |
+
) from e
|
| 104 |
+
|
| 105 |
+
# Wrap in App if needed
|
| 106 |
+
from cyclopts.core import App
|
| 107 |
+
|
| 108 |
+
if isinstance(target, App):
|
| 109 |
+
# Validate that no kwargs were provided for App imports
|
| 110 |
+
if self.app_kwargs:
|
| 111 |
+
raise ValueError(
|
| 112 |
+
f"Cannot apply configuration to imported App. "
|
| 113 |
+
f"Import path {self.import_path!r} resolves to an App, "
|
| 114 |
+
f"but kwargs were specified: {self.app_kwargs!r}. "
|
| 115 |
+
f"Configure the App in its definition instead."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# Validate that the App's name matches the expected CLI command name
|
| 119 |
+
# The name used for CLI registration is stored in self.name
|
| 120 |
+
if self.name is not None and target.name[0] != self.name:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"Imported App name mismatch. "
|
| 123 |
+
f"Import path {self.import_path!r} resolves to an App with name={target.name[0]!r}, "
|
| 124 |
+
f"but it was registered with CLI command name={self.name!r}. "
|
| 125 |
+
f"Either use app.command('{self.import_path}', name='{target.name[0]}') "
|
| 126 |
+
f"or change the App's name to match."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Copy parent groups if not set (matches direct App registration behavior)
|
| 130 |
+
from cyclopts.core import _apply_parent_defaults_to_app
|
| 131 |
+
|
| 132 |
+
_apply_parent_defaults_to_app(target, parent_app)
|
| 133 |
+
|
| 134 |
+
self._resolved = target
|
| 135 |
+
else:
|
| 136 |
+
# It's a function - wrap it in an App with parent defaults
|
| 137 |
+
# Match the behavior of direct function registration
|
| 138 |
+
app_kwargs = dict(self.app_kwargs) # Copy to avoid mutating
|
| 139 |
+
|
| 140 |
+
from cyclopts.core import _apply_parent_groups_to_kwargs
|
| 141 |
+
|
| 142 |
+
app_kwargs.setdefault("help_flags", parent_app.help_flags)
|
| 143 |
+
app_kwargs.setdefault("version_flags", parent_app.version_flags)
|
| 144 |
+
if "version" not in app_kwargs and parent_app.version is not None:
|
| 145 |
+
app_kwargs["version"] = parent_app.version
|
| 146 |
+
|
| 147 |
+
_apply_parent_groups_to_kwargs(app_kwargs, parent_app)
|
| 148 |
+
|
| 149 |
+
self._resolved = App(name=self.name, **app_kwargs)
|
| 150 |
+
self._resolved.default(target)
|
| 151 |
+
|
| 152 |
+
# Apply registration-time overrides to the resolved App
|
| 153 |
+
if self.help is not None:
|
| 154 |
+
self._resolved.help = self.help
|
| 155 |
+
if self.sort_key is not None:
|
| 156 |
+
self._resolved.sort_key = self.sort_key
|
| 157 |
+
if self.group is not None:
|
| 158 |
+
self._resolved.group = self.group
|
| 159 |
+
if self._show is not None:
|
| 160 |
+
self._resolved.show = self._show
|
| 161 |
+
if self._resolved._name_transform is None:
|
| 162 |
+
self._resolved.name_transform = parent_app.name_transform
|
| 163 |
+
|
| 164 |
+
# Hide help and version flags from subapp help output
|
| 165 |
+
# This matches the behavior of direct App/function registration in core.py
|
| 166 |
+
for flag in chain(self._resolved.help_flags, self._resolved.version_flags):
|
| 167 |
+
self._resolved[flag].show = False
|
| 168 |
+
|
| 169 |
+
return self._resolved
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def is_resolved(self) -> bool:
|
| 173 |
+
"""Check if this command has been imported and resolved yet."""
|
| 174 |
+
return self._resolved is not None
|
.venv/lib/python3.10/site-packages/cyclopts/completion/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shell completion generation for Cyclopts applications."""
|
| 2 |
+
|
| 3 |
+
from cyclopts.completion.detect import ShellDetectionError, detect_shell
|
| 4 |
+
from cyclopts.completion.install import add_to_rc_file, get_default_completion_path
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"detect_shell",
|
| 8 |
+
"ShellDetectionError",
|
| 9 |
+
"get_default_completion_path",
|
| 10 |
+
"add_to_rc_file",
|
| 11 |
+
]
|
.venv/lib/python3.10/site-packages/cyclopts/completion/_base.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared shell completion infrastructure.
|
| 2 |
+
|
| 3 |
+
Provides data extraction, type analysis, and text processing utilities.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import warnings
|
| 9 |
+
from enum import Enum
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import TYPE_CHECKING, Any, get_args, get_origin
|
| 12 |
+
|
| 13 |
+
from cyclopts.annotations import ITERABLE_TYPES, is_annotated, is_union
|
| 14 |
+
from cyclopts.argument import ArgumentCollection
|
| 15 |
+
from cyclopts.exceptions import CycloptsError
|
| 16 |
+
from cyclopts.group_extractors import RegisteredCommand, groups_from_app
|
| 17 |
+
from cyclopts.utils import frozen, is_class_and_subclass
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from cyclopts import App
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class CompletionAction(Enum):
|
| 24 |
+
"""Shell-agnostic completion action types."""
|
| 25 |
+
|
| 26 |
+
NONE = "none"
|
| 27 |
+
FILES = "files"
|
| 28 |
+
DIRECTORIES = "directories"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@frozen
|
| 32 |
+
class CompletionData:
|
| 33 |
+
"""Completion data for a command path."""
|
| 34 |
+
|
| 35 |
+
arguments: "ArgumentCollection"
|
| 36 |
+
commands: list[RegisteredCommand]
|
| 37 |
+
help_format: str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def extract_completion_data(app: "App") -> dict[tuple[str, ...], CompletionData]:
|
| 41 |
+
"""Recursively extract completion data for app and all subcommands.
|
| 42 |
+
|
| 43 |
+
Parameters
|
| 44 |
+
----------
|
| 45 |
+
app : App
|
| 46 |
+
The Cyclopts application to extract completion data from.
|
| 47 |
+
|
| 48 |
+
Returns
|
| 49 |
+
-------
|
| 50 |
+
dict[tuple[str, ...], CompletionData]
|
| 51 |
+
Mapping from command path tuples to their completion data.
|
| 52 |
+
"""
|
| 53 |
+
completion_data: dict[tuple[str, ...], CompletionData] = {}
|
| 54 |
+
|
| 55 |
+
def _extract(command_path: tuple[str, ...] = ()):
|
| 56 |
+
"""Recursively extract completion data for command and subcommands."""
|
| 57 |
+
try:
|
| 58 |
+
_, execution_path, _ = app.parse_commands(list(command_path))
|
| 59 |
+
command_app = execution_path[-1]
|
| 60 |
+
except (CycloptsError, ValueError, TypeError) as e:
|
| 61 |
+
if os.environ.get("CYCLOPTS_COMPLETION_DEBUG"):
|
| 62 |
+
raise
|
| 63 |
+
warnings.warn(f"Failed to extract completion data for command path {command_path!r}: {e}", stacklevel=2)
|
| 64 |
+
help_format = app.app_stack.resolve("help_format", fallback="markdown")
|
| 65 |
+
completion_data[command_path] = CompletionData(
|
| 66 |
+
arguments=ArgumentCollection(), commands=[], help_format=help_format
|
| 67 |
+
)
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
arguments = ArgumentCollection()
|
| 71 |
+
apps_for_params = app._get_resolution_context(execution_path)
|
| 72 |
+
with app.app_stack(execution_path):
|
| 73 |
+
for subapp in apps_for_params:
|
| 74 |
+
if subapp.default_command:
|
| 75 |
+
app_arguments = subapp.assemble_argument_collection(parse_docstring=True)
|
| 76 |
+
arguments.extend(app_arguments)
|
| 77 |
+
|
| 78 |
+
commands = []
|
| 79 |
+
for group, registered_commands in groups_from_app(command_app, resolve_lazy=True):
|
| 80 |
+
if group.show:
|
| 81 |
+
for registered_command in registered_commands:
|
| 82 |
+
if registered_command.app.show and registered_command not in commands:
|
| 83 |
+
commands.append(registered_command)
|
| 84 |
+
|
| 85 |
+
help_format = command_app.app_stack.resolve("help_format", fallback="markdown")
|
| 86 |
+
|
| 87 |
+
completion_data[command_path] = CompletionData(arguments=arguments, commands=commands, help_format=help_format)
|
| 88 |
+
|
| 89 |
+
for registered_command in commands:
|
| 90 |
+
for cmd_name in registered_command.names:
|
| 91 |
+
if not cmd_name.startswith("-"):
|
| 92 |
+
_extract(command_path + (cmd_name,))
|
| 93 |
+
|
| 94 |
+
_extract()
|
| 95 |
+
return completion_data
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def get_completion_action(type_hint: Any) -> CompletionAction:
|
| 99 |
+
"""Get completion action from type hint.
|
| 100 |
+
|
| 101 |
+
Parameters
|
| 102 |
+
----------
|
| 103 |
+
type_hint : Any
|
| 104 |
+
Type annotation.
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
CompletionAction
|
| 109 |
+
Completion action for type.
|
| 110 |
+
"""
|
| 111 |
+
if is_annotated(type_hint):
|
| 112 |
+
return get_completion_action(get_args(type_hint)[0])
|
| 113 |
+
|
| 114 |
+
if is_union(type_hint):
|
| 115 |
+
for arg in get_args(type_hint):
|
| 116 |
+
if arg is not type(None):
|
| 117 |
+
action = get_completion_action(arg)
|
| 118 |
+
if action != CompletionAction.NONE:
|
| 119 |
+
return action
|
| 120 |
+
return CompletionAction.NONE
|
| 121 |
+
|
| 122 |
+
origin = get_origin(type_hint)
|
| 123 |
+
|
| 124 |
+
# For collection types, unwrap to get element type
|
| 125 |
+
if is_class_and_subclass(origin, tuple(ITERABLE_TYPES)):
|
| 126 |
+
args = get_args(type_hint)
|
| 127 |
+
if args and len(args) >= 1:
|
| 128 |
+
# list[Path], set[Path], tuple[Path, ...] -> check first arg
|
| 129 |
+
return get_completion_action(args[0])
|
| 130 |
+
|
| 131 |
+
target_type = origin or type_hint
|
| 132 |
+
|
| 133 |
+
if target_type is Path or is_class_and_subclass(target_type, Path):
|
| 134 |
+
return CompletionAction.FILES
|
| 135 |
+
|
| 136 |
+
return CompletionAction.NONE
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def clean_choice_text(text: str) -> str:
|
| 140 |
+
"""Clean choice text without shell-specific escaping.
|
| 141 |
+
|
| 142 |
+
Parameters
|
| 143 |
+
----------
|
| 144 |
+
text : str
|
| 145 |
+
Raw choice text.
|
| 146 |
+
|
| 147 |
+
Returns
|
| 148 |
+
-------
|
| 149 |
+
str
|
| 150 |
+
Cleaned text (not shell-escaped).
|
| 151 |
+
"""
|
| 152 |
+
text = re.sub(r"[\x00-\x1f\x7f]", "", text)
|
| 153 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 154 |
+
return text
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def escape_for_shell_pattern(name: str, chars: str = "*?[]") -> str:
|
| 158 |
+
"""Escape glob/pattern characters for shell case patterns.
|
| 159 |
+
|
| 160 |
+
Both bash and zsh case patterns treat glob characters as special even inside
|
| 161 |
+
quotes. This function escapes them with backslashes for literal matching.
|
| 162 |
+
|
| 163 |
+
Parameters
|
| 164 |
+
----------
|
| 165 |
+
name : str
|
| 166 |
+
String to escape.
|
| 167 |
+
chars : str
|
| 168 |
+
Characters to escape. Default covers basic glob chars.
|
| 169 |
+
For zsh, also pass "()|" for extended patterns.
|
| 170 |
+
|
| 171 |
+
Returns
|
| 172 |
+
-------
|
| 173 |
+
str
|
| 174 |
+
Escaped string safe for shell case patterns.
|
| 175 |
+
"""
|
| 176 |
+
# Escape backslashes first to avoid double-escaping
|
| 177 |
+
result = name.replace("\\", "\\\\")
|
| 178 |
+
for char in chars:
|
| 179 |
+
result = result.replace(char, f"\\{char}")
|
| 180 |
+
return result
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def strip_markup(text: str, format: str = "markdown", max_length: int = 80) -> str:
|
| 184 |
+
"""Strip markup and render to plain text for shell completions.
|
| 185 |
+
|
| 186 |
+
Converts formatted text (markdown/RST/rich) to plain text suitable for
|
| 187 |
+
shell completion descriptions. Removes control characters, normalizes
|
| 188 |
+
whitespace, and truncates if needed.
|
| 189 |
+
|
| 190 |
+
Parameters
|
| 191 |
+
----------
|
| 192 |
+
text : str
|
| 193 |
+
Text with markup.
|
| 194 |
+
format : str
|
| 195 |
+
Markup format: "markdown", "rst", "rich", or "plaintext".
|
| 196 |
+
max_length : int
|
| 197 |
+
Maximum length before truncation.
|
| 198 |
+
|
| 199 |
+
Returns
|
| 200 |
+
-------
|
| 201 |
+
str
|
| 202 |
+
Plain text (not shell-escaped).
|
| 203 |
+
"""
|
| 204 |
+
from cyclopts._markup import extract_text
|
| 205 |
+
from cyclopts.help.inline_text import InlineText
|
| 206 |
+
|
| 207 |
+
inline = InlineText.from_format(text, format=format)
|
| 208 |
+
text = extract_text(inline)
|
| 209 |
+
|
| 210 |
+
text = re.sub(r"[\x00-\x1f\x7f]", "", text)
|
| 211 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 212 |
+
|
| 213 |
+
if len(text) > max_length:
|
| 214 |
+
text = text[: max_length - 1] + "…"
|
| 215 |
+
|
| 216 |
+
return text
|
.venv/lib/python3.10/site-packages/cyclopts/completion/bash.py
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bash completion script generator.
|
| 2 |
+
|
| 3 |
+
Generates static bash completion scripts using COMPREPLY and compgen.
|
| 4 |
+
Targets bash 3.2+ with no external dependencies.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
from typing import TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
from cyclopts.annotations import is_iterable_type
|
| 11 |
+
from cyclopts.completion._base import (
|
| 12 |
+
CompletionAction,
|
| 13 |
+
CompletionData,
|
| 14 |
+
clean_choice_text,
|
| 15 |
+
escape_for_shell_pattern,
|
| 16 |
+
extract_completion_data,
|
| 17 |
+
get_completion_action,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from cyclopts import App
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def generate_completion_script(app: "App", prog_name: str) -> str:
|
| 25 |
+
"""Generate bash completion script.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
app : App
|
| 30 |
+
The Cyclopts application to generate completion for.
|
| 31 |
+
prog_name : str
|
| 32 |
+
Program name (alphanumeric with hyphens/underscores).
|
| 33 |
+
|
| 34 |
+
Returns
|
| 35 |
+
-------
|
| 36 |
+
str
|
| 37 |
+
Complete bash completion script.
|
| 38 |
+
|
| 39 |
+
Raises
|
| 40 |
+
------
|
| 41 |
+
ValueError
|
| 42 |
+
If prog_name contains invalid characters.
|
| 43 |
+
"""
|
| 44 |
+
if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name):
|
| 45 |
+
raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.")
|
| 46 |
+
|
| 47 |
+
func_name = prog_name.replace("-", "_")
|
| 48 |
+
completion_data = extract_completion_data(app)
|
| 49 |
+
|
| 50 |
+
lines = [
|
| 51 |
+
f"# Bash completion for {prog_name}",
|
| 52 |
+
"# Generated by Cyclopts",
|
| 53 |
+
"",
|
| 54 |
+
f"_{func_name}() {{",
|
| 55 |
+
" local cur prev",
|
| 56 |
+
"",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
lines.extend(_generate_completion_function_body(completion_data, prog_name, app))
|
| 60 |
+
|
| 61 |
+
lines.extend(["}"])
|
| 62 |
+
lines.append("")
|
| 63 |
+
lines.append(f"complete -F _{func_name} {prog_name}")
|
| 64 |
+
lines.append("")
|
| 65 |
+
|
| 66 |
+
return "\n".join(lines)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _escape_bash_choice(choice: str) -> str:
|
| 70 |
+
r"""Escape single quotes for bash strings."""
|
| 71 |
+
return choice.replace("'", "'\\''")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _escape_bash_description(text: str) -> str:
|
| 75 |
+
r"""Escape description text for bash comments."""
|
| 76 |
+
text = text.replace("\n", " ")
|
| 77 |
+
text = text.replace("\r", " ")
|
| 78 |
+
return text
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _map_completion_action_to_bash(action: CompletionAction) -> str:
|
| 82 |
+
"""Map completion action to bash compgen flags.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
----------
|
| 86 |
+
action : CompletionAction
|
| 87 |
+
Completion action type.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
str
|
| 92 |
+
Compgen flags ("-f", "-d", or "").
|
| 93 |
+
"""
|
| 94 |
+
if action == CompletionAction.FILES:
|
| 95 |
+
return "-f"
|
| 96 |
+
elif action == CompletionAction.DIRECTORIES:
|
| 97 |
+
return "-d"
|
| 98 |
+
return ""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _generate_completion_function_body(
|
| 102 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 103 |
+
prog_name: str,
|
| 104 |
+
app: "App",
|
| 105 |
+
) -> list[str]:
|
| 106 |
+
"""Generate the body of the bash completion function.
|
| 107 |
+
|
| 108 |
+
Parameters
|
| 109 |
+
----------
|
| 110 |
+
completion_data : dict
|
| 111 |
+
All extracted completion data.
|
| 112 |
+
prog_name : str
|
| 113 |
+
Program name.
|
| 114 |
+
app : App
|
| 115 |
+
Application instance.
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
list[str]
|
| 120 |
+
Lines of bash code for the completion function body.
|
| 121 |
+
"""
|
| 122 |
+
lines = []
|
| 123 |
+
lines.append(' cur="${COMP_WORDS[COMP_CWORD]}"')
|
| 124 |
+
lines.append(' prev="${COMP_WORDS[COMP_CWORD-1]}"')
|
| 125 |
+
lines.append("")
|
| 126 |
+
|
| 127 |
+
lines.extend(_generate_command_path_detection(completion_data))
|
| 128 |
+
lines.append("")
|
| 129 |
+
|
| 130 |
+
lines.extend(_generate_completion_logic(completion_data, prog_name, app))
|
| 131 |
+
|
| 132 |
+
return lines
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _generate_command_path_detection(completion_data: dict[tuple[str, ...], CompletionData]) -> list[str]:
|
| 136 |
+
"""Generate bash code to detect the current command path.
|
| 137 |
+
|
| 138 |
+
This function generates two passes through COMP_WORDS:
|
| 139 |
+
1. First pass builds cmd_path by identifying valid command names
|
| 140 |
+
2. Second pass counts positionals (non-option words after the command path)
|
| 141 |
+
|
| 142 |
+
The two-pass approach is necessary because we need to know the full command
|
| 143 |
+
path length before we can correctly identify which words are positionals.
|
| 144 |
+
|
| 145 |
+
Note: all_commands is built globally across all command levels. If a positional
|
| 146 |
+
argument value happens to match a command name from a different level, it could
|
| 147 |
+
be incorrectly classified (though this represents poor CLI design).
|
| 148 |
+
|
| 149 |
+
Parameters
|
| 150 |
+
----------
|
| 151 |
+
completion_data : dict
|
| 152 |
+
All extracted completion data.
|
| 153 |
+
|
| 154 |
+
Returns
|
| 155 |
+
-------
|
| 156 |
+
list[str]
|
| 157 |
+
Lines of bash code for command path detection.
|
| 158 |
+
"""
|
| 159 |
+
options_with_values = set()
|
| 160 |
+
all_commands = set()
|
| 161 |
+
|
| 162 |
+
for data in completion_data.values():
|
| 163 |
+
for argument in data.arguments:
|
| 164 |
+
if not argument.is_flag() and argument.parameter.name:
|
| 165 |
+
for name in argument.parameter.name:
|
| 166 |
+
if name.startswith("-"):
|
| 167 |
+
options_with_values.add(name)
|
| 168 |
+
|
| 169 |
+
for registered_command in data.commands:
|
| 170 |
+
for cmd_name in registered_command.names:
|
| 171 |
+
if not cmd_name.startswith("-"):
|
| 172 |
+
all_commands.add(cmd_name)
|
| 173 |
+
|
| 174 |
+
lines = []
|
| 175 |
+
lines.append(" # Build list of options that take values (to skip their arguments)")
|
| 176 |
+
if options_with_values:
|
| 177 |
+
escaped_opts = [_escape_bash_choice(opt) for opt in sorted(options_with_values)]
|
| 178 |
+
opts_str = " ".join(escaped_opts)
|
| 179 |
+
lines.append(f" local options_with_values='{opts_str}'")
|
| 180 |
+
else:
|
| 181 |
+
lines.append(" local options_with_values=''")
|
| 182 |
+
|
| 183 |
+
lines.append("")
|
| 184 |
+
lines.append(" # Build list of all valid command names (to distinguish from positionals)")
|
| 185 |
+
if all_commands:
|
| 186 |
+
escaped_cmds = [_escape_bash_choice(cmd) for cmd in sorted(all_commands)]
|
| 187 |
+
cmds_str = " ".join(escaped_cmds)
|
| 188 |
+
lines.append(f" local all_commands='{cmds_str}'")
|
| 189 |
+
else:
|
| 190 |
+
lines.append(" local all_commands=''")
|
| 191 |
+
|
| 192 |
+
lines.append("")
|
| 193 |
+
lines.append(" # Detect command path by collecting valid command words only")
|
| 194 |
+
lines.append(" local -a cmd_path=()")
|
| 195 |
+
lines.append(" local i skip_next=0")
|
| 196 |
+
lines.append(" for ((i=1; i<COMP_CWORD; i++)); do")
|
| 197 |
+
lines.append(' local word="${COMP_WORDS[i]}"')
|
| 198 |
+
lines.append(" if [[ $skip_next -eq 1 ]]; then")
|
| 199 |
+
lines.append(" skip_next=0")
|
| 200 |
+
lines.append(" continue")
|
| 201 |
+
lines.append(" fi")
|
| 202 |
+
lines.append(" if [[ $word =~ ^- ]]; then")
|
| 203 |
+
lines.append(" # Check if this option takes a value")
|
| 204 |
+
lines.append(' if [[ " $options_with_values " =~ " $word " ]]; then')
|
| 205 |
+
lines.append(" skip_next=1")
|
| 206 |
+
lines.append(" fi")
|
| 207 |
+
lines.append(" else")
|
| 208 |
+
lines.append(" # Non-option word - only add to cmd_path if it's a valid command")
|
| 209 |
+
lines.append(' if [[ " $all_commands " =~ " $word " ]]; then')
|
| 210 |
+
lines.append(' cmd_path+=("$word")')
|
| 211 |
+
lines.append(" fi")
|
| 212 |
+
lines.append(" fi")
|
| 213 |
+
lines.append(" done")
|
| 214 |
+
lines.append("")
|
| 215 |
+
lines.append(" # Count positionals (non-option words after command path)")
|
| 216 |
+
lines.append(" local positional_count=0")
|
| 217 |
+
lines.append(" local cmd_path_len=${#cmd_path[@]}")
|
| 218 |
+
lines.append(" skip_next=0")
|
| 219 |
+
lines.append(" local cmd_depth=0")
|
| 220 |
+
lines.append(" for ((i=1; i<COMP_CWORD; i++)); do")
|
| 221 |
+
lines.append(' local word="${COMP_WORDS[i]}"')
|
| 222 |
+
lines.append(" if [[ $skip_next -eq 1 ]]; then")
|
| 223 |
+
lines.append(" skip_next=0")
|
| 224 |
+
lines.append(" continue")
|
| 225 |
+
lines.append(" fi")
|
| 226 |
+
lines.append(" if [[ $word =~ ^- ]]; then")
|
| 227 |
+
lines.append(' if [[ " $options_with_values " =~ " $word " ]]; then')
|
| 228 |
+
lines.append(" skip_next=1")
|
| 229 |
+
lines.append(" fi")
|
| 230 |
+
lines.append(" else")
|
| 231 |
+
lines.append(" # Non-option word")
|
| 232 |
+
lines.append(" if [[ $cmd_depth -lt $cmd_path_len ]]; then")
|
| 233 |
+
lines.append(" # Still in command path")
|
| 234 |
+
lines.append(" ((cmd_depth++))")
|
| 235 |
+
lines.append(" else")
|
| 236 |
+
lines.append(" # Past command path, this is a positional")
|
| 237 |
+
lines.append(" ((positional_count++))")
|
| 238 |
+
lines.append(" fi")
|
| 239 |
+
lines.append(" fi")
|
| 240 |
+
lines.append(" done")
|
| 241 |
+
return lines
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _generate_completion_logic(
|
| 245 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 246 |
+
prog_name: str,
|
| 247 |
+
app: "App",
|
| 248 |
+
) -> list[str]:
|
| 249 |
+
"""Generate the main completion logic using case statements.
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
completion_data : dict
|
| 254 |
+
All extracted completion data.
|
| 255 |
+
prog_name : str
|
| 256 |
+
Program name.
|
| 257 |
+
app : App
|
| 258 |
+
Application instance.
|
| 259 |
+
|
| 260 |
+
Returns
|
| 261 |
+
-------
|
| 262 |
+
list[str]
|
| 263 |
+
Lines of bash code for completion logic.
|
| 264 |
+
"""
|
| 265 |
+
lines = []
|
| 266 |
+
|
| 267 |
+
help_flags = tuple(app.help_flags) if app.help_flags else ()
|
| 268 |
+
version_flags = tuple(app.version_flags) if app.version_flags else ()
|
| 269 |
+
|
| 270 |
+
lines.append(" # Determine command level and generate completions")
|
| 271 |
+
lines.append(' case "${#cmd_path[@]}" in')
|
| 272 |
+
|
| 273 |
+
max_depth = max(len(path) for path in completion_data.keys())
|
| 274 |
+
for depth in range(max_depth + 1):
|
| 275 |
+
relevant_paths = [path for path in completion_data.keys() if len(path) == depth]
|
| 276 |
+
if not relevant_paths:
|
| 277 |
+
continue
|
| 278 |
+
|
| 279 |
+
lines.append(f" {depth})")
|
| 280 |
+
|
| 281 |
+
if depth == 0:
|
| 282 |
+
lines.extend(_generate_completions_for_path(completion_data, (), " ", help_flags, version_flags))
|
| 283 |
+
else:
|
| 284 |
+
lines.append(' case "${cmd_path[@]}" in')
|
| 285 |
+
for path in sorted(relevant_paths):
|
| 286 |
+
# Escape glob characters in command names for case pattern matching
|
| 287 |
+
escaped_path = [escape_for_shell_pattern(cmd) for cmd in path]
|
| 288 |
+
path_str = " ".join(escaped_path)
|
| 289 |
+
lines.append(f' "{path_str}")')
|
| 290 |
+
lines.extend(
|
| 291 |
+
_generate_completions_for_path(completion_data, path, " ", help_flags, version_flags)
|
| 292 |
+
)
|
| 293 |
+
lines.append(" ;;")
|
| 294 |
+
lines.append(" *)")
|
| 295 |
+
lines.append(" ;;")
|
| 296 |
+
lines.append(" esac")
|
| 297 |
+
|
| 298 |
+
lines.append(" ;;")
|
| 299 |
+
|
| 300 |
+
lines.append(" *)")
|
| 301 |
+
lines.append(" ;;")
|
| 302 |
+
lines.append(" esac")
|
| 303 |
+
|
| 304 |
+
return lines
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _generate_completions_for_path(
|
| 308 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 309 |
+
command_path: tuple[str, ...],
|
| 310 |
+
indent: str,
|
| 311 |
+
help_flags: tuple[str, ...],
|
| 312 |
+
version_flags: tuple[str, ...],
|
| 313 |
+
) -> list[str]:
|
| 314 |
+
"""Generate completions for a specific command path.
|
| 315 |
+
|
| 316 |
+
Parameters
|
| 317 |
+
----------
|
| 318 |
+
completion_data : dict
|
| 319 |
+
All extracted completion data.
|
| 320 |
+
command_path : tuple[str, ...]
|
| 321 |
+
Current command path.
|
| 322 |
+
indent : str
|
| 323 |
+
Indentation string.
|
| 324 |
+
help_flags : tuple[str, ...]
|
| 325 |
+
Help flag names.
|
| 326 |
+
version_flags : tuple[str, ...]
|
| 327 |
+
Version flag names.
|
| 328 |
+
|
| 329 |
+
Returns
|
| 330 |
+
-------
|
| 331 |
+
list[str]
|
| 332 |
+
Lines of bash code for completions at this command path.
|
| 333 |
+
"""
|
| 334 |
+
if command_path not in completion_data:
|
| 335 |
+
return [f"{indent}COMPREPLY=()"]
|
| 336 |
+
|
| 337 |
+
data = completion_data[command_path]
|
| 338 |
+
lines = []
|
| 339 |
+
|
| 340 |
+
options = []
|
| 341 |
+
keyword_args = [arg for arg in data.arguments if not arg.is_positional_only() and arg.show]
|
| 342 |
+
|
| 343 |
+
for argument in keyword_args:
|
| 344 |
+
for name in argument.parameter.name or []:
|
| 345 |
+
if name.startswith("-"):
|
| 346 |
+
options.append(name)
|
| 347 |
+
|
| 348 |
+
for name in argument.negatives:
|
| 349 |
+
if name.startswith("-"):
|
| 350 |
+
options.append(name)
|
| 351 |
+
|
| 352 |
+
flag_commands = []
|
| 353 |
+
for registered_command in data.commands:
|
| 354 |
+
for name in registered_command.names:
|
| 355 |
+
if name.startswith("-"):
|
| 356 |
+
flag_commands.append(name)
|
| 357 |
+
|
| 358 |
+
for flag in help_flags:
|
| 359 |
+
if flag.startswith("-") and flag not in options and flag not in flag_commands:
|
| 360 |
+
options.append(flag)
|
| 361 |
+
|
| 362 |
+
for flag in version_flags:
|
| 363 |
+
if flag.startswith("-") and flag not in options and flag not in flag_commands:
|
| 364 |
+
options.append(flag)
|
| 365 |
+
|
| 366 |
+
options.extend(flag_commands)
|
| 367 |
+
|
| 368 |
+
commands = []
|
| 369 |
+
for registered_command in data.commands:
|
| 370 |
+
for cmd_name in registered_command.names:
|
| 371 |
+
if not cmd_name.startswith("-"):
|
| 372 |
+
commands.append(cmd_name)
|
| 373 |
+
|
| 374 |
+
positional_args = [arg for arg in data.arguments if arg.index is not None and arg.show]
|
| 375 |
+
positional_args.sort(key=lambda a: a.index if a.index is not None else 0)
|
| 376 |
+
|
| 377 |
+
lines.append(f"{indent}if [[ ${{cur}} == -* ]]; then")
|
| 378 |
+
|
| 379 |
+
if options:
|
| 380 |
+
escaped_options = [_escape_bash_choice(opt) for opt in options]
|
| 381 |
+
options_str = " ".join(escaped_options)
|
| 382 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{options_str}' -- \"${{cur}}\") )")
|
| 383 |
+
else:
|
| 384 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 385 |
+
|
| 386 |
+
lines.append(f"{indent}else")
|
| 387 |
+
|
| 388 |
+
needs_value_completion = _check_if_prev_needs_value(data.arguments)
|
| 389 |
+
|
| 390 |
+
if needs_value_completion:
|
| 391 |
+
value_completion_lines = _generate_value_completion_for_prev(
|
| 392 |
+
data.arguments, commands, positional_args, f"{indent} "
|
| 393 |
+
)
|
| 394 |
+
lines.extend(value_completion_lines)
|
| 395 |
+
elif commands:
|
| 396 |
+
escaped_commands = [_escape_bash_choice(cmd) for cmd in commands]
|
| 397 |
+
commands_str = " ".join(escaped_commands)
|
| 398 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )")
|
| 399 |
+
elif positional_args:
|
| 400 |
+
lines.extend(_generate_positional_completion(positional_args, f"{indent} "))
|
| 401 |
+
else:
|
| 402 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 403 |
+
|
| 404 |
+
lines.append(f"{indent}fi")
|
| 405 |
+
|
| 406 |
+
return lines
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _generate_positional_completion(positional_args, indent: str) -> list[str]:
|
| 410 |
+
"""Generate position-aware positional argument completion.
|
| 411 |
+
|
| 412 |
+
Parameters
|
| 413 |
+
----------
|
| 414 |
+
positional_args : list
|
| 415 |
+
List of positional arguments sorted by index.
|
| 416 |
+
indent : str
|
| 417 |
+
Indentation string.
|
| 418 |
+
|
| 419 |
+
Returns
|
| 420 |
+
-------
|
| 421 |
+
list[str]
|
| 422 |
+
Lines of bash code for position-aware positional completion.
|
| 423 |
+
"""
|
| 424 |
+
lines = []
|
| 425 |
+
|
| 426 |
+
if len(positional_args) == 1:
|
| 427 |
+
# Single positional - simple case
|
| 428 |
+
choices = positional_args[0].get_choices(force=True)
|
| 429 |
+
action = get_completion_action(positional_args[0].hint)
|
| 430 |
+
if choices:
|
| 431 |
+
escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices]
|
| 432 |
+
choices_str = " ".join(escaped_choices)
|
| 433 |
+
lines.append(f"{indent}COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )")
|
| 434 |
+
else:
|
| 435 |
+
compgen_flag = _map_completion_action_to_bash(action)
|
| 436 |
+
if compgen_flag:
|
| 437 |
+
lines.append(f'{indent}COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )')
|
| 438 |
+
else:
|
| 439 |
+
lines.append(f"{indent}COMPREPLY=()")
|
| 440 |
+
else:
|
| 441 |
+
# Multiple positionals - use case statement for position-aware completion
|
| 442 |
+
lines.append(f"{indent}case ${{positional_count}} in")
|
| 443 |
+
|
| 444 |
+
for idx, argument in enumerate(positional_args):
|
| 445 |
+
choices = argument.get_choices(force=True)
|
| 446 |
+
action = get_completion_action(argument.hint)
|
| 447 |
+
lines.append(f"{indent} {idx})")
|
| 448 |
+
if choices:
|
| 449 |
+
escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices]
|
| 450 |
+
choices_str = " ".join(escaped_choices)
|
| 451 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )")
|
| 452 |
+
else:
|
| 453 |
+
compgen_flag = _map_completion_action_to_bash(action)
|
| 454 |
+
if compgen_flag:
|
| 455 |
+
lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )')
|
| 456 |
+
else:
|
| 457 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 458 |
+
lines.append(f"{indent} ;;")
|
| 459 |
+
|
| 460 |
+
# Default case for positions beyond defined positionals
|
| 461 |
+
# If any positional is a collection type, use it as the default
|
| 462 |
+
iterable_arg = next((arg for arg in positional_args if is_iterable_type(arg.hint)), None)
|
| 463 |
+
lines.append(f"{indent} *)")
|
| 464 |
+
if iterable_arg:
|
| 465 |
+
choices = iterable_arg.get_choices(force=True)
|
| 466 |
+
action = get_completion_action(iterable_arg.hint)
|
| 467 |
+
if choices:
|
| 468 |
+
escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices]
|
| 469 |
+
choices_str = " ".join(escaped_choices)
|
| 470 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )")
|
| 471 |
+
else:
|
| 472 |
+
compgen_flag = _map_completion_action_to_bash(action)
|
| 473 |
+
if compgen_flag:
|
| 474 |
+
lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )')
|
| 475 |
+
else:
|
| 476 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 477 |
+
else:
|
| 478 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 479 |
+
lines.append(f"{indent} ;;")
|
| 480 |
+
lines.append(f"{indent}esac")
|
| 481 |
+
|
| 482 |
+
return lines
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _check_if_prev_needs_value(arguments) -> bool:
|
| 486 |
+
"""Check if any options take values, requiring prev-word completion logic.
|
| 487 |
+
|
| 488 |
+
Parameters
|
| 489 |
+
----------
|
| 490 |
+
arguments : ArgumentCollection
|
| 491 |
+
Arguments to check.
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
bool
|
| 496 |
+
True if any option (starts with -) takes a value (is not a flag).
|
| 497 |
+
"""
|
| 498 |
+
for argument in arguments:
|
| 499 |
+
if not argument.is_flag():
|
| 500 |
+
for name in argument.parameter.name or []:
|
| 501 |
+
if name.startswith("-"):
|
| 502 |
+
return True
|
| 503 |
+
return False
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _generate_value_completion_for_prev(arguments, commands: list[str], positional_args, indent: str) -> list[str]:
|
| 507 |
+
"""Generate value completion based on previous word.
|
| 508 |
+
|
| 509 |
+
Parameters
|
| 510 |
+
----------
|
| 511 |
+
arguments : ArgumentCollection
|
| 512 |
+
Arguments with potential values.
|
| 513 |
+
commands : list[str]
|
| 514 |
+
Available commands at this level.
|
| 515 |
+
positional_args : list
|
| 516 |
+
List of positional arguments sorted by index.
|
| 517 |
+
indent : str
|
| 518 |
+
Indentation string.
|
| 519 |
+
|
| 520 |
+
Returns
|
| 521 |
+
-------
|
| 522 |
+
list[str]
|
| 523 |
+
Lines of bash code for value completion.
|
| 524 |
+
"""
|
| 525 |
+
lines = []
|
| 526 |
+
lines.append(f'{indent}case "${{prev}}" in')
|
| 527 |
+
|
| 528 |
+
has_cases = False
|
| 529 |
+
for argument in arguments:
|
| 530 |
+
if argument.is_flag():
|
| 531 |
+
continue
|
| 532 |
+
|
| 533 |
+
names = [name for name in (argument.parameter.name or []) if name.startswith("-")]
|
| 534 |
+
if not names:
|
| 535 |
+
continue
|
| 536 |
+
|
| 537 |
+
has_cases = True
|
| 538 |
+
choices = argument.get_choices(force=True)
|
| 539 |
+
action = get_completion_action(argument.hint)
|
| 540 |
+
|
| 541 |
+
for name in names:
|
| 542 |
+
lines.append(f"{indent} {name})")
|
| 543 |
+
|
| 544 |
+
if choices:
|
| 545 |
+
escaped_choices = [_escape_bash_choice(clean_choice_text(c)) for c in choices]
|
| 546 |
+
choices_str = " ".join(escaped_choices)
|
| 547 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{choices_str}' -- \"${{cur}}\") )")
|
| 548 |
+
else:
|
| 549 |
+
compgen_flag = _map_completion_action_to_bash(action)
|
| 550 |
+
if compgen_flag:
|
| 551 |
+
lines.append(f'{indent} COMPREPLY=( $(compgen {compgen_flag} -- "${{cur}}") )')
|
| 552 |
+
else:
|
| 553 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 554 |
+
|
| 555 |
+
lines.append(f"{indent} ;;")
|
| 556 |
+
|
| 557 |
+
if has_cases:
|
| 558 |
+
lines.append(f"{indent} *)")
|
| 559 |
+
if commands:
|
| 560 |
+
escaped_commands = [_escape_bash_choice(cmd) for cmd in commands]
|
| 561 |
+
commands_str = " ".join(escaped_commands)
|
| 562 |
+
lines.append(f"{indent} COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )")
|
| 563 |
+
elif positional_args:
|
| 564 |
+
lines.extend(_generate_positional_completion(positional_args, f"{indent} "))
|
| 565 |
+
else:
|
| 566 |
+
lines.append(f"{indent} COMPREPLY=()")
|
| 567 |
+
lines.append(f"{indent} ;;")
|
| 568 |
+
lines.append(f"{indent}esac")
|
| 569 |
+
else:
|
| 570 |
+
lines = []
|
| 571 |
+
if commands:
|
| 572 |
+
escaped_commands = [_escape_bash_choice(cmd) for cmd in commands]
|
| 573 |
+
commands_str = " ".join(escaped_commands)
|
| 574 |
+
lines.append(f"{indent}COMPREPLY=( $(compgen -W '{commands_str}' -- \"${{cur}}\") )")
|
| 575 |
+
elif positional_args:
|
| 576 |
+
lines.extend(_generate_positional_completion(positional_args, indent))
|
| 577 |
+
else:
|
| 578 |
+
lines.append(f"{indent}COMPREPLY=()")
|
| 579 |
+
|
| 580 |
+
return lines
|
.venv/lib/python3.10/site-packages/cyclopts/completion/detect.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shell detection utilities for completion generation.
|
| 2 |
+
|
| 3 |
+
This module provides functionality to detect the current shell type by inspecting
|
| 4 |
+
environment variables. This is useful for dynamically generating appropriate completion
|
| 5 |
+
scripts for different shell environments.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Literal
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ShellDetectionError(Exception):
|
| 15 |
+
"""Raised when the shell type cannot be detected."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _extract_shell_name(shell_string: str) -> Literal["zsh", "bash", "fish"] | None:
|
| 19 |
+
"""Extract shell name from a string (path or process name).
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
shell_string : str
|
| 24 |
+
String that may contain a shell name (e.g., "/bin/bash", "zsh", "-bash").
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
Literal["zsh", "bash", "fish"] | None
|
| 29 |
+
The detected shell type, or None if not recognized.
|
| 30 |
+
"""
|
| 31 |
+
shell_lower = shell_string.lower()
|
| 32 |
+
if "zsh" in shell_lower:
|
| 33 |
+
return "zsh"
|
| 34 |
+
elif "bash" in shell_lower:
|
| 35 |
+
return "bash"
|
| 36 |
+
elif "fish" in shell_lower:
|
| 37 |
+
return "fish"
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def detect_shell() -> Literal["zsh", "bash", "fish"]:
|
| 42 |
+
"""Detect the current shell type using multiple detection methods.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
Literal["zsh", "bash", "fish"]
|
| 47 |
+
The detected shell type.
|
| 48 |
+
|
| 49 |
+
Raises
|
| 50 |
+
------
|
| 51 |
+
ShellDetectionError
|
| 52 |
+
If the shell type cannot be determined from any detection method.
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
--------
|
| 56 |
+
>>> shell = detect_shell() # doctest: +SKIP
|
| 57 |
+
>>> print(f"Detected shell: {shell}") # doctest: +SKIP
|
| 58 |
+
Detected shell: bash
|
| 59 |
+
"""
|
| 60 |
+
if os.environ.get("ZSH_VERSION"):
|
| 61 |
+
return "zsh"
|
| 62 |
+
elif os.environ.get("BASH_VERSION"):
|
| 63 |
+
return "bash"
|
| 64 |
+
elif os.environ.get("FISH_VERSION"):
|
| 65 |
+
return "fish"
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
ppid = os.getppid()
|
| 69 |
+
result = subprocess.run(
|
| 70 |
+
["ps", "-p", str(ppid), "-o", "comm="],
|
| 71 |
+
capture_output=True,
|
| 72 |
+
text=True,
|
| 73 |
+
timeout=1,
|
| 74 |
+
)
|
| 75 |
+
if result.returncode == 0 and result.stdout:
|
| 76 |
+
parent_process = result.stdout.strip()
|
| 77 |
+
shell = _extract_shell_name(parent_process)
|
| 78 |
+
if shell:
|
| 79 |
+
return shell
|
| 80 |
+
except (subprocess.SubprocessError, FileNotFoundError, OSError):
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
shell_path = os.environ.get("SHELL", "")
|
| 84 |
+
if shell_path:
|
| 85 |
+
shell_name = Path(shell_path).name
|
| 86 |
+
shell = _extract_shell_name(shell_name)
|
| 87 |
+
if shell:
|
| 88 |
+
return shell
|
| 89 |
+
|
| 90 |
+
raise ShellDetectionError("Unable to detect shell type.")
|
.venv/lib/python3.10/site-packages/cyclopts/completion/fish.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fish completion script generator.
|
| 2 |
+
|
| 3 |
+
Generates static fish completion scripts using `complete -c COMMAND` statements.
|
| 4 |
+
Completions auto-load from ~/.config/fish/completions/PROGNAME.fish.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
from typing import TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
from cyclopts.completion._base import (
|
| 11 |
+
CompletionAction,
|
| 12 |
+
CompletionData,
|
| 13 |
+
clean_choice_text,
|
| 14 |
+
extract_completion_data,
|
| 15 |
+
get_completion_action,
|
| 16 |
+
strip_markup,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from cyclopts import App
|
| 21 |
+
from cyclopts.command_spec import CommandSpec
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def generate_completion_script(app: "App", prog_name: str) -> str:
|
| 25 |
+
"""Generate fish completion script.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
app : App
|
| 30 |
+
The Cyclopts application to generate completion for.
|
| 31 |
+
prog_name : str
|
| 32 |
+
Program name for completion (alphanumeric with hyphens/underscores).
|
| 33 |
+
|
| 34 |
+
Returns
|
| 35 |
+
-------
|
| 36 |
+
str
|
| 37 |
+
Complete fish completion script.
|
| 38 |
+
|
| 39 |
+
Raises
|
| 40 |
+
------
|
| 41 |
+
ValueError
|
| 42 |
+
If prog_name contains invalid characters.
|
| 43 |
+
"""
|
| 44 |
+
if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name):
|
| 45 |
+
raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.")
|
| 46 |
+
|
| 47 |
+
completion_data = extract_completion_data(app)
|
| 48 |
+
|
| 49 |
+
lines = [
|
| 50 |
+
f"# Fish completion for {prog_name}",
|
| 51 |
+
"# Generated by Cyclopts",
|
| 52 |
+
"",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
has_nested_commands = any(len(path) > 0 for path in completion_data.keys())
|
| 56 |
+
if has_nested_commands:
|
| 57 |
+
lines.extend(_generate_helper_functions(prog_name, completion_data))
|
| 58 |
+
lines.append("")
|
| 59 |
+
|
| 60 |
+
help_flags = tuple(app.help_flags) if app.help_flags else ()
|
| 61 |
+
version_flags = tuple(app.version_flags) if app.version_flags else ()
|
| 62 |
+
|
| 63 |
+
lines.extend(_generate_completions(completion_data, prog_name, help_flags, version_flags))
|
| 64 |
+
|
| 65 |
+
return "\n".join(lines) + "\n"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _escape_fish_string(text: str) -> str:
|
| 69 |
+
r"""Escape single quotes for fish strings."""
|
| 70 |
+
return text.replace("'", r"'\''")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _escape_fish_description(text: str) -> str:
|
| 74 |
+
"""Escape description text for fish."""
|
| 75 |
+
text = text.replace("\n", " ")
|
| 76 |
+
text = text.replace("\r", " ")
|
| 77 |
+
return _escape_fish_string(text)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _generate_helper_functions(
|
| 81 |
+
prog_name: str,
|
| 82 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 83 |
+
) -> list[str]:
|
| 84 |
+
"""Generate helper function for command path detection.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
prog_name : str
|
| 89 |
+
Program name.
|
| 90 |
+
completion_data : dict
|
| 91 |
+
Completion data used to identify options that take values.
|
| 92 |
+
|
| 93 |
+
Returns
|
| 94 |
+
-------
|
| 95 |
+
list[str]
|
| 96 |
+
Lines defining the helper function.
|
| 97 |
+
"""
|
| 98 |
+
options_with_values = set()
|
| 99 |
+
for data in completion_data.values():
|
| 100 |
+
for argument in data.arguments:
|
| 101 |
+
if not argument.is_flag() and argument.parameter.name:
|
| 102 |
+
for name in argument.parameter.name:
|
| 103 |
+
if name.startswith("-"):
|
| 104 |
+
options_with_values.add(name)
|
| 105 |
+
|
| 106 |
+
func_name = f"__fish_{prog_name}_using_command"
|
| 107 |
+
lines = [
|
| 108 |
+
"# Helper function to check exact command path sequence",
|
| 109 |
+
f"function {func_name}",
|
| 110 |
+
" set -l cmd (commandline -opc)",
|
| 111 |
+
" set -l subcommands",
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
if options_with_values:
|
| 115 |
+
escaped_opts = " ".join(_escape_fish_string(opt) for opt in sorted(options_with_values))
|
| 116 |
+
lines.append(f" set -l options_with_values '{escaped_opts}'")
|
| 117 |
+
else:
|
| 118 |
+
lines.append(" set -l options_with_values ''")
|
| 119 |
+
|
| 120 |
+
lines.extend(
|
| 121 |
+
[
|
| 122 |
+
" set -l skip_next 0",
|
| 123 |
+
" # Extract non-option words (commands) from command line",
|
| 124 |
+
" for i in (seq 2 (count $cmd))",
|
| 125 |
+
" set -l word $cmd[$i]",
|
| 126 |
+
" if test $skip_next -eq 1",
|
| 127 |
+
" set skip_next 0",
|
| 128 |
+
" continue",
|
| 129 |
+
" end",
|
| 130 |
+
" if string match -qr -- '^-' $word",
|
| 131 |
+
" # Check if this option takes a value (exact match)",
|
| 132 |
+
' if string match -q -- "* $word *" " $options_with_values "',
|
| 133 |
+
" set skip_next 1",
|
| 134 |
+
" end",
|
| 135 |
+
" else",
|
| 136 |
+
" # Non-option word is a command",
|
| 137 |
+
" set -a subcommands $word",
|
| 138 |
+
" end",
|
| 139 |
+
" end",
|
| 140 |
+
" # Check if subcommand sequence matches expected path",
|
| 141 |
+
" if test (count $subcommands) -ne (count $argv)",
|
| 142 |
+
" return 1",
|
| 143 |
+
" end",
|
| 144 |
+
" for i in (seq 1 (count $argv))",
|
| 145 |
+
" if test $subcommands[$i] != $argv[$i]",
|
| 146 |
+
" return 1",
|
| 147 |
+
" end",
|
| 148 |
+
" end",
|
| 149 |
+
" return 0",
|
| 150 |
+
"end",
|
| 151 |
+
]
|
| 152 |
+
)
|
| 153 |
+
return lines
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _map_completion_action_to_fish(action: CompletionAction) -> str:
|
| 157 |
+
"""Map completion action to fish flags.
|
| 158 |
+
|
| 159 |
+
Parameters
|
| 160 |
+
----------
|
| 161 |
+
action : CompletionAction
|
| 162 |
+
Completion action type.
|
| 163 |
+
|
| 164 |
+
Returns
|
| 165 |
+
-------
|
| 166 |
+
str
|
| 167 |
+
Fish completion flags ("-r -F" for files, "-r -a '(...)'" for directories, "" otherwise).
|
| 168 |
+
"""
|
| 169 |
+
if action == CompletionAction.FILES:
|
| 170 |
+
return "-r -F"
|
| 171 |
+
if action == CompletionAction.DIRECTORIES:
|
| 172 |
+
return "-r -a '(__fish_complete_directories)'"
|
| 173 |
+
return ""
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _generate_completions(
|
| 177 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 178 |
+
prog_name: str,
|
| 179 |
+
help_flags: tuple[str, ...],
|
| 180 |
+
version_flags: tuple[str, ...],
|
| 181 |
+
) -> list[str]:
|
| 182 |
+
"""Generate all fish completion commands.
|
| 183 |
+
|
| 184 |
+
Parameters
|
| 185 |
+
----------
|
| 186 |
+
completion_data : dict
|
| 187 |
+
Extracted completion data.
|
| 188 |
+
prog_name : str
|
| 189 |
+
Program name.
|
| 190 |
+
help_flags : tuple[str, ...]
|
| 191 |
+
Help flags.
|
| 192 |
+
version_flags : tuple[str, ...]
|
| 193 |
+
Version flags.
|
| 194 |
+
|
| 195 |
+
Returns
|
| 196 |
+
-------
|
| 197 |
+
list[str]
|
| 198 |
+
Completion command lines.
|
| 199 |
+
"""
|
| 200 |
+
lines = []
|
| 201 |
+
|
| 202 |
+
for command_path, _data in sorted(completion_data.items()):
|
| 203 |
+
lines.extend(
|
| 204 |
+
_generate_completions_for_path(
|
| 205 |
+
completion_data,
|
| 206 |
+
command_path,
|
| 207 |
+
prog_name,
|
| 208 |
+
help_flags,
|
| 209 |
+
version_flags,
|
| 210 |
+
)
|
| 211 |
+
)
|
| 212 |
+
if command_path != max(completion_data.keys(), key=len):
|
| 213 |
+
lines.append("")
|
| 214 |
+
|
| 215 |
+
return lines
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _generate_completions_for_path(
|
| 219 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 220 |
+
command_path: tuple[str, ...],
|
| 221 |
+
prog_name: str,
|
| 222 |
+
help_flags: tuple[str, ...],
|
| 223 |
+
version_flags: tuple[str, ...],
|
| 224 |
+
) -> list[str]:
|
| 225 |
+
"""Generate completions for a specific command path.
|
| 226 |
+
|
| 227 |
+
Parameters
|
| 228 |
+
----------
|
| 229 |
+
completion_data : dict
|
| 230 |
+
Extracted completion data.
|
| 231 |
+
command_path : tuple[str, ...]
|
| 232 |
+
Command path.
|
| 233 |
+
prog_name : str
|
| 234 |
+
Program name.
|
| 235 |
+
help_flags : tuple[str, ...]
|
| 236 |
+
Help flags.
|
| 237 |
+
version_flags : tuple[str, ...]
|
| 238 |
+
Version flags.
|
| 239 |
+
|
| 240 |
+
Returns
|
| 241 |
+
-------
|
| 242 |
+
list[str]
|
| 243 |
+
Completion command lines.
|
| 244 |
+
"""
|
| 245 |
+
if command_path not in completion_data:
|
| 246 |
+
return []
|
| 247 |
+
|
| 248 |
+
data = completion_data[command_path]
|
| 249 |
+
lines = []
|
| 250 |
+
condition = _get_condition_for_path(command_path, prog_name)
|
| 251 |
+
|
| 252 |
+
lines.extend(_generate_subcommand_completions(data, command_path, prog_name, condition))
|
| 253 |
+
|
| 254 |
+
keyword_args = [arg for arg in data.arguments if not arg.is_positional_only() and arg.show]
|
| 255 |
+
if keyword_args or help_flags or version_flags:
|
| 256 |
+
lines.extend(_generate_option_section_header(command_path))
|
| 257 |
+
lines.extend(_generate_help_version_completions(prog_name, condition, help_flags, version_flags))
|
| 258 |
+
lines.extend(_generate_keyword_arg_completions(keyword_args, prog_name, condition, data.help_format))
|
| 259 |
+
lines.extend(_generate_command_option_completions(data.commands, prog_name, condition, data.help_format))
|
| 260 |
+
|
| 261 |
+
return lines
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _generate_subcommand_completions(
|
| 265 |
+
data: CompletionData,
|
| 266 |
+
command_path: tuple[str, ...],
|
| 267 |
+
prog_name: str,
|
| 268 |
+
condition: str,
|
| 269 |
+
) -> list[str]:
|
| 270 |
+
"""Generate completions for subcommands.
|
| 271 |
+
|
| 272 |
+
Parameters
|
| 273 |
+
----------
|
| 274 |
+
data : CompletionData
|
| 275 |
+
Completion data.
|
| 276 |
+
command_path : tuple[str, ...]
|
| 277 |
+
Command path.
|
| 278 |
+
prog_name : str
|
| 279 |
+
Program name.
|
| 280 |
+
condition : str
|
| 281 |
+
Fish condition.
|
| 282 |
+
|
| 283 |
+
Returns
|
| 284 |
+
-------
|
| 285 |
+
list[str]
|
| 286 |
+
Completion command lines.
|
| 287 |
+
"""
|
| 288 |
+
commands = [
|
| 289 |
+
name for registered_command in data.commands for name in registered_command.names if not name.startswith("-")
|
| 290 |
+
]
|
| 291 |
+
if not commands:
|
| 292 |
+
return []
|
| 293 |
+
|
| 294 |
+
lines = []
|
| 295 |
+
if command_path:
|
| 296 |
+
lines.append(f"# Subcommands for: {' '.join(command_path)}")
|
| 297 |
+
else:
|
| 298 |
+
lines.append("# Root-level commands")
|
| 299 |
+
|
| 300 |
+
for registered_command in data.commands:
|
| 301 |
+
for cmd_name in registered_command.names:
|
| 302 |
+
if cmd_name.startswith("-"):
|
| 303 |
+
continue
|
| 304 |
+
|
| 305 |
+
desc = _get_description_from_app(registered_command.app, data.help_format)
|
| 306 |
+
escaped_desc = _escape_fish_description(desc)
|
| 307 |
+
escaped_cmd = _escape_fish_string(cmd_name)
|
| 308 |
+
|
| 309 |
+
lines.append(f"complete -c {prog_name} {condition} -a '{escaped_cmd}' -d '{escaped_desc}'")
|
| 310 |
+
|
| 311 |
+
return lines
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _generate_option_section_header(command_path: tuple[str, ...]) -> list[str]:
|
| 315 |
+
"""Generate section header comment for options.
|
| 316 |
+
|
| 317 |
+
Parameters
|
| 318 |
+
----------
|
| 319 |
+
command_path : tuple[str, ...]
|
| 320 |
+
Command path.
|
| 321 |
+
|
| 322 |
+
Returns
|
| 323 |
+
-------
|
| 324 |
+
list[str]
|
| 325 |
+
Comment line.
|
| 326 |
+
"""
|
| 327 |
+
if command_path:
|
| 328 |
+
return [f"# Options for: {' '.join(command_path)}"]
|
| 329 |
+
return ["# Root-level options"]
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _generate_help_version_completions(
|
| 333 |
+
prog_name: str,
|
| 334 |
+
condition: str,
|
| 335 |
+
help_flags: tuple[str, ...],
|
| 336 |
+
version_flags: tuple[str, ...],
|
| 337 |
+
) -> list[str]:
|
| 338 |
+
"""Generate completions for help and version flags.
|
| 339 |
+
|
| 340 |
+
Parameters
|
| 341 |
+
----------
|
| 342 |
+
prog_name : str
|
| 343 |
+
Program name.
|
| 344 |
+
condition : str
|
| 345 |
+
Fish condition.
|
| 346 |
+
help_flags : tuple[str, ...]
|
| 347 |
+
Help flags.
|
| 348 |
+
version_flags : tuple[str, ...]
|
| 349 |
+
Version flags.
|
| 350 |
+
|
| 351 |
+
Returns
|
| 352 |
+
-------
|
| 353 |
+
list[str]
|
| 354 |
+
Completion command lines.
|
| 355 |
+
"""
|
| 356 |
+
lines = []
|
| 357 |
+
|
| 358 |
+
for flag in help_flags:
|
| 359 |
+
if flag.startswith("--"):
|
| 360 |
+
long_name = flag[2:]
|
| 361 |
+
lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d 'Display this message and exit.'")
|
| 362 |
+
elif flag.startswith("-") and len(flag) == 2:
|
| 363 |
+
short_name = flag[1]
|
| 364 |
+
lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d 'Display this message and exit.'")
|
| 365 |
+
|
| 366 |
+
for flag in version_flags:
|
| 367 |
+
if flag.startswith("--"):
|
| 368 |
+
long_name = flag[2:]
|
| 369 |
+
lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d 'Display application version.'")
|
| 370 |
+
elif flag.startswith("-") and len(flag) == 2:
|
| 371 |
+
short_name = flag[1]
|
| 372 |
+
lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d 'Display application version.'")
|
| 373 |
+
|
| 374 |
+
return lines
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _generate_keyword_arg_completions(
|
| 378 |
+
keyword_args: list,
|
| 379 |
+
prog_name: str,
|
| 380 |
+
condition: str,
|
| 381 |
+
help_format: str,
|
| 382 |
+
) -> list[str]:
|
| 383 |
+
"""Generate completions for keyword arguments.
|
| 384 |
+
|
| 385 |
+
Parameters
|
| 386 |
+
----------
|
| 387 |
+
keyword_args : list
|
| 388 |
+
Keyword arguments.
|
| 389 |
+
prog_name : str
|
| 390 |
+
Program name.
|
| 391 |
+
condition : str
|
| 392 |
+
Fish condition.
|
| 393 |
+
help_format : str
|
| 394 |
+
Help text format.
|
| 395 |
+
|
| 396 |
+
Returns
|
| 397 |
+
-------
|
| 398 |
+
list[str]
|
| 399 |
+
Completion command lines.
|
| 400 |
+
"""
|
| 401 |
+
lines = []
|
| 402 |
+
|
| 403 |
+
for argument in keyword_args:
|
| 404 |
+
desc = strip_markup(argument.parameter.help or "", format=help_format)
|
| 405 |
+
escaped_desc = _escape_fish_description(desc)
|
| 406 |
+
|
| 407 |
+
is_flag = argument.is_flag()
|
| 408 |
+
choices = argument.get_choices(force=True)
|
| 409 |
+
action = get_completion_action(argument.hint)
|
| 410 |
+
|
| 411 |
+
for name in argument.parameter.name or []:
|
| 412 |
+
if not name.startswith("-"):
|
| 413 |
+
continue
|
| 414 |
+
|
| 415 |
+
if name.startswith("--"):
|
| 416 |
+
long_name = name[2:]
|
| 417 |
+
line_parts = [f"complete -c {prog_name} {condition} -l {long_name}"]
|
| 418 |
+
elif len(name) == 2:
|
| 419 |
+
short_name = name[1]
|
| 420 |
+
line_parts = [f"complete -c {prog_name} {condition} -s {short_name}"]
|
| 421 |
+
else:
|
| 422 |
+
continue
|
| 423 |
+
|
| 424 |
+
if is_flag:
|
| 425 |
+
line_parts.append(f"-d '{escaped_desc}'")
|
| 426 |
+
elif choices:
|
| 427 |
+
escaped_choices = [_escape_fish_string(clean_choice_text(c)) for c in choices]
|
| 428 |
+
choices_str = " ".join(escaped_choices)
|
| 429 |
+
line_parts.append(f"-x -a '{choices_str}' -d '{escaped_desc}'")
|
| 430 |
+
else:
|
| 431 |
+
action_flags = _map_completion_action_to_fish(action)
|
| 432 |
+
if action_flags:
|
| 433 |
+
line_parts.append(f"{action_flags} -d '{escaped_desc}'")
|
| 434 |
+
else:
|
| 435 |
+
line_parts.append(f"-r -d '{escaped_desc}'")
|
| 436 |
+
|
| 437 |
+
lines.append(" ".join(line_parts))
|
| 438 |
+
|
| 439 |
+
for name in argument.negatives:
|
| 440 |
+
if not name.startswith("-"):
|
| 441 |
+
continue
|
| 442 |
+
|
| 443 |
+
if name.startswith("--"):
|
| 444 |
+
long_name = name[2:]
|
| 445 |
+
lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d '{escaped_desc}'")
|
| 446 |
+
elif len(name) == 2:
|
| 447 |
+
short_name = name[1]
|
| 448 |
+
lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d '{escaped_desc}'")
|
| 449 |
+
|
| 450 |
+
return lines
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def _generate_command_option_completions(
|
| 454 |
+
commands: list,
|
| 455 |
+
prog_name: str,
|
| 456 |
+
condition: str,
|
| 457 |
+
help_format: str,
|
| 458 |
+
) -> list[str]:
|
| 459 |
+
"""Generate completions for commands that look like options.
|
| 460 |
+
|
| 461 |
+
Parameters
|
| 462 |
+
----------
|
| 463 |
+
commands : list
|
| 464 |
+
List of RegisteredCommand tuples.
|
| 465 |
+
prog_name : str
|
| 466 |
+
Program name.
|
| 467 |
+
condition : str
|
| 468 |
+
Fish condition.
|
| 469 |
+
help_format : str
|
| 470 |
+
Help text format.
|
| 471 |
+
|
| 472 |
+
Returns
|
| 473 |
+
-------
|
| 474 |
+
list[str]
|
| 475 |
+
Completion command lines.
|
| 476 |
+
"""
|
| 477 |
+
lines = []
|
| 478 |
+
|
| 479 |
+
for registered_command in commands:
|
| 480 |
+
for cmd_name in registered_command.names:
|
| 481 |
+
if not cmd_name.startswith("-"):
|
| 482 |
+
continue
|
| 483 |
+
|
| 484 |
+
desc = _get_description_from_app(registered_command.app, help_format)
|
| 485 |
+
escaped_desc = _escape_fish_description(desc)
|
| 486 |
+
|
| 487 |
+
if cmd_name.startswith("--"):
|
| 488 |
+
long_name = cmd_name[2:]
|
| 489 |
+
lines.append(f"complete -c {prog_name} {condition} -l {long_name} -d '{escaped_desc}'")
|
| 490 |
+
elif len(cmd_name) == 2:
|
| 491 |
+
short_name = cmd_name[1]
|
| 492 |
+
lines.append(f"complete -c {prog_name} {condition} -s {short_name} -d '{escaped_desc}'")
|
| 493 |
+
|
| 494 |
+
return lines
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def _get_condition_for_path(command_path: tuple[str, ...], prog_name: str) -> str:
|
| 498 |
+
"""Generate fish condition string for a command path.
|
| 499 |
+
|
| 500 |
+
Parameters
|
| 501 |
+
----------
|
| 502 |
+
command_path : tuple[str, ...]
|
| 503 |
+
Command path (empty for root).
|
| 504 |
+
prog_name : str
|
| 505 |
+
Program name.
|
| 506 |
+
|
| 507 |
+
Returns
|
| 508 |
+
-------
|
| 509 |
+
str
|
| 510 |
+
Fish condition flag.
|
| 511 |
+
"""
|
| 512 |
+
if not command_path:
|
| 513 |
+
return "-n __fish_use_subcommand"
|
| 514 |
+
|
| 515 |
+
func_name = f"__fish_{prog_name}_using_command"
|
| 516 |
+
escaped_commands = " ".join(_escape_fish_string(cmd) for cmd in command_path)
|
| 517 |
+
return f"-n '{func_name} {escaped_commands}'"
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _get_description_from_app(cmd_app: "App | CommandSpec", help_format: str) -> str:
|
| 521 |
+
"""Extract description from App.
|
| 522 |
+
|
| 523 |
+
Parameters
|
| 524 |
+
----------
|
| 525 |
+
cmd_app : App | CommandSpec
|
| 526 |
+
Command app or spec.
|
| 527 |
+
help_format : str
|
| 528 |
+
Help text format.
|
| 529 |
+
|
| 530 |
+
Returns
|
| 531 |
+
-------
|
| 532 |
+
str
|
| 533 |
+
Description text.
|
| 534 |
+
"""
|
| 535 |
+
from cyclopts.help.help import docstring_parse
|
| 536 |
+
|
| 537 |
+
try:
|
| 538 |
+
parsed = docstring_parse(cmd_app.help, "plaintext")
|
| 539 |
+
text = parsed.short_description or ""
|
| 540 |
+
except Exception:
|
| 541 |
+
text = str(cmd_app.help or "")
|
| 542 |
+
|
| 543 |
+
return strip_markup(text, format=help_format)
|
.venv/lib/python3.10/site-packages/cyclopts/completion/install.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shell completion installation utilities.
|
| 2 |
+
|
| 3 |
+
This module handles the installation of completion scripts to shell-specific
|
| 4 |
+
locations and the updating of shell RC files to load completions.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from collections.abc import Callable
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Annotated, Literal
|
| 12 |
+
|
| 13 |
+
from cyclopts.parameter import Parameter
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _detect_omz_completions_dir() -> Path | None:
|
| 17 |
+
"""Detect oh-my-zsh custom completions directory.
|
| 18 |
+
|
| 19 |
+
Uses ``$ZSH_CUSTOM/completions`` (the recommended location for user
|
| 20 |
+
completions in oh-my-zsh). Falls back to ``$ZSH/custom/completions``
|
| 21 |
+
when ``$ZSH_CUSTOM`` is not set.
|
| 22 |
+
|
| 23 |
+
Returns
|
| 24 |
+
-------
|
| 25 |
+
Path | None
|
| 26 |
+
Path to the oh-my-zsh custom completions directory, or None if
|
| 27 |
+
oh-my-zsh is not detected.
|
| 28 |
+
"""
|
| 29 |
+
zsh_custom_str = os.environ.get("ZSH_CUSTOM")
|
| 30 |
+
if zsh_custom_str:
|
| 31 |
+
zsh_custom = Path(zsh_custom_str)
|
| 32 |
+
if zsh_custom.is_dir():
|
| 33 |
+
return zsh_custom / "completions"
|
| 34 |
+
zsh_dir_str = os.environ.get("ZSH")
|
| 35 |
+
if not zsh_dir_str:
|
| 36 |
+
return None
|
| 37 |
+
zsh_dir = Path(zsh_dir_str)
|
| 38 |
+
if zsh_dir.is_dir():
|
| 39 |
+
return zsh_dir / "custom" / "completions"
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_default_completion_path(shell: Literal["zsh", "bash", "fish"], prog_name: str) -> Path:
|
| 44 |
+
"""Get the default completion script path for a given shell.
|
| 45 |
+
|
| 46 |
+
Parameters
|
| 47 |
+
----------
|
| 48 |
+
shell : Literal["zsh", "bash", "fish"]
|
| 49 |
+
Shell type.
|
| 50 |
+
prog_name : str
|
| 51 |
+
Program name for the completion script.
|
| 52 |
+
|
| 53 |
+
Returns
|
| 54 |
+
-------
|
| 55 |
+
Path
|
| 56 |
+
Default installation path for the shell.
|
| 57 |
+
|
| 58 |
+
Raises
|
| 59 |
+
------
|
| 60 |
+
ValueError
|
| 61 |
+
If shell type is unsupported.
|
| 62 |
+
"""
|
| 63 |
+
home = Path.home()
|
| 64 |
+
if shell == "zsh":
|
| 65 |
+
omz_completions = _detect_omz_completions_dir()
|
| 66 |
+
if omz_completions is not None:
|
| 67 |
+
omz_completions.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
return omz_completions / f"_{prog_name}"
|
| 69 |
+
# Vanilla zsh fallback
|
| 70 |
+
zsh_completions = home / ".zsh" / "completions"
|
| 71 |
+
zsh_completions.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
return zsh_completions / f"_{prog_name}"
|
| 73 |
+
elif shell == "bash":
|
| 74 |
+
bash_completions = home / ".local" / "share" / "bash-completion" / "completions"
|
| 75 |
+
bash_completions.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
return bash_completions / prog_name
|
| 77 |
+
elif shell == "fish":
|
| 78 |
+
fish_completions = home / ".config" / "fish" / "completions"
|
| 79 |
+
fish_completions.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
return fish_completions / f"{prog_name}.fish"
|
| 81 |
+
else:
|
| 82 |
+
raise ValueError(f"Unsupported shell: {shell}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def add_to_rc_file(script_path: Path, prog_name: str, shell: Literal["bash", "zsh"]) -> bool:
|
| 86 |
+
"""Add completion configuration to shell RC file.
|
| 87 |
+
|
| 88 |
+
For bash, adds a source line to load the completion script.
|
| 89 |
+
For zsh, adds the completion directory to fpath so compinit can find it.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
script_path : Path
|
| 94 |
+
Path to the completion script.
|
| 95 |
+
prog_name : str
|
| 96 |
+
Program name for display in comments.
|
| 97 |
+
shell : Literal["bash", "zsh"]
|
| 98 |
+
Shell type.
|
| 99 |
+
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
bool
|
| 103 |
+
True if configuration was added, False if it already existed or on error.
|
| 104 |
+
"""
|
| 105 |
+
if shell == "bash":
|
| 106 |
+
rc_file = Path.home() / ".bashrc"
|
| 107 |
+
config_line = f'[ -f "{script_path}" ] && . "{script_path}"'
|
| 108 |
+
comment = f"# Load {prog_name} completion"
|
| 109 |
+
elif shell == "zsh":
|
| 110 |
+
if _detect_omz_completions_dir():
|
| 111 |
+
return False
|
| 112 |
+
rc_file = Path.home() / ".zshrc"
|
| 113 |
+
completion_dir = script_path.parent
|
| 114 |
+
config_line = f"fpath=({completion_dir} $fpath)"
|
| 115 |
+
comment = f"# {prog_name} completions"
|
| 116 |
+
else:
|
| 117 |
+
raise NotImplementedError
|
| 118 |
+
|
| 119 |
+
rc_file = rc_file.resolve()
|
| 120 |
+
|
| 121 |
+
if rc_file.exists():
|
| 122 |
+
content = rc_file.read_text()
|
| 123 |
+
# For zsh, check if this directory is already in fpath configuration
|
| 124 |
+
# For bash, check if the exact source line exists
|
| 125 |
+
if shell == "zsh" and str(script_path.parent) in content and "fpath=" in content:
|
| 126 |
+
return False
|
| 127 |
+
elif config_line in content:
|
| 128 |
+
return False
|
| 129 |
+
else:
|
| 130 |
+
content = ""
|
| 131 |
+
|
| 132 |
+
if shell == "zsh":
|
| 133 |
+
# Prepend to ensure fpath is set before any compinit call
|
| 134 |
+
rc_file.write_text(f"{comment}\n{config_line}\n{content}")
|
| 135 |
+
else:
|
| 136 |
+
# Bash: append
|
| 137 |
+
needs_newline = content and not content.endswith("\n")
|
| 138 |
+
with rc_file.open("a") as f:
|
| 139 |
+
if needs_newline:
|
| 140 |
+
f.write("\n")
|
| 141 |
+
f.write(f"{comment}\n{config_line}\n")
|
| 142 |
+
|
| 143 |
+
return True
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def create_install_completion_command(
|
| 147 |
+
install_completion_fn: Callable[..., Path],
|
| 148 |
+
add_to_startup: bool,
|
| 149 |
+
):
|
| 150 |
+
"""Create a command function for installing shell completion.
|
| 151 |
+
|
| 152 |
+
Parameters
|
| 153 |
+
----------
|
| 154 |
+
install_completion_fn : Callable
|
| 155 |
+
Function that performs the actual installation (typically App.install_completion).
|
| 156 |
+
Should accept (shell, output, add_to_startup) and return the installation path.
|
| 157 |
+
add_to_startup : bool
|
| 158 |
+
Whether to add source line to shell RC file.
|
| 159 |
+
|
| 160 |
+
Returns
|
| 161 |
+
-------
|
| 162 |
+
Callable
|
| 163 |
+
Command function that can be registered with App.command().
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
def _install_completion_command(
|
| 167 |
+
*,
|
| 168 |
+
shell: Annotated[Literal["zsh", "bash", "fish"] | None, Parameter()] = None,
|
| 169 |
+
output: Annotated[Path | None, Parameter(name=["-o", "--output"])] = None,
|
| 170 |
+
):
|
| 171 |
+
"""Install shell completion for this application.
|
| 172 |
+
|
| 173 |
+
This command generates and installs the completion script to the appropriate
|
| 174 |
+
location for your shell. After installation, you may need to restart your
|
| 175 |
+
shell or source your shell configuration file.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
shell : Literal["zsh", "bash", "fish"] | None
|
| 180 |
+
Shell type for completion. If not specified, attempts to auto-detect current shell.
|
| 181 |
+
output : Path | None
|
| 182 |
+
Output path for the completion script. If not specified, uses shell-specific default.
|
| 183 |
+
"""
|
| 184 |
+
from cyclopts.completion.detect import ShellDetectionError, detect_shell
|
| 185 |
+
|
| 186 |
+
if shell is None:
|
| 187 |
+
try:
|
| 188 |
+
shell = detect_shell()
|
| 189 |
+
except ShellDetectionError:
|
| 190 |
+
print(
|
| 191 |
+
"Could not auto-detect shell. Please specify --shell explicitly.",
|
| 192 |
+
file=sys.stderr,
|
| 193 |
+
)
|
| 194 |
+
sys.exit(1)
|
| 195 |
+
|
| 196 |
+
install_path = install_completion_fn(shell=shell, output=output, add_to_startup=add_to_startup)
|
| 197 |
+
|
| 198 |
+
print(f"✓ Completion script installed to {install_path}")
|
| 199 |
+
|
| 200 |
+
if shell == "zsh":
|
| 201 |
+
if _detect_omz_completions_dir():
|
| 202 |
+
print("✓ Detected oh-my-zsh: completions directory is already in $fpath.")
|
| 203 |
+
print("\nRestart your shell or run: exec zsh")
|
| 204 |
+
elif add_to_startup:
|
| 205 |
+
zshrc = Path.home() / ".zshrc"
|
| 206 |
+
completion_dir = install_path.parent
|
| 207 |
+
print(f"✓ Added {completion_dir} to fpath in {zshrc}")
|
| 208 |
+
print("\nNote: Ensure compinit is configured in your .zshrc (most zsh setups already have this).")
|
| 209 |
+
print("Restart your shell or run: exec zsh")
|
| 210 |
+
else:
|
| 211 |
+
completion_dir = install_path.parent
|
| 212 |
+
print(f"\nTo enable completions, ensure {completion_dir} is in your $fpath.")
|
| 213 |
+
print("Add this to your ~/.zshrc or ~/.zprofile if not already present:")
|
| 214 |
+
print(f" fpath=({completion_dir} $fpath)")
|
| 215 |
+
print(" autoload -Uz compinit && compinit")
|
| 216 |
+
print("\nThen restart your shell or run: exec zsh")
|
| 217 |
+
elif shell == "bash":
|
| 218 |
+
if add_to_startup:
|
| 219 |
+
bashrc = Path.home() / ".bashrc"
|
| 220 |
+
print(f"✓ Added completion loader to {bashrc}")
|
| 221 |
+
print("\nRestart your shell or run: source ~/.bashrc")
|
| 222 |
+
else:
|
| 223 |
+
print("\nCompletions will be automatically loaded by bash-completion.")
|
| 224 |
+
print("If completions don't work:")
|
| 225 |
+
print(" 1. Ensure bash-completion is installed (v2.8+)")
|
| 226 |
+
print(" 2. Restart your shell or run: exec bash")
|
| 227 |
+
print("\nNote: bash-completion is typically installed via:")
|
| 228 |
+
print(" - macOS: brew install bash-completion@2")
|
| 229 |
+
print(" - Debian/Ubuntu: apt install bash-completion")
|
| 230 |
+
print(" - Fedora/RHEL: dnf install bash-completion")
|
| 231 |
+
elif shell == "fish":
|
| 232 |
+
print("\nCompletions are automatically loaded in fish.")
|
| 233 |
+
print("Restart your shell or run: source ~/.config/fish/config.fish")
|
| 234 |
+
else:
|
| 235 |
+
raise NotImplementedError
|
| 236 |
+
|
| 237 |
+
return _install_completion_command
|
.venv/lib/python3.10/site-packages/cyclopts/completion/zsh.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Zsh completion script generator.
|
| 2 |
+
|
| 3 |
+
Generates static zsh completion scripts using the compsys framework.
|
| 4 |
+
No runtime Python dependency.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
from textwrap import dedent
|
| 9 |
+
from textwrap import indent as textwrap_indent
|
| 10 |
+
from typing import TYPE_CHECKING
|
| 11 |
+
|
| 12 |
+
from cyclopts.annotations import is_iterable_type
|
| 13 |
+
from cyclopts.completion._base import (
|
| 14 |
+
CompletionAction,
|
| 15 |
+
CompletionData,
|
| 16 |
+
clean_choice_text,
|
| 17 |
+
escape_for_shell_pattern,
|
| 18 |
+
extract_completion_data,
|
| 19 |
+
get_completion_action,
|
| 20 |
+
strip_markup,
|
| 21 |
+
)
|
| 22 |
+
from cyclopts.help.help import docstring_parse
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from cyclopts import App
|
| 26 |
+
from cyclopts.argument import Argument, ArgumentCollection
|
| 27 |
+
from cyclopts.command_spec import CommandSpec
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def generate_completion_script(app: "App", prog_name: str) -> str:
|
| 31 |
+
"""Generate zsh completion script.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
app : App
|
| 36 |
+
The Cyclopts application to generate completion for.
|
| 37 |
+
prog_name : str
|
| 38 |
+
Program name (alphanumeric with hyphens/underscores).
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
str
|
| 43 |
+
Complete zsh completion script.
|
| 44 |
+
|
| 45 |
+
Raises
|
| 46 |
+
------
|
| 47 |
+
ValueError
|
| 48 |
+
If prog_name contains invalid characters.
|
| 49 |
+
"""
|
| 50 |
+
if not prog_name or not re.match(r"^[a-zA-Z0-9_-]+$", prog_name):
|
| 51 |
+
raise ValueError(f"Invalid prog_name: {prog_name!r}. Must be alphanumeric with hyphens/underscores.")
|
| 52 |
+
|
| 53 |
+
completion_data = extract_completion_data(app)
|
| 54 |
+
|
| 55 |
+
lines = [
|
| 56 |
+
f"#compdef {prog_name}",
|
| 57 |
+
"",
|
| 58 |
+
f"_{prog_name}() {{",
|
| 59 |
+
" local line state",
|
| 60 |
+
"",
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
lines.extend(
|
| 64 |
+
_generate_completion_for_path(
|
| 65 |
+
completion_data,
|
| 66 |
+
(),
|
| 67 |
+
prog_name=prog_name,
|
| 68 |
+
help_flags=tuple(app.help_flags) if app.help_flags else (),
|
| 69 |
+
version_flags=tuple(app.version_flags) if app.version_flags else (),
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
lines.extend(
|
| 74 |
+
[
|
| 75 |
+
"}",
|
| 76 |
+
"",
|
| 77 |
+
]
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
return "\n".join(lines) + "\n"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _generate_run_command_completion(
|
| 84 |
+
arguments: "ArgumentCollection",
|
| 85 |
+
indent_str: str,
|
| 86 |
+
prog_name: str,
|
| 87 |
+
) -> list[str]:
|
| 88 |
+
"""Generate dynamic completion for the 'run' command.
|
| 89 |
+
|
| 90 |
+
Parameters
|
| 91 |
+
----------
|
| 92 |
+
arguments : ArgumentCollection
|
| 93 |
+
Arguments for run command.
|
| 94 |
+
indent_str : str
|
| 95 |
+
Indentation string.
|
| 96 |
+
prog_name : str
|
| 97 |
+
Program name.
|
| 98 |
+
|
| 99 |
+
Returns
|
| 100 |
+
-------
|
| 101 |
+
list[str]
|
| 102 |
+
Zsh completion code lines.
|
| 103 |
+
"""
|
| 104 |
+
template = dedent(f"""\
|
| 105 |
+
local script_path
|
| 106 |
+
local -a completions
|
| 107 |
+
local -a remaining_words
|
| 108 |
+
|
| 109 |
+
# If completing first argument (the script path), suggest files
|
| 110 |
+
if [[ $CURRENT -eq 2 ]]; then
|
| 111 |
+
_files
|
| 112 |
+
return
|
| 113 |
+
fi
|
| 114 |
+
|
| 115 |
+
# Get absolute path to the script file
|
| 116 |
+
script_path=${{words[2]}}
|
| 117 |
+
script_path=${{script_path:a}}
|
| 118 |
+
if [[ -f $script_path ]]; then
|
| 119 |
+
remaining_words=(${{words[3,-1]}})
|
| 120 |
+
local result
|
| 121 |
+
local cmd
|
| 122 |
+
|
| 123 |
+
if command -v {prog_name} &>/dev/null; then
|
| 124 |
+
cmd="{prog_name}"
|
| 125 |
+
else
|
| 126 |
+
return
|
| 127 |
+
fi
|
| 128 |
+
# Call back into cyclopts to get dynamic completions from the script
|
| 129 |
+
result=$($cmd _complete run "$script_path" "${{remaining_words[@]}}" 2>/dev/null)
|
| 130 |
+
if [[ -n $result ]]; then
|
| 131 |
+
# Parse and display completion results
|
| 132 |
+
completions=()
|
| 133 |
+
while IFS= read -r line; do
|
| 134 |
+
completions+=($line)
|
| 135 |
+
done <<< $result
|
| 136 |
+
_describe 'command' completions
|
| 137 |
+
fi
|
| 138 |
+
fi""")
|
| 139 |
+
|
| 140 |
+
indented = textwrap_indent(template, indent_str)
|
| 141 |
+
return [line.rstrip() for line in indented.split("\n")]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _generate_nested_positional_specs(
|
| 145 |
+
positional_args: list["Argument"],
|
| 146 |
+
help_format: str,
|
| 147 |
+
) -> list[str]:
|
| 148 |
+
"""Generate positional argument specs for nested command context.
|
| 149 |
+
|
| 150 |
+
In nested contexts (after *::arg:->args), word indexing is shifted:
|
| 151 |
+
- words[1] = subcommand name
|
| 152 |
+
- words[2] = first positional argument
|
| 153 |
+
- words[3] = second positional argument, etc.
|
| 154 |
+
|
| 155 |
+
Parameters
|
| 156 |
+
----------
|
| 157 |
+
positional_args : list[Argument]
|
| 158 |
+
Positional arguments to generate specs for.
|
| 159 |
+
help_format : str
|
| 160 |
+
Help text format.
|
| 161 |
+
|
| 162 |
+
Returns
|
| 163 |
+
-------
|
| 164 |
+
list[str]
|
| 165 |
+
List of zsh positional argument specs.
|
| 166 |
+
"""
|
| 167 |
+
specs = []
|
| 168 |
+
|
| 169 |
+
# Check if we have variadic positionals (including collection types like list[X])
|
| 170 |
+
variadic_args = [arg for arg in positional_args if arg.is_var_positional() or is_iterable_type(arg.hint)]
|
| 171 |
+
non_variadic_args = [
|
| 172 |
+
arg for arg in positional_args if not arg.is_var_positional() and not is_iterable_type(arg.hint)
|
| 173 |
+
]
|
| 174 |
+
|
| 175 |
+
# Generate specs for non-variadic positionals
|
| 176 |
+
for arg in non_variadic_args:
|
| 177 |
+
# Position in nested context: After *::arg:->args, $words[1] is the subcommand
|
| 178 |
+
# So positionals start at position 1 (not 2)
|
| 179 |
+
# Use 1-based indexing: first positional is '1:', second is '2:', etc.
|
| 180 |
+
pos = 1 + (arg.index or 0)
|
| 181 |
+
desc = _get_description_from_argument(arg, help_format)
|
| 182 |
+
|
| 183 |
+
# Check for choices first (Literal/Enum types)
|
| 184 |
+
choices = arg.get_choices(force=True)
|
| 185 |
+
if choices:
|
| 186 |
+
escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices]
|
| 187 |
+
choices_str = " ".join(escaped_choices)
|
| 188 |
+
action = f"({choices_str})"
|
| 189 |
+
else:
|
| 190 |
+
action = _map_completion_action_to_zsh(get_completion_action(arg.hint))
|
| 191 |
+
|
| 192 |
+
spec = f"'{pos}:{desc}:{action}'" if action else f"'{pos}:{desc}'"
|
| 193 |
+
specs.append(spec)
|
| 194 |
+
|
| 195 |
+
# Generate specs for variadic positionals
|
| 196 |
+
for arg in variadic_args:
|
| 197 |
+
desc = _get_description_from_argument(arg, help_format)
|
| 198 |
+
|
| 199 |
+
choices = arg.get_choices(force=True)
|
| 200 |
+
if choices:
|
| 201 |
+
escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices]
|
| 202 |
+
choices_str = " ".join(escaped_choices)
|
| 203 |
+
action = f"({choices_str})"
|
| 204 |
+
else:
|
| 205 |
+
action = _map_completion_action_to_zsh(get_completion_action(arg.hint))
|
| 206 |
+
|
| 207 |
+
spec = f"'*:{desc}:{action}'" if action else f"'*:{desc}'"
|
| 208 |
+
specs.append(spec)
|
| 209 |
+
|
| 210 |
+
return specs
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _generate_describe_completion(
|
| 214 |
+
argument: "Argument",
|
| 215 |
+
help_format: str,
|
| 216 |
+
indent_str: str,
|
| 217 |
+
) -> list[str]:
|
| 218 |
+
"""Generate _describe-based completion for a single positional argument.
|
| 219 |
+
|
| 220 |
+
Parameters
|
| 221 |
+
----------
|
| 222 |
+
argument : Argument
|
| 223 |
+
Argument to generate completion for.
|
| 224 |
+
help_format : str
|
| 225 |
+
Help text format.
|
| 226 |
+
indent_str : str
|
| 227 |
+
Indentation string.
|
| 228 |
+
|
| 229 |
+
Returns
|
| 230 |
+
-------
|
| 231 |
+
list[str]
|
| 232 |
+
Zsh completion code lines.
|
| 233 |
+
"""
|
| 234 |
+
lines = []
|
| 235 |
+
desc = _get_description_from_argument(argument, help_format)
|
| 236 |
+
|
| 237 |
+
# Check for choices (Literal/Enum types)
|
| 238 |
+
choices = argument.get_choices(force=True)
|
| 239 |
+
if choices:
|
| 240 |
+
# Generate choices array with descriptions
|
| 241 |
+
escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices]
|
| 242 |
+
lines.append(f"{indent_str}local -a choices")
|
| 243 |
+
lines.append(f"{indent_str}choices=(")
|
| 244 |
+
for choice in escaped_choices:
|
| 245 |
+
lines.append(f"{indent_str} '{choice}:{desc}'")
|
| 246 |
+
lines.append(f"{indent_str})")
|
| 247 |
+
lines.append(f"{indent_str}_describe 'argument' choices")
|
| 248 |
+
else:
|
| 249 |
+
# Use completion action (files, directories, or nothing)
|
| 250 |
+
action = get_completion_action(argument.hint)
|
| 251 |
+
if action == CompletionAction.FILES:
|
| 252 |
+
lines.append(f"{indent_str}_files")
|
| 253 |
+
elif action == CompletionAction.DIRECTORIES:
|
| 254 |
+
lines.append(f"{indent_str}_directories")
|
| 255 |
+
# For other types, provide no completion
|
| 256 |
+
|
| 257 |
+
return lines
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _generate_completion_for_path(
|
| 261 |
+
completion_data: dict[tuple[str, ...], CompletionData],
|
| 262 |
+
command_path: tuple[str, ...],
|
| 263 |
+
indent: int = 2,
|
| 264 |
+
prog_name: str = "cyclopts",
|
| 265 |
+
help_flags: tuple[str, ...] = (),
|
| 266 |
+
version_flags: tuple[str, ...] = (),
|
| 267 |
+
) -> list[str]:
|
| 268 |
+
"""Generate completion code for a specific command path.
|
| 269 |
+
|
| 270 |
+
Parameters
|
| 271 |
+
----------
|
| 272 |
+
completion_data : dict
|
| 273 |
+
Extracted completion data.
|
| 274 |
+
command_path : tuple[str, ...]
|
| 275 |
+
Command path.
|
| 276 |
+
indent : int
|
| 277 |
+
Indentation level.
|
| 278 |
+
prog_name : str
|
| 279 |
+
Program name.
|
| 280 |
+
help_flags : tuple[str, ...]
|
| 281 |
+
Help flags.
|
| 282 |
+
version_flags : tuple[str, ...]
|
| 283 |
+
Version flags.
|
| 284 |
+
|
| 285 |
+
Returns
|
| 286 |
+
-------
|
| 287 |
+
list[str]
|
| 288 |
+
Zsh code lines.
|
| 289 |
+
"""
|
| 290 |
+
data = completion_data[command_path]
|
| 291 |
+
commands = data.commands
|
| 292 |
+
arguments = data.arguments
|
| 293 |
+
indent_str = " " * indent
|
| 294 |
+
lines = []
|
| 295 |
+
|
| 296 |
+
if command_path == ("run",) and prog_name == "cyclopts":
|
| 297 |
+
lines.extend(_generate_run_command_completion(arguments, indent_str, prog_name))
|
| 298 |
+
return lines
|
| 299 |
+
|
| 300 |
+
args_specs = []
|
| 301 |
+
positional_specs = []
|
| 302 |
+
|
| 303 |
+
# Separate positional from keyword arguments
|
| 304 |
+
# Include all arguments with an index (both positional-only and positional-or-keyword)
|
| 305 |
+
positional_args = [arg for arg in arguments if arg.index is not None and arg.show]
|
| 306 |
+
keyword_args = [arg for arg in arguments if not arg.is_positional_only() and arg.show]
|
| 307 |
+
|
| 308 |
+
# Sort positionals by index (should never be None for positional-only args)
|
| 309 |
+
positional_args.sort(key=lambda a: a.index or 0)
|
| 310 |
+
|
| 311 |
+
# Generate keyword argument specs
|
| 312 |
+
for argument in keyword_args:
|
| 313 |
+
specs = _generate_keyword_specs(argument, data.help_format)
|
| 314 |
+
args_specs.extend(specs)
|
| 315 |
+
|
| 316 |
+
# Check for flag commands (commands that look like options)
|
| 317 |
+
flag_command_names = set()
|
| 318 |
+
for registered_command in commands:
|
| 319 |
+
if any(name.startswith("-") for name in registered_command.names):
|
| 320 |
+
specs = _generate_keyword_specs_for_command(
|
| 321 |
+
registered_command.names, registered_command.app, data.help_format
|
| 322 |
+
)
|
| 323 |
+
args_specs.extend(specs)
|
| 324 |
+
flag_command_names.update(registered_command.names)
|
| 325 |
+
|
| 326 |
+
# Add help and version flags to all command paths (if not already added as flag commands)
|
| 327 |
+
for flag in help_flags:
|
| 328 |
+
if flag.startswith("-") and flag not in flag_command_names:
|
| 329 |
+
spec = f"'{flag}[Display this message and exit.]'"
|
| 330 |
+
args_specs.append(spec)
|
| 331 |
+
|
| 332 |
+
for flag in version_flags:
|
| 333 |
+
if flag.startswith("-") and flag not in flag_command_names:
|
| 334 |
+
spec = f"'{flag}[Display application version.]'"
|
| 335 |
+
args_specs.append(spec)
|
| 336 |
+
|
| 337 |
+
has_non_flag_commands = any(
|
| 338 |
+
not cmd_name.startswith("-") for registered_command in commands for cmd_name in registered_command.names
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
# Generate positional argument specs
|
| 342 |
+
# Only add positionals if there are no subcommands (they conflict in zsh)
|
| 343 |
+
if positional_args and not has_non_flag_commands:
|
| 344 |
+
if command_path:
|
| 345 |
+
# Nested context: use shifted positional indexing (words[1] is subcommand)
|
| 346 |
+
positional_specs = _generate_nested_positional_specs(positional_args, data.help_format)
|
| 347 |
+
else:
|
| 348 |
+
# Root context: standard _arguments works fine
|
| 349 |
+
for argument in positional_args:
|
| 350 |
+
spec = _generate_positional_spec(argument, data.help_format)
|
| 351 |
+
positional_specs.append(spec)
|
| 352 |
+
|
| 353 |
+
# Add positionals BEFORE options to prioritize them in completion
|
| 354 |
+
args_specs = positional_specs + args_specs
|
| 355 |
+
|
| 356 |
+
if has_non_flag_commands:
|
| 357 |
+
args_specs.append("'1: :->cmds'")
|
| 358 |
+
args_specs.append("'*::arg:->args'")
|
| 359 |
+
|
| 360 |
+
if args_specs:
|
| 361 |
+
c_flag = "-C " if has_non_flag_commands else ""
|
| 362 |
+
lines.append(f"{indent_str}_arguments {c_flag}\\")
|
| 363 |
+
for spec in args_specs[:-1]:
|
| 364 |
+
lines.append(f"{indent_str} {spec} \\")
|
| 365 |
+
lines.append(f"{indent_str} {args_specs[-1]}")
|
| 366 |
+
lines.append("")
|
| 367 |
+
|
| 368 |
+
if has_non_flag_commands:
|
| 369 |
+
lines.append(f"{indent_str}case $state in")
|
| 370 |
+
lines.append(f"{indent_str} cmds)")
|
| 371 |
+
|
| 372 |
+
cmd_list = []
|
| 373 |
+
for registered_command in commands:
|
| 374 |
+
for cmd_name in registered_command.names:
|
| 375 |
+
if not cmd_name.startswith("-"):
|
| 376 |
+
desc = _safe_get_description_from_app(registered_command.app, data.help_format)
|
| 377 |
+
escaped_cmd_name = _escape_completion_choice(cmd_name)
|
| 378 |
+
cmd_list.append(f"'{escaped_cmd_name}:{desc}'")
|
| 379 |
+
|
| 380 |
+
lines.append(f"{indent_str} local -a commands")
|
| 381 |
+
lines.append(f"{indent_str} commands=(")
|
| 382 |
+
for cmd in cmd_list:
|
| 383 |
+
lines.append(f"{indent_str} {cmd}")
|
| 384 |
+
lines.append(f"{indent_str} )")
|
| 385 |
+
lines.append(f"{indent_str} _describe -t commands 'command' commands")
|
| 386 |
+
lines.append(f"{indent_str} ;;")
|
| 387 |
+
|
| 388 |
+
lines.append(f"{indent_str} args)")
|
| 389 |
+
lines.append(f"{indent_str} case $words[1] in")
|
| 390 |
+
|
| 391 |
+
for registered_command in commands:
|
| 392 |
+
for cmd_name in registered_command.names:
|
| 393 |
+
if cmd_name.startswith("-"):
|
| 394 |
+
continue
|
| 395 |
+
|
| 396 |
+
sub_path = command_path + (cmd_name,)
|
| 397 |
+
if sub_path in completion_data:
|
| 398 |
+
escaped_case_name = _escape_command_name_for_case(cmd_name)
|
| 399 |
+
lines.append(f"{indent_str} {escaped_case_name})")
|
| 400 |
+
sub_lines = _generate_completion_for_path(
|
| 401 |
+
completion_data, sub_path, indent + 8, prog_name, help_flags, version_flags
|
| 402 |
+
)
|
| 403 |
+
lines.extend(sub_lines)
|
| 404 |
+
lines.append(f"{indent_str} ;;")
|
| 405 |
+
|
| 406 |
+
lines.append(f"{indent_str} esac")
|
| 407 |
+
lines.append(f"{indent_str} ;;")
|
| 408 |
+
lines.append(f"{indent_str}esac")
|
| 409 |
+
|
| 410 |
+
return lines
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _escape_completion_choice(choice: str) -> str:
|
| 414 |
+
"""Escape special characters in a completion choice value for zsh.
|
| 415 |
+
|
| 416 |
+
Choice should already be cleaned via clean_choice_text() before calling this function.
|
| 417 |
+
This function only applies zsh-specific escaping.
|
| 418 |
+
|
| 419 |
+
Parameters
|
| 420 |
+
----------
|
| 421 |
+
choice : str
|
| 422 |
+
Cleaned choice value.
|
| 423 |
+
|
| 424 |
+
Returns
|
| 425 |
+
-------
|
| 426 |
+
str
|
| 427 |
+
Escaped choice value safe for zsh completion.
|
| 428 |
+
"""
|
| 429 |
+
choice = choice.replace("\\", "\\\\")
|
| 430 |
+
choice = choice.replace("'", r"'\''")
|
| 431 |
+
choice = choice.replace("`", "\\`")
|
| 432 |
+
choice = choice.replace("$", "\\$")
|
| 433 |
+
choice = choice.replace('"', '\\"')
|
| 434 |
+
choice = choice.replace(" ", "\\ ")
|
| 435 |
+
choice = choice.replace("(", "\\(")
|
| 436 |
+
choice = choice.replace(")", "\\)")
|
| 437 |
+
choice = choice.replace("[", "\\[")
|
| 438 |
+
choice = choice.replace("]", "\\]")
|
| 439 |
+
choice = choice.replace(";", "\\;")
|
| 440 |
+
choice = choice.replace("|", "\\|")
|
| 441 |
+
choice = choice.replace("&", "\\&")
|
| 442 |
+
choice = choice.replace(":", "\\:")
|
| 443 |
+
return choice
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _escape_command_name_for_case(name: str) -> str:
|
| 447 |
+
"""Escape special characters in command name for zsh case patterns.
|
| 448 |
+
|
| 449 |
+
In zsh case patterns, glob characters need to be escaped to match literally.
|
| 450 |
+
Colons also need escaping because zsh's completion system may treat them
|
| 451 |
+
specially when populating the $words array after _describe completion.
|
| 452 |
+
|
| 453 |
+
Parameters
|
| 454 |
+
----------
|
| 455 |
+
name : str
|
| 456 |
+
Command name.
|
| 457 |
+
|
| 458 |
+
Returns
|
| 459 |
+
-------
|
| 460 |
+
str
|
| 461 |
+
Escaped command name safe for zsh case patterns.
|
| 462 |
+
"""
|
| 463 |
+
# zsh case patterns have more special chars than bash: includes ()|
|
| 464 |
+
# Colons (:) also need escaping for completion $words matching (issue #715)
|
| 465 |
+
return escape_for_shell_pattern(name, chars="*?[]()|:")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _escape_zsh_description(text: str) -> str:
|
| 469 |
+
"""Escape special characters in description text for zsh.
|
| 470 |
+
|
| 471 |
+
Parameters
|
| 472 |
+
----------
|
| 473 |
+
text : str
|
| 474 |
+
Cleaned description text.
|
| 475 |
+
|
| 476 |
+
Returns
|
| 477 |
+
-------
|
| 478 |
+
str
|
| 479 |
+
Escaped description safe for zsh completion.
|
| 480 |
+
"""
|
| 481 |
+
text = text.replace("\\", "\\\\")
|
| 482 |
+
text = text.replace("`", "\\`")
|
| 483 |
+
text = text.replace("$", "\\$")
|
| 484 |
+
text = text.replace('"', '\\"')
|
| 485 |
+
text = text.replace("'", r"'\''")
|
| 486 |
+
text = text.replace(":", r"\:")
|
| 487 |
+
text = text.replace("[", r"\[")
|
| 488 |
+
text = text.replace("]", r"\]")
|
| 489 |
+
return text
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def _generate_keyword_specs(argument: "Argument", help_format: str) -> list[str]:
|
| 493 |
+
"""Generate zsh _arguments specs for a keyword argument.
|
| 494 |
+
|
| 495 |
+
Parameters
|
| 496 |
+
----------
|
| 497 |
+
argument : Argument
|
| 498 |
+
Argument object from ArgumentCollection.
|
| 499 |
+
help_format : str
|
| 500 |
+
Help text format.
|
| 501 |
+
|
| 502 |
+
Returns
|
| 503 |
+
-------
|
| 504 |
+
list[str]
|
| 505 |
+
List of zsh argument specs.
|
| 506 |
+
"""
|
| 507 |
+
specs = []
|
| 508 |
+
desc = _get_description_from_argument(argument, help_format)
|
| 509 |
+
|
| 510 |
+
flag = argument.is_flag()
|
| 511 |
+
|
| 512 |
+
# Determine completion action
|
| 513 |
+
action = ""
|
| 514 |
+
choices = argument.get_choices(force=True)
|
| 515 |
+
if choices:
|
| 516 |
+
escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices]
|
| 517 |
+
choices_str = " ".join(escaped_choices)
|
| 518 |
+
action = f"({choices_str})"
|
| 519 |
+
flag = False
|
| 520 |
+
else:
|
| 521 |
+
action = _map_completion_action_to_zsh(get_completion_action(argument.hint))
|
| 522 |
+
|
| 523 |
+
# Generate specs for positive names (from parameter.name)
|
| 524 |
+
for name in argument.parameter.name: # pyright: ignore[reportOptionalIterable]
|
| 525 |
+
if not name.startswith("-"):
|
| 526 |
+
continue
|
| 527 |
+
if flag and not action:
|
| 528 |
+
spec = f"'{name}[{desc}]'"
|
| 529 |
+
elif action:
|
| 530 |
+
spec = f"'{name}[{desc}]:{name.lstrip('-')}:{action}'"
|
| 531 |
+
else:
|
| 532 |
+
spec = f"'{name}[{desc}]:{name.lstrip('-')}'"
|
| 533 |
+
specs.append(spec)
|
| 534 |
+
|
| 535 |
+
# Generate specs for negative names (always flags, consume no tokens)
|
| 536 |
+
for name in argument.negatives:
|
| 537 |
+
if not name.startswith("-"):
|
| 538 |
+
continue
|
| 539 |
+
# Negative flags always consume zero tokens (e.g., --empty-items, --no-verbose)
|
| 540 |
+
spec = f"'{name}[{desc}]'"
|
| 541 |
+
specs.append(spec)
|
| 542 |
+
|
| 543 |
+
return specs
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def _generate_positional_spec(argument: "Argument", help_format: str) -> str:
|
| 547 |
+
"""Generate zsh _arguments spec for a positional argument.
|
| 548 |
+
|
| 549 |
+
Parameters
|
| 550 |
+
----------
|
| 551 |
+
argument : Argument
|
| 552 |
+
Positional argument object.
|
| 553 |
+
help_format : str
|
| 554 |
+
Help text format.
|
| 555 |
+
|
| 556 |
+
Returns
|
| 557 |
+
-------
|
| 558 |
+
str
|
| 559 |
+
Zsh positional argument spec.
|
| 560 |
+
"""
|
| 561 |
+
desc = _get_description_from_argument(argument, help_format)
|
| 562 |
+
|
| 563 |
+
# Check for choices first (Literal/Enum types)
|
| 564 |
+
choices = argument.get_choices(force=True)
|
| 565 |
+
if choices:
|
| 566 |
+
escaped_choices = [_escape_completion_choice(clean_choice_text(c)) for c in choices]
|
| 567 |
+
choices_str = " ".join(escaped_choices)
|
| 568 |
+
action = f"({choices_str})"
|
| 569 |
+
else:
|
| 570 |
+
action = _map_completion_action_to_zsh(get_completion_action(argument.hint))
|
| 571 |
+
|
| 572 |
+
if argument.is_var_positional() or is_iterable_type(argument.hint):
|
| 573 |
+
# Variadic positional (*args) or collection type (list[X], set[X], etc.)
|
| 574 |
+
return f"'*:{desc}:{action}'" if action else f"'*:{desc}'"
|
| 575 |
+
|
| 576 |
+
# Regular positional - zsh uses 1-based indexing
|
| 577 |
+
if argument.index is None:
|
| 578 |
+
raise ValueError(f"Positional-only argument {argument.names} missing index")
|
| 579 |
+
pos = argument.index + 1
|
| 580 |
+
return f"'{pos}:{desc}:{action}'" if action else f"'{pos}:{desc}'"
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _generate_keyword_specs_for_command(
|
| 584 |
+
names: tuple[str, ...], cmd_app: "App | CommandSpec", help_format: str
|
| 585 |
+
) -> list[str]:
|
| 586 |
+
"""Generate zsh _arguments specs for a command that looks like a flag.
|
| 587 |
+
|
| 588 |
+
Parameters
|
| 589 |
+
----------
|
| 590 |
+
names : tuple[str, ...]
|
| 591 |
+
Registered names for the command.
|
| 592 |
+
cmd_app : App | CommandSpec
|
| 593 |
+
Command app or spec.
|
| 594 |
+
help_format : str
|
| 595 |
+
Help text format.
|
| 596 |
+
|
| 597 |
+
Returns
|
| 598 |
+
-------
|
| 599 |
+
list[str]
|
| 600 |
+
List of zsh argument specs.
|
| 601 |
+
"""
|
| 602 |
+
specs = []
|
| 603 |
+
desc = _safe_get_description_from_app(cmd_app, help_format)
|
| 604 |
+
|
| 605 |
+
for name in names:
|
| 606 |
+
if name.startswith("-"):
|
| 607 |
+
spec = f"'{name}[{desc}]'"
|
| 608 |
+
specs.append(spec)
|
| 609 |
+
|
| 610 |
+
return specs
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _map_completion_action_to_zsh(action: CompletionAction) -> str:
|
| 614 |
+
"""Map shell-agnostic completion action to zsh-specific completion command.
|
| 615 |
+
|
| 616 |
+
Parameters
|
| 617 |
+
----------
|
| 618 |
+
action : CompletionAction
|
| 619 |
+
Shell-agnostic completion action.
|
| 620 |
+
|
| 621 |
+
Returns
|
| 622 |
+
-------
|
| 623 |
+
str
|
| 624 |
+
Zsh completion command (e.g., "_files", "_directories", or "").
|
| 625 |
+
"""
|
| 626 |
+
if action == CompletionAction.FILES:
|
| 627 |
+
return "_files"
|
| 628 |
+
elif action == CompletionAction.DIRECTORIES:
|
| 629 |
+
return "_directories"
|
| 630 |
+
return ""
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def _get_description_from_argument(argument: "Argument", help_format: str) -> str:
|
| 634 |
+
"""Extract plain text description from Argument, escaping zsh special chars.
|
| 635 |
+
|
| 636 |
+
Parameters
|
| 637 |
+
----------
|
| 638 |
+
argument : Argument
|
| 639 |
+
Argument object with parameter help text.
|
| 640 |
+
help_format : str
|
| 641 |
+
Help text format.
|
| 642 |
+
|
| 643 |
+
Returns
|
| 644 |
+
-------
|
| 645 |
+
str
|
| 646 |
+
Escaped plain text description (truncated to 80 chars).
|
| 647 |
+
Falls back to argument name if help text is empty, since zsh _arguments
|
| 648 |
+
requires a non-empty description for positional specs to work correctly.
|
| 649 |
+
"""
|
| 650 |
+
text = strip_markup(argument.parameter.help or "", format=help_format)
|
| 651 |
+
if not text:
|
| 652 |
+
# Use primary argument name as fallback - zsh _arguments requires non-empty
|
| 653 |
+
# description for positional specs to provide completions
|
| 654 |
+
text = argument.names[0] if argument.names else "argument"
|
| 655 |
+
return _escape_zsh_description(text)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def _safe_get_description_from_app(cmd_app: "App | CommandSpec", help_format: str) -> str:
|
| 659 |
+
"""Extract plain text description from App, escaping zsh special chars.
|
| 660 |
+
|
| 661 |
+
Parameters
|
| 662 |
+
----------
|
| 663 |
+
cmd_app : App | CommandSpec
|
| 664 |
+
Command app or spec with help text.
|
| 665 |
+
help_format : str
|
| 666 |
+
Help text format.
|
| 667 |
+
|
| 668 |
+
Returns
|
| 669 |
+
-------
|
| 670 |
+
str
|
| 671 |
+
Escaped plain text description (truncated to 80 chars).
|
| 672 |
+
"""
|
| 673 |
+
try:
|
| 674 |
+
parsed = docstring_parse(cmd_app.help, "plaintext")
|
| 675 |
+
text = parsed.short_description or ""
|
| 676 |
+
except Exception:
|
| 677 |
+
text = str(cmd_app.help or "")
|
| 678 |
+
|
| 679 |
+
text = strip_markup(text, format=help_format)
|
| 680 |
+
return _escape_zsh_description(text)
|
.venv/lib/python3.10/site-packages/cyclopts/config/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = [
|
| 2 |
+
"ConfigFromFile",
|
| 3 |
+
"Dict",
|
| 4 |
+
"Env",
|
| 5 |
+
"Json",
|
| 6 |
+
"Toml",
|
| 7 |
+
"Yaml",
|
| 8 |
+
]
|
| 9 |
+
|
| 10 |
+
from cyclopts.config._common import ConfigFromFile, Dict
|
| 11 |
+
from cyclopts.config._env import Env
|
| 12 |
+
from cyclopts.config._json import Json
|
| 13 |
+
from cyclopts.config._toml import Toml
|
| 14 |
+
from cyclopts.config._yaml import Yaml
|
.venv/lib/python3.10/site-packages/cyclopts/config/_common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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import os
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
from collections.abc import Iterable
|
| 5 |
+
from contextlib import suppress
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import TYPE_CHECKING, Any
|
| 9 |
+
|
| 10 |
+
from attrs import define, field
|
| 11 |
+
|
| 12 |
+
from cyclopts.argument import ArgumentCollection, update_argument_collection
|
| 13 |
+
from cyclopts.exceptions import CycloptsError
|
| 14 |
+
from cyclopts.utils import to_tuple_converter
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _root_keys_converter(value: Iterable[str]) -> tuple[str, ...]:
|
| 18 |
+
return to_tuple_converter(value) # type: ignore[return-value]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from cyclopts.core import App
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@define(kw_only=True)
|
| 26 |
+
class ConfigBase(ABC):
|
| 27 |
+
"""Base class for configuration sources.
|
| 28 |
+
|
| 29 |
+
Handles the common logic of processing configuration dictionaries
|
| 30 |
+
and updating ArgumentCollections.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
root_keys: Iterable[str] = field(default=(), converter=_root_keys_converter)
|
| 34 |
+
allow_unknown: bool = field(default=False)
|
| 35 |
+
use_commands_as_keys: bool = field(default=True)
|
| 36 |
+
_source: str | None = field(default=None, alias="source")
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
@abstractmethod
|
| 40 |
+
def config(self) -> dict[str, Any]:
|
| 41 |
+
"""Return the configuration dictionary."""
|
| 42 |
+
raise NotImplementedError
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
@abstractmethod
|
| 46 |
+
def source(self) -> str:
|
| 47 |
+
"""Return a string identifying the configuration source for error messages."""
|
| 48 |
+
raise NotImplementedError
|
| 49 |
+
|
| 50 |
+
def __call__(
|
| 51 |
+
self,
|
| 52 |
+
app: "App",
|
| 53 |
+
commands: tuple[str, ...],
|
| 54 |
+
arguments: ArgumentCollection,
|
| 55 |
+
):
|
| 56 |
+
config: dict[str, Any] = self.config.copy()
|
| 57 |
+
try:
|
| 58 |
+
for key in chain(self.root_keys, commands if self.use_commands_as_keys else ()):
|
| 59 |
+
config = config[key]
|
| 60 |
+
except KeyError:
|
| 61 |
+
return
|
| 62 |
+
|
| 63 |
+
# Hierarchical config uses current app; flat config uses root app to filter sibling commands
|
| 64 |
+
if self.use_commands_as_keys:
|
| 65 |
+
filter_app = app
|
| 66 |
+
else:
|
| 67 |
+
filter_app = next((a for a in app.app_stack.current_frame if not a._meta_parent), app)
|
| 68 |
+
config = {k: v for k, v in config.items() if k not in filter_app}
|
| 69 |
+
|
| 70 |
+
update_argument_collection(
|
| 71 |
+
config,
|
| 72 |
+
self.source,
|
| 73 |
+
arguments,
|
| 74 |
+
app.app_stack.stack[-1],
|
| 75 |
+
root_keys=self.root_keys,
|
| 76 |
+
allow_unknown=self.allow_unknown,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class FileCacheKey:
|
| 81 |
+
"""Abstraction to quickly check if a file needs to be read again.
|
| 82 |
+
|
| 83 |
+
If a newly instantiated ``CacheKey`` doesn't equal a previously instantiated ``CacheKey``,
|
| 84 |
+
then the file needs to be re-read.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
def __init__(self, path: str | Path):
|
| 88 |
+
self.path = Path(path).absolute()
|
| 89 |
+
if self.path.exists():
|
| 90 |
+
stat = self.path.stat()
|
| 91 |
+
self._mtime = stat.st_mtime
|
| 92 |
+
self._size = stat.st_size
|
| 93 |
+
else:
|
| 94 |
+
self._mtime = None
|
| 95 |
+
self._size = None
|
| 96 |
+
|
| 97 |
+
def __eq__(self, other):
|
| 98 |
+
if not isinstance(other, type(self)):
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
return self._mtime == other._mtime and self._size == other._size and self.path == other.path
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@define
|
| 105 |
+
class ConfigFromFile(ConfigBase):
|
| 106 |
+
"""Configuration source that loads from a file.
|
| 107 |
+
|
| 108 |
+
Supports file caching and parent directory searching.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
path: str | Path = field(converter=Path)
|
| 112 |
+
must_exist: bool = field(default=False, kw_only=True)
|
| 113 |
+
search_parents: bool = field(default=False, kw_only=True)
|
| 114 |
+
|
| 115 |
+
_config: dict[str, Any] | None = field(default=None, init=False, repr=False)
|
| 116 |
+
"Loaded configuration structure (to be loaded by subclassed ``_load_config`` method)."
|
| 117 |
+
|
| 118 |
+
_config_cache_key: FileCacheKey | None = field(default=None, init=False, repr=False)
|
| 119 |
+
"Conditions under which ``_config`` was loaded."
|
| 120 |
+
|
| 121 |
+
@abstractmethod
|
| 122 |
+
def _load_config(self, path: Path) -> dict[str, Any]:
|
| 123 |
+
"""Load the config dictionary from path.
|
| 124 |
+
|
| 125 |
+
Do **not** do any downstream caching; ``ConfigFromFile`` handles caching.
|
| 126 |
+
|
| 127 |
+
Parameters
|
| 128 |
+
----------
|
| 129 |
+
path: Path
|
| 130 |
+
Path to the file. Guaranteed to exist.
|
| 131 |
+
|
| 132 |
+
Returns
|
| 133 |
+
-------
|
| 134 |
+
dict
|
| 135 |
+
Loaded configuration.
|
| 136 |
+
"""
|
| 137 |
+
raise NotImplementedError
|
| 138 |
+
|
| 139 |
+
@property
|
| 140 |
+
def config(self) -> dict[str, Any]:
|
| 141 |
+
assert isinstance(self.path, Path)
|
| 142 |
+
for parent in self.path.expanduser().resolve().absolute().parents:
|
| 143 |
+
candidate = parent / self.path.name
|
| 144 |
+
if candidate.exists():
|
| 145 |
+
cache_key = FileCacheKey(candidate)
|
| 146 |
+
if self._config_cache_key == cache_key:
|
| 147 |
+
return self._config or {}
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
self._config = self._load_config(candidate)
|
| 151 |
+
self._config_cache_key = cache_key
|
| 152 |
+
except CycloptsError:
|
| 153 |
+
raise
|
| 154 |
+
except Exception as e:
|
| 155 |
+
msg = getattr(type(e), "__name__", "")
|
| 156 |
+
with suppress(IndexError):
|
| 157 |
+
exception_msg = e.args[0]
|
| 158 |
+
if msg:
|
| 159 |
+
msg += ": "
|
| 160 |
+
msg += exception_msg
|
| 161 |
+
raise CycloptsError(msg=msg) from e
|
| 162 |
+
return self._config
|
| 163 |
+
elif self.search_parents:
|
| 164 |
+
# Continue iterating over parents.
|
| 165 |
+
continue
|
| 166 |
+
elif self.must_exist:
|
| 167 |
+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), str(self.path))
|
| 168 |
+
|
| 169 |
+
# No matching file was found.
|
| 170 |
+
if self.must_exist:
|
| 171 |
+
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), str(self.path))
|
| 172 |
+
|
| 173 |
+
self._config = {}
|
| 174 |
+
return self._config
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def source(self) -> str:
|
| 178 |
+
"""Return a string identifying the configuration source for error messages."""
|
| 179 |
+
if self._source is not None:
|
| 180 |
+
return self._source
|
| 181 |
+
assert isinstance(self.path, Path)
|
| 182 |
+
return str(self.path.absolute())
|
| 183 |
+
|
| 184 |
+
@source.setter
|
| 185 |
+
def source(self, value: str) -> None:
|
| 186 |
+
self._source = value
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@define
|
| 190 |
+
class Dict(ConfigBase):
|
| 191 |
+
"""Configuration source from an in-memory dictionary.
|
| 192 |
+
|
| 193 |
+
Useful for programmatically generated configurations.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
data: dict[str, Any]
|
| 197 |
+
|
| 198 |
+
@property
|
| 199 |
+
def config(self) -> dict[str, Any]:
|
| 200 |
+
return self.data
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def source(self) -> str:
|
| 204 |
+
"""Return a string identifying the configuration source for error messages."""
|
| 205 |
+
if self._source is not None:
|
| 206 |
+
return self._source
|
| 207 |
+
return "dict"
|
| 208 |
+
|
| 209 |
+
@source.setter
|
| 210 |
+
def source(self, value: str) -> None:
|
| 211 |
+
self._source = value
|
.venv/lib/python3.10/site-packages/cyclopts/config/_env.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
from attrs import define, field
|
| 5 |
+
|
| 6 |
+
from cyclopts.argument import Argument, ArgumentCollection, Token
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from cyclopts.core import App
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _transform(s: str) -> str:
|
| 13 |
+
return s.upper().replace("-", "_").replace(".", "_").lstrip("_")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@define
|
| 17 |
+
class Env:
|
| 18 |
+
prefix: str = ""
|
| 19 |
+
source: str = field(default="env", kw_only=True)
|
| 20 |
+
command: bool = field(default=True, kw_only=True)
|
| 21 |
+
show: bool = field(default=True, kw_only=True)
|
| 22 |
+
|
| 23 |
+
def _prefix(self, commands: tuple[str, ...]) -> str:
|
| 24 |
+
prefix = self.prefix
|
| 25 |
+
if self.command and commands:
|
| 26 |
+
prefix += "_".join(x.upper() for x in commands) + "_"
|
| 27 |
+
|
| 28 |
+
return prefix
|
| 29 |
+
|
| 30 |
+
def _convert_argument(self, commands: tuple[str, ...], argument: Argument) -> str:
|
| 31 |
+
"""For generating environment variable names for the help-page.
|
| 32 |
+
|
| 33 |
+
Internal Cyclopts use only.
|
| 34 |
+
"""
|
| 35 |
+
return self._prefix(commands) + _transform(argument.name)
|
| 36 |
+
|
| 37 |
+
def __call__(self, app: "App", commands: tuple[str, ...], arguments: ArgumentCollection):
|
| 38 |
+
added_tokens = set()
|
| 39 |
+
|
| 40 |
+
prefix = self._prefix(commands)
|
| 41 |
+
|
| 42 |
+
candidate_env_keys = [x for x in os.environ if x.startswith(prefix)]
|
| 43 |
+
candidate_env_keys.sort()
|
| 44 |
+
delimiter = "_"
|
| 45 |
+
for candidate_env_key in candidate_env_keys:
|
| 46 |
+
try:
|
| 47 |
+
argument, remaining_keys, _ = arguments.match(
|
| 48 |
+
candidate_env_key[len(prefix) :],
|
| 49 |
+
transform=_transform,
|
| 50 |
+
delimiter=delimiter,
|
| 51 |
+
)
|
| 52 |
+
except ValueError:
|
| 53 |
+
continue
|
| 54 |
+
if set(argument.tokens) - added_tokens:
|
| 55 |
+
# Skip if there are any tokens from another source.
|
| 56 |
+
continue
|
| 57 |
+
|
| 58 |
+
# There's inherently an ambiguity because we use "_" as the key-delimiter.
|
| 59 |
+
# However, we can somewhat resolve this ambiguity by checking if the argument
|
| 60 |
+
# accepts subkeys. If there are no children arguments, then just re-combine the
|
| 61 |
+
# remaining_keys.
|
| 62 |
+
if not argument.children and remaining_keys:
|
| 63 |
+
remaining_keys = (delimiter.join(remaining_keys),)
|
| 64 |
+
|
| 65 |
+
remaining_keys = tuple(x.lower() for x in remaining_keys)
|
| 66 |
+
for i, value in enumerate(argument.env_var_split(os.environ[candidate_env_key])):
|
| 67 |
+
token = Token(keyword=candidate_env_key, value=value, source=self.source, index=i, keys=remaining_keys)
|
| 68 |
+
argument.append(token)
|
| 69 |
+
added_tokens.add(token)
|
.venv/lib/python3.10/site-packages/cyclopts/config/_json.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from cyclopts.config._common import ConfigFromFile
|
| 6 |
+
from cyclopts.exceptions import CoercionError
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Json(ConfigFromFile):
|
| 10 |
+
def _load_config(self, path: Path) -> dict[str, Any]:
|
| 11 |
+
with path.open() as f:
|
| 12 |
+
try:
|
| 13 |
+
return json.load(f)
|
| 14 |
+
except json.JSONDecodeError as e:
|
| 15 |
+
raise CoercionError from e
|
.venv/lib/python3.10/site-packages/cyclopts/config/_toml.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from cyclopts.config._common import ConfigFromFile
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Toml(ConfigFromFile):
|
| 8 |
+
def _load_config(self, path: Path) -> dict[str, Any]:
|
| 9 |
+
try:
|
| 10 |
+
# Attempt to use builtin >=python3.11
|
| 11 |
+
import tomllib # pyright: ignore[reportMissingImports]
|
| 12 |
+
except ImportError:
|
| 13 |
+
# Fallback to most popular pypi toml package.
|
| 14 |
+
import tomli as tomllib # pyright: ignore[reportMissingImports]
|
| 15 |
+
|
| 16 |
+
with path.open("rb") as f:
|
| 17 |
+
return tomllib.load(f)
|
.venv/lib/python3.10/site-packages/cyclopts/config/_yaml.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from cyclopts.config._common import ConfigFromFile
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Yaml(ConfigFromFile):
|
| 8 |
+
def _load_config(self, path: Path) -> dict[str, Any]:
|
| 9 |
+
from yaml import safe_load # pyright: ignore[reportMissingImports]
|
| 10 |
+
|
| 11 |
+
with path.open() as f:
|
| 12 |
+
return safe_load(f)
|
.venv/lib/python3.10/site-packages/cyclopts/core.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.10/site-packages/cyclopts/docs/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Documentation generation for cyclopts CLI applications."""
|
| 2 |
+
|
| 3 |
+
from cyclopts.docs.html import generate_html_docs
|
| 4 |
+
from cyclopts.docs.markdown import generate_markdown_docs
|
| 5 |
+
from cyclopts.docs.rst import generate_rst_docs
|
| 6 |
+
from cyclopts.docs.types import (
|
| 7 |
+
FORMAT_ALIASES,
|
| 8 |
+
CanonicalDocFormat,
|
| 9 |
+
DocFormat,
|
| 10 |
+
normalize_format,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
"generate_html_docs",
|
| 15 |
+
"generate_markdown_docs",
|
| 16 |
+
"generate_rst_docs",
|
| 17 |
+
"DocFormat",
|
| 18 |
+
"CanonicalDocFormat",
|
| 19 |
+
"FORMAT_ALIASES",
|
| 20 |
+
"normalize_format",
|
| 21 |
+
]
|
.venv/lib/python3.10/site-packages/cyclopts/docs/base.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base utilities for documentation generation."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from typing import TYPE_CHECKING, Any
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from cyclopts.core import App
|
| 9 |
+
from cyclopts.help import HelpPanel
|
| 10 |
+
|
| 11 |
+
from cyclopts.command_spec import CommandSpec
|
| 12 |
+
from cyclopts.help import format_doc, format_usage
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def should_show_usage(app: "App") -> bool:
|
| 16 |
+
"""Determine if usage should be shown for an app.
|
| 17 |
+
|
| 18 |
+
Root apps always show usage (even without default_command, showing "app COMMAND").
|
| 19 |
+
Subcommands only show usage if they have a default_command.
|
| 20 |
+
This skips usage for command groups that can't be invoked directly.
|
| 21 |
+
|
| 22 |
+
The determination is made by checking the app_stack depth:
|
| 23 |
+
- Stack length of 1 means root app (just the initial frame)
|
| 24 |
+
- Stack length > 1 means we're in a subcommand context (frames were pushed)
|
| 25 |
+
|
| 26 |
+
Parameters
|
| 27 |
+
----------
|
| 28 |
+
app : App
|
| 29 |
+
The App instance to check.
|
| 30 |
+
|
| 31 |
+
Returns
|
| 32 |
+
-------
|
| 33 |
+
bool
|
| 34 |
+
True if usage should be shown.
|
| 35 |
+
"""
|
| 36 |
+
# Check if we're in a subcommand context by examining the stack depth
|
| 37 |
+
is_root = len(app.app_stack.stack) == 1
|
| 38 |
+
|
| 39 |
+
if is_root:
|
| 40 |
+
# Root app: always show usage
|
| 41 |
+
return True
|
| 42 |
+
else:
|
| 43 |
+
# Subcommand: only show if it has a default_command
|
| 44 |
+
return app.default_command is not None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def should_show_commands_list(app: "App") -> bool:
|
| 48 |
+
"""Determine if commands list should be shown for an app.
|
| 49 |
+
|
| 50 |
+
Only show commands list for apps with a default_command.
|
| 51 |
+
Command groups (apps without default_command) skip the list
|
| 52 |
+
since their commands will be documented recursively anyway.
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
----------
|
| 56 |
+
app : App
|
| 57 |
+
The App instance to check.
|
| 58 |
+
|
| 59 |
+
Returns
|
| 60 |
+
-------
|
| 61 |
+
bool
|
| 62 |
+
True if commands list should be shown.
|
| 63 |
+
"""
|
| 64 |
+
return app.default_command is not None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _is_builtin_flag(app: "App", name: str) -> bool:
|
| 68 |
+
"""Check if a flag name is a built-in help or version flag.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
app : App
|
| 73 |
+
The App instance to check against.
|
| 74 |
+
name : str
|
| 75 |
+
The flag name to check.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
bool
|
| 80 |
+
True if this is a built-in help or version flag.
|
| 81 |
+
"""
|
| 82 |
+
help_flags = set(app.app_stack.resolve("help_flags", fallback=()))
|
| 83 |
+
version_flags = set(app.app_stack.resolve("version_flags", fallback=()))
|
| 84 |
+
builtin_flags = help_flags | version_flags
|
| 85 |
+
return name in builtin_flags
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def is_all_builtin_flags(app: "App", names: Sequence[str]) -> bool:
|
| 89 |
+
"""Check if all names in the sequence are builtin help or version flags.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
app : App
|
| 94 |
+
The App instance to check against.
|
| 95 |
+
names : Sequence[str]
|
| 96 |
+
Sequence of flag names to check.
|
| 97 |
+
|
| 98 |
+
Returns
|
| 99 |
+
-------
|
| 100 |
+
bool
|
| 101 |
+
True if all names are builtin flags.
|
| 102 |
+
"""
|
| 103 |
+
if not names:
|
| 104 |
+
return False
|
| 105 |
+
return all(_is_builtin_flag(app, name) for name in names)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def normalize_command_filters(
|
| 109 |
+
commands_filter: list[str] | None = None,
|
| 110 |
+
exclude_commands: list[str] | None = None,
|
| 111 |
+
) -> tuple[set[str] | None, set[str] | None]:
|
| 112 |
+
"""Normalize command filter lists by converting underscores to dashes.
|
| 113 |
+
|
| 114 |
+
Parameters
|
| 115 |
+
----------
|
| 116 |
+
commands_filter : list[str] | None
|
| 117 |
+
List of commands to include.
|
| 118 |
+
exclude_commands : list[str] | None
|
| 119 |
+
List of commands to exclude.
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
-------
|
| 123 |
+
tuple[set[str] | None, set[str] | None]
|
| 124 |
+
Normalized include and exclude sets for O(1) lookup.
|
| 125 |
+
"""
|
| 126 |
+
normalized_include = None
|
| 127 |
+
if commands_filter is not None:
|
| 128 |
+
normalized_include = {cmd.replace("_", "-") for cmd in commands_filter}
|
| 129 |
+
|
| 130 |
+
normalized_exclude = None
|
| 131 |
+
if exclude_commands:
|
| 132 |
+
normalized_exclude = {cmd.replace("_", "-") for cmd in exclude_commands}
|
| 133 |
+
|
| 134 |
+
return normalized_include, normalized_exclude
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def should_include_command(
|
| 138 |
+
name: str,
|
| 139 |
+
parent_path: list[str],
|
| 140 |
+
normalized_commands_filter: set[str] | None,
|
| 141 |
+
normalized_exclude_commands: set[str] | None,
|
| 142 |
+
subapp: "App",
|
| 143 |
+
) -> bool:
|
| 144 |
+
"""Determine if a command should be included based on filters.
|
| 145 |
+
|
| 146 |
+
Parameters
|
| 147 |
+
----------
|
| 148 |
+
name : str
|
| 149 |
+
The command name.
|
| 150 |
+
parent_path : list[str]
|
| 151 |
+
Path to parent commands.
|
| 152 |
+
normalized_commands_filter : set[str] | None
|
| 153 |
+
Set of commands to include (already normalized).
|
| 154 |
+
normalized_exclude_commands : set[str] | None
|
| 155 |
+
Set of commands to exclude (already normalized).
|
| 156 |
+
subapp : App
|
| 157 |
+
The subcommand App instance.
|
| 158 |
+
|
| 159 |
+
Returns
|
| 160 |
+
-------
|
| 161 |
+
bool
|
| 162 |
+
True if the command should be included, False otherwise.
|
| 163 |
+
"""
|
| 164 |
+
full_path = ".".join(parent_path + [name]) if parent_path else name
|
| 165 |
+
|
| 166 |
+
if normalized_exclude_commands:
|
| 167 |
+
if name in normalized_exclude_commands or full_path in normalized_exclude_commands:
|
| 168 |
+
return False
|
| 169 |
+
for i in range(len(parent_path)):
|
| 170 |
+
parent_segment = ".".join(parent_path[: i + 1])
|
| 171 |
+
if parent_segment in normalized_exclude_commands:
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
if normalized_commands_filter is not None:
|
| 175 |
+
if name in normalized_commands_filter or full_path in normalized_commands_filter:
|
| 176 |
+
return True
|
| 177 |
+
|
| 178 |
+
for i in range(len(parent_path)):
|
| 179 |
+
parent_segment = ".".join(parent_path[: i + 1])
|
| 180 |
+
if parent_segment in normalized_commands_filter:
|
| 181 |
+
return True
|
| 182 |
+
|
| 183 |
+
if hasattr(subapp, "_commands") and subapp._commands:
|
| 184 |
+
for filter_cmd in normalized_commands_filter:
|
| 185 |
+
if filter_cmd.startswith(full_path + "."):
|
| 186 |
+
return True
|
| 187 |
+
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
return True
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def adjust_filters_for_subcommand(
|
| 194 |
+
name: str,
|
| 195 |
+
normalized_commands_filter: set[str] | None,
|
| 196 |
+
normalized_exclude_commands: set[str] | None,
|
| 197 |
+
) -> tuple[list[str] | None, list[str] | None]:
|
| 198 |
+
"""Adjust filter lists for subcommand context.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
name : str
|
| 203 |
+
The current command name.
|
| 204 |
+
normalized_commands_filter : set[str] | None
|
| 205 |
+
Set of commands to include (already normalized).
|
| 206 |
+
normalized_exclude_commands : set[str] | None
|
| 207 |
+
Set of commands to exclude (already normalized).
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
-------
|
| 211 |
+
tuple[list[str] | None, list[str] | None]
|
| 212 |
+
Adjusted commands_filter and exclude_commands lists (denormalized).
|
| 213 |
+
"""
|
| 214 |
+
sub_commands_filter = None
|
| 215 |
+
if normalized_commands_filter is not None:
|
| 216 |
+
sub_commands_filter = []
|
| 217 |
+
for filter_cmd in normalized_commands_filter:
|
| 218 |
+
if filter_cmd.startswith(name + "."):
|
| 219 |
+
sub_filter = filter_cmd[len(name) + 1 :]
|
| 220 |
+
sub_commands_filter.append(sub_filter.replace("-", "_"))
|
| 221 |
+
elif filter_cmd == name:
|
| 222 |
+
sub_commands_filter = None
|
| 223 |
+
break
|
| 224 |
+
|
| 225 |
+
if sub_commands_filter is not None and not sub_commands_filter:
|
| 226 |
+
sub_commands_filter = []
|
| 227 |
+
|
| 228 |
+
sub_exclude_commands = None
|
| 229 |
+
if normalized_exclude_commands:
|
| 230 |
+
sub_exclude_commands = []
|
| 231 |
+
for exclude_cmd in normalized_exclude_commands:
|
| 232 |
+
if exclude_cmd.startswith(name + "."):
|
| 233 |
+
sub_exclude = exclude_cmd[len(name) + 1 :]
|
| 234 |
+
sub_exclude_commands.append(sub_exclude.replace("-", "_"))
|
| 235 |
+
else:
|
| 236 |
+
sub_exclude_commands.append(exclude_cmd.replace("-", "_"))
|
| 237 |
+
|
| 238 |
+
return sub_commands_filter, sub_exclude_commands
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def get_app_info(app: "App", command_chain: list[str] | None = None) -> tuple[str, str, str]:
|
| 242 |
+
"""Get app name, full command path, and title.
|
| 243 |
+
|
| 244 |
+
Parameters
|
| 245 |
+
----------
|
| 246 |
+
app : App
|
| 247 |
+
The cyclopts App instance.
|
| 248 |
+
command_chain : Optional[List[str]]
|
| 249 |
+
Chain of parent commands leading to this app.
|
| 250 |
+
|
| 251 |
+
Returns
|
| 252 |
+
-------
|
| 253 |
+
Tuple[str, str, str]
|
| 254 |
+
(app_name, full_command, title)
|
| 255 |
+
"""
|
| 256 |
+
if not command_chain:
|
| 257 |
+
app_name = app.name[0]
|
| 258 |
+
full_command = app_name
|
| 259 |
+
title = app_name
|
| 260 |
+
else:
|
| 261 |
+
app_name = command_chain[0]
|
| 262 |
+
full_command = " ".join(command_chain)
|
| 263 |
+
title = full_command
|
| 264 |
+
|
| 265 |
+
return app_name, full_command, title
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def build_command_chain(command_chain: list[str] | None, command_name: str, app_name: str) -> list[str]:
|
| 269 |
+
"""Build command chain for a subcommand.
|
| 270 |
+
|
| 271 |
+
Parameters
|
| 272 |
+
----------
|
| 273 |
+
command_chain : Optional[List[str]]
|
| 274 |
+
Current command chain.
|
| 275 |
+
command_name : str
|
| 276 |
+
Name of the subcommand.
|
| 277 |
+
app_name : str
|
| 278 |
+
Name of the root app.
|
| 279 |
+
|
| 280 |
+
Returns
|
| 281 |
+
-------
|
| 282 |
+
List[str]
|
| 283 |
+
Updated command chain.
|
| 284 |
+
"""
|
| 285 |
+
if command_chain:
|
| 286 |
+
return command_chain + [command_name]
|
| 287 |
+
else:
|
| 288 |
+
return [app_name, command_name]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def apply_usage_name(command_chain: list[str], usage_name: str | None) -> list[str]:
|
| 292 |
+
"""Return a display command chain with the root replaced by ``usage_name``.
|
| 293 |
+
|
| 294 |
+
When ``usage_name`` is ``None``, returns ``command_chain`` unchanged so callers
|
| 295 |
+
can use this helper unconditionally. When ``usage_name`` is ``""``, the root
|
| 296 |
+
token is dropped rather than substituted, so downstream formatters never see
|
| 297 |
+
an empty element (which would render as stray leading/internal whitespace).
|
| 298 |
+
When the chain is empty and ``usage_name`` is a non-empty string, returns a
|
| 299 |
+
single-element list containing ``usage_name``.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
command_chain : list[str]
|
| 304 |
+
The logical command chain (root app name first).
|
| 305 |
+
usage_name : str | None
|
| 306 |
+
Replacement for the chain's root element used in Usage: lines only.
|
| 307 |
+
An empty string drops the root token entirely.
|
| 308 |
+
|
| 309 |
+
Returns
|
| 310 |
+
-------
|
| 311 |
+
list[str]
|
| 312 |
+
A new list with the root replaced/dropped, or the original chain when
|
| 313 |
+
``usage_name`` is ``None``.
|
| 314 |
+
"""
|
| 315 |
+
if usage_name is None:
|
| 316 |
+
return command_chain
|
| 317 |
+
if usage_name == "":
|
| 318 |
+
return command_chain[1:]
|
| 319 |
+
if not command_chain:
|
| 320 |
+
return [usage_name]
|
| 321 |
+
return [usage_name, *command_chain[1:]]
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def generate_anchor(command_path: str) -> str:
|
| 325 |
+
"""Generate a URL-friendly anchor from a command path.
|
| 326 |
+
|
| 327 |
+
Converts spaces to hyphens and lowercases the string to match
|
| 328 |
+
how markdown/HTML processors generate anchors from headings.
|
| 329 |
+
Strips leading dashes to match markdown processor behavior.
|
| 330 |
+
|
| 331 |
+
Parameters
|
| 332 |
+
----------
|
| 333 |
+
command_path : str
|
| 334 |
+
Full command path (e.g., "myapp files cp").
|
| 335 |
+
|
| 336 |
+
Returns
|
| 337 |
+
-------
|
| 338 |
+
str
|
| 339 |
+
Anchor string (e.g., "myapp-files-cp").
|
| 340 |
+
|
| 341 |
+
Examples
|
| 342 |
+
--------
|
| 343 |
+
>>> generate_anchor("myapp files cp")
|
| 344 |
+
'myapp-files-cp'
|
| 345 |
+
>>> generate_anchor("myapp --install-completion")
|
| 346 |
+
'myapp-install-completion'
|
| 347 |
+
"""
|
| 348 |
+
anchor = command_path.lower().replace(" ", "-")
|
| 349 |
+
# Collapse consecutive dashes to single dash (markdown processors do this)
|
| 350 |
+
anchor = re.sub(r"-+", "-", anchor)
|
| 351 |
+
return anchor
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def should_skip_command(command_name: str, subapp: "App", parent_app: "App", include_hidden: bool) -> bool:
|
| 355 |
+
"""Check if a command should be skipped.
|
| 356 |
+
|
| 357 |
+
Parameters
|
| 358 |
+
----------
|
| 359 |
+
command_name : str
|
| 360 |
+
Name of the command.
|
| 361 |
+
subapp : App
|
| 362 |
+
The subcommand App instance.
|
| 363 |
+
parent_app : App
|
| 364 |
+
The parent App instance.
|
| 365 |
+
include_hidden : bool
|
| 366 |
+
Whether to include hidden commands.
|
| 367 |
+
|
| 368 |
+
Returns
|
| 369 |
+
-------
|
| 370 |
+
bool
|
| 371 |
+
True if command should be skipped.
|
| 372 |
+
"""
|
| 373 |
+
if _is_builtin_flag(parent_app, command_name):
|
| 374 |
+
return True
|
| 375 |
+
|
| 376 |
+
if not isinstance(subapp, type(parent_app)):
|
| 377 |
+
return True
|
| 378 |
+
|
| 379 |
+
if not include_hidden and not subapp.show:
|
| 380 |
+
return True
|
| 381 |
+
|
| 382 |
+
return False
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def filter_help_entries(app: "App", panel: "HelpPanel", include_hidden: bool) -> list[Any]:
|
| 386 |
+
"""Filter help panel entries based on visibility settings.
|
| 387 |
+
|
| 388 |
+
Parameters
|
| 389 |
+
----------
|
| 390 |
+
app : App
|
| 391 |
+
The App instance to check against.
|
| 392 |
+
panel : HelpPanel
|
| 393 |
+
The help panel to filter.
|
| 394 |
+
include_hidden : bool
|
| 395 |
+
Whether to include hidden entries.
|
| 396 |
+
|
| 397 |
+
Returns
|
| 398 |
+
-------
|
| 399 |
+
List[Any]
|
| 400 |
+
Filtered panel entries.
|
| 401 |
+
"""
|
| 402 |
+
if include_hidden:
|
| 403 |
+
return panel.entries
|
| 404 |
+
|
| 405 |
+
return [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))]
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def extract_description(app: "App", help_format: str) -> Any | None:
|
| 409 |
+
"""Extract app description.
|
| 410 |
+
|
| 411 |
+
Parameters
|
| 412 |
+
----------
|
| 413 |
+
app : App
|
| 414 |
+
The App instance.
|
| 415 |
+
help_format : str
|
| 416 |
+
Help format type.
|
| 417 |
+
|
| 418 |
+
Returns
|
| 419 |
+
-------
|
| 420 |
+
Optional[Any]
|
| 421 |
+
The extracted description object, or None.
|
| 422 |
+
"""
|
| 423 |
+
description = format_doc(app, help_format)
|
| 424 |
+
return description
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def extract_usage(app: "App") -> Any | None:
|
| 428 |
+
"""Extract usage string.
|
| 429 |
+
|
| 430 |
+
Parameters
|
| 431 |
+
----------
|
| 432 |
+
app : App
|
| 433 |
+
The App instance.
|
| 434 |
+
|
| 435 |
+
Returns
|
| 436 |
+
-------
|
| 437 |
+
Optional[Any]
|
| 438 |
+
The extracted usage object, or None.
|
| 439 |
+
"""
|
| 440 |
+
if app.usage is not None:
|
| 441 |
+
return app.usage if app.usage else None
|
| 442 |
+
|
| 443 |
+
usage = format_usage(app, [])
|
| 444 |
+
return usage
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def format_usage_line(usage_text: str, command_chain: list[str], prefix: str = "") -> str:
|
| 448 |
+
"""Format usage line with proper command path.
|
| 449 |
+
|
| 450 |
+
Parameters
|
| 451 |
+
----------
|
| 452 |
+
usage_text : str
|
| 453 |
+
Raw usage text.
|
| 454 |
+
command_chain : List[str]
|
| 455 |
+
Command chain for the app.
|
| 456 |
+
prefix : str
|
| 457 |
+
Optional prefix for the usage line (e.g., "$").
|
| 458 |
+
|
| 459 |
+
Returns
|
| 460 |
+
-------
|
| 461 |
+
str
|
| 462 |
+
Formatted usage line.
|
| 463 |
+
"""
|
| 464 |
+
if not usage_text:
|
| 465 |
+
return ""
|
| 466 |
+
|
| 467 |
+
if "Usage:" in usage_text:
|
| 468 |
+
usage_text = usage_text.replace("Usage:", "").strip()
|
| 469 |
+
|
| 470 |
+
full_command = " ".join(command_chain) if command_chain else ""
|
| 471 |
+
|
| 472 |
+
parts = usage_text.split(None, 1)
|
| 473 |
+
if len(parts) > 1 and command_chain:
|
| 474 |
+
usage_line = f"{prefix} {full_command} {parts[1]}" if prefix else f"{full_command} {parts[1]}"
|
| 475 |
+
elif command_chain:
|
| 476 |
+
usage_line = f"{prefix} {full_command}" if prefix else full_command
|
| 477 |
+
else:
|
| 478 |
+
usage_line = f"{prefix} {usage_text}" if prefix else usage_text
|
| 479 |
+
|
| 480 |
+
return usage_line.strip()
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def iterate_commands(app: "App", include_hidden: bool = False, resolve_lazy: bool = True):
|
| 484 |
+
"""Iterate through app commands, yielding valid resolved subapps.
|
| 485 |
+
|
| 486 |
+
Automatically resolves CommandSpec instances to App instances.
|
| 487 |
+
Each unique subapp is yielded only once (first occurrence wins).
|
| 488 |
+
|
| 489 |
+
Parameters
|
| 490 |
+
----------
|
| 491 |
+
app : App
|
| 492 |
+
The App instance.
|
| 493 |
+
include_hidden : bool
|
| 494 |
+
Whether to include hidden commands.
|
| 495 |
+
resolve_lazy : bool
|
| 496 |
+
If ``True`` (default), resolve lazy commands (import their modules) to
|
| 497 |
+
include them in the output. If ``False``, skip unresolved lazy commands.
|
| 498 |
+
Set to ``True`` when generating static artifacts that need all commands,
|
| 499 |
+
such as documentation or shell completion scripts.
|
| 500 |
+
|
| 501 |
+
Yields
|
| 502 |
+
------
|
| 503 |
+
Tuple[str, App]
|
| 504 |
+
(command_name, resolved_subapp) for each valid command.
|
| 505 |
+
"""
|
| 506 |
+
if not app._commands:
|
| 507 |
+
return
|
| 508 |
+
|
| 509 |
+
seen: set[int] = set()
|
| 510 |
+
|
| 511 |
+
for name, app_or_spec in app._commands.items():
|
| 512 |
+
if _is_builtin_flag(app, name):
|
| 513 |
+
continue
|
| 514 |
+
|
| 515 |
+
if isinstance(app_or_spec, CommandSpec):
|
| 516 |
+
if not app_or_spec.is_resolved and not resolve_lazy:
|
| 517 |
+
continue
|
| 518 |
+
subapp = app_or_spec.resolve(app)
|
| 519 |
+
else:
|
| 520 |
+
subapp = app_or_spec
|
| 521 |
+
|
| 522 |
+
if not isinstance(subapp, type(app)):
|
| 523 |
+
continue
|
| 524 |
+
|
| 525 |
+
if not include_hidden and not subapp.show:
|
| 526 |
+
continue
|
| 527 |
+
|
| 528 |
+
# Skip if we've already yielded this app (alias)
|
| 529 |
+
app_id = id(subapp)
|
| 530 |
+
if app_id in seen:
|
| 531 |
+
continue
|
| 532 |
+
seen.add(app_id)
|
| 533 |
+
|
| 534 |
+
yield name, subapp
|
.venv/lib/python3.10/site-packages/cyclopts/docs/html.py
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTML documentation generation for cyclopts apps."""
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from cyclopts._markup import escape_html, extract_text
|
| 6 |
+
from cyclopts.docs.base import (
|
| 7 |
+
apply_usage_name,
|
| 8 |
+
build_command_chain,
|
| 9 |
+
extract_description,
|
| 10 |
+
extract_usage,
|
| 11 |
+
filter_help_entries,
|
| 12 |
+
format_usage_line,
|
| 13 |
+
generate_anchor,
|
| 14 |
+
iterate_commands,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from cyclopts.core import App
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _generate_html_toc(
|
| 22 |
+
lines: list[str],
|
| 23 |
+
app: "App",
|
| 24 |
+
include_hidden: bool,
|
| 25 |
+
app_name: str,
|
| 26 |
+
prefix: str,
|
| 27 |
+
depth: int = 0,
|
| 28 |
+
) -> None:
|
| 29 |
+
"""Recursively generate HTML table of contents."""
|
| 30 |
+
if not app._commands:
|
| 31 |
+
return
|
| 32 |
+
|
| 33 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 34 |
+
display_name = f"{prefix}{name}" if prefix else name
|
| 35 |
+
full_path = f"{app_name}-{display_name.replace(' ', '-')}".lower()
|
| 36 |
+
|
| 37 |
+
indent = " " * (depth + 1)
|
| 38 |
+
lines.append(f'{indent}<li><a href="#{full_path}"><code>{name}</code></a>')
|
| 39 |
+
|
| 40 |
+
if subapp._commands:
|
| 41 |
+
lines.append(f"{indent} <ul>")
|
| 42 |
+
_generate_html_toc(lines, subapp, include_hidden, app_name, f"{display_name} ", depth + 1)
|
| 43 |
+
lines.append(f"{indent} </ul>")
|
| 44 |
+
|
| 45 |
+
lines.append(f"{indent}</li>")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# CSS styles embedded as a string - clean, modern design
|
| 49 |
+
DEFAULT_CSS = """
|
| 50 |
+
:root {
|
| 51 |
+
--bg-color: #ffffff;
|
| 52 |
+
--text-color: #333333;
|
| 53 |
+
--border-color: #e0e0e0;
|
| 54 |
+
--code-bg: #f5f5f5;
|
| 55 |
+
--link-color: #0066cc;
|
| 56 |
+
--header-bg: #f8f9fa;
|
| 57 |
+
--required-color: #d73027;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
* {
|
| 61 |
+
box-sizing: border-box;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
body {
|
| 65 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
| 66 |
+
line-height: 1.6;
|
| 67 |
+
color: var(--text-color);
|
| 68 |
+
background: var(--bg-color);
|
| 69 |
+
max-width: 1200px;
|
| 70 |
+
margin: 0 auto;
|
| 71 |
+
padding: 20px;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
h1, h2, h3, h4, h5, h6 {
|
| 75 |
+
margin-top: 24px;
|
| 76 |
+
margin-bottom: 16px;
|
| 77 |
+
font-weight: 600;
|
| 78 |
+
line-height: 1.25;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
h1 { font-size: 2em; border-bottom: 2px solid var(--border-color); padding-bottom: 0.3em; }
|
| 82 |
+
h2 { font-size: 1.5em; border-bottom: 1px solid var(--border-color); padding-bottom: 0.3em; }
|
| 83 |
+
h3 { font-size: 1.25em; }
|
| 84 |
+
h4 { font-size: 1em; }
|
| 85 |
+
|
| 86 |
+
code {
|
| 87 |
+
background: var(--code-bg);
|
| 88 |
+
padding: 2px 6px;
|
| 89 |
+
border-radius: 3px;
|
| 90 |
+
font-family: 'Courier New', Consolas, monospace;
|
| 91 |
+
font-size: 0.9em;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
pre {
|
| 95 |
+
background: var(--code-bg);
|
| 96 |
+
padding: 16px;
|
| 97 |
+
border-radius: 6px;
|
| 98 |
+
overflow-x: auto;
|
| 99 |
+
font-family: 'Courier New', Consolas, monospace;
|
| 100 |
+
font-size: 0.9em;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
pre code {
|
| 104 |
+
background: none;
|
| 105 |
+
padding: 0;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
.usage-block {
|
| 109 |
+
margin: 16px 0;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
.usage {
|
| 113 |
+
background: #f8f9fa;
|
| 114 |
+
border-left: 4px solid #0066cc;
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
.description, .app-description, .command-description {
|
| 118 |
+
margin: 16px 0;
|
| 119 |
+
color: var(--text-color);
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
.panel-description {
|
| 123 |
+
margin: 12px 0;
|
| 124 |
+
color: #666;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
.help-panel {
|
| 128 |
+
margin: 24px 0;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
/* List styles for commands and parameters */
|
| 132 |
+
.commands-list, .parameters-list {
|
| 133 |
+
list-style: none;
|
| 134 |
+
padding-left: 0;
|
| 135 |
+
margin: 16px 0;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
.commands-list li, .parameters-list li {
|
| 139 |
+
padding: 8px 0;
|
| 140 |
+
border-bottom: 1px solid var(--border-color);
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
.commands-list li:last-child, .parameters-list li:last-child {
|
| 144 |
+
border-bottom: none;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
.commands-list code, .parameters-list code {
|
| 148 |
+
font-weight: 600;
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
/* Metadata styling */
|
| 152 |
+
.parameter-metadata {
|
| 153 |
+
display: inline-flex;
|
| 154 |
+
gap: 8px;
|
| 155 |
+
margin-left: 8px;
|
| 156 |
+
flex-wrap: wrap;
|
| 157 |
+
align-items: center;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
.metadata-item {
|
| 161 |
+
display: inline-block;
|
| 162 |
+
padding: 2px 8px;
|
| 163 |
+
font-size: 0.85em;
|
| 164 |
+
border-radius: 4px;
|
| 165 |
+
background: var(--code-bg);
|
| 166 |
+
border: 1px solid var(--border-color);
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
.metadata-required {
|
| 170 |
+
background: #fee;
|
| 171 |
+
border-color: #fcc;
|
| 172 |
+
color: #c00;
|
| 173 |
+
font-weight: 600;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
.metadata-default {
|
| 177 |
+
background: #f0f8ff;
|
| 178 |
+
border-color: #d0e8ff;
|
| 179 |
+
color: #0066cc;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
.metadata-env {
|
| 183 |
+
background: #f0fff0;
|
| 184 |
+
border-color: #d0ffd0;
|
| 185 |
+
color: #080;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
.metadata-choices {
|
| 189 |
+
background: #fffaf0;
|
| 190 |
+
border-color: #ffd0a0;
|
| 191 |
+
color: #840;
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
.metadata-label {
|
| 195 |
+
font-weight: 600;
|
| 196 |
+
opacity: 0.8;
|
| 197 |
+
text-transform: uppercase;
|
| 198 |
+
font-size: 0.9em;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/* Table of Contents */
|
| 202 |
+
.table-of-contents {
|
| 203 |
+
background: var(--header-bg);
|
| 204 |
+
border-radius: 6px;
|
| 205 |
+
padding: 16px;
|
| 206 |
+
margin: 24px 0;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
.table-of-contents h2 {
|
| 210 |
+
margin-top: 0;
|
| 211 |
+
border-bottom: none;
|
| 212 |
+
padding-bottom: 0;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
.table-of-contents ul {
|
| 216 |
+
margin: 8px 0;
|
| 217 |
+
padding-left: 24px;
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
.table-of-contents li {
|
| 221 |
+
margin: 4px 0;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
.table-of-contents a {
|
| 225 |
+
color: var(--link-color);
|
| 226 |
+
text-decoration: none;
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
.table-of-contents a:hover {
|
| 230 |
+
text-decoration: underline;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
/* General link styles */
|
| 234 |
+
a {
|
| 235 |
+
color: var(--link-color);
|
| 236 |
+
text-decoration: none;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
a:hover {
|
| 240 |
+
text-decoration: underline;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
.commands-list a code {
|
| 244 |
+
color: var(--link-color);
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
/* Back to top link */
|
| 248 |
+
.back-to-top {
|
| 249 |
+
display: inline-block;
|
| 250 |
+
margin-top: 8px;
|
| 251 |
+
font-size: 0.9em;
|
| 252 |
+
opacity: 0.7;
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
.back-to-top:hover {
|
| 256 |
+
opacity: 1;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
/* Responsive design */
|
| 260 |
+
@media (max-width: 768px) {
|
| 261 |
+
body {
|
| 262 |
+
padding: 10px;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
.commands-list, .parameters-list {
|
| 266 |
+
font-size: 0.9em;
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
/* Dark mode support */
|
| 271 |
+
@media (prefers-color-scheme: dark) {
|
| 272 |
+
:root {
|
| 273 |
+
--bg-color: #1e1e1e;
|
| 274 |
+
--text-color: #e0e0e0;
|
| 275 |
+
--border-color: #444;
|
| 276 |
+
--code-bg: #2d2d2d;
|
| 277 |
+
--link-color: #66b3ff;
|
| 278 |
+
--header-bg: #2d2d2d;
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
.usage {
|
| 282 |
+
background: #2d2d2d;
|
| 283 |
+
border-left-color: #66b3ff;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
.table-of-contents {
|
| 287 |
+
background: #2d2d2d;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
.metadata-required {
|
| 291 |
+
background: #4a2020;
|
| 292 |
+
border-color: #6a3030;
|
| 293 |
+
color: #ff9999;
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
.metadata-default {
|
| 297 |
+
background: #20304a;
|
| 298 |
+
border-color: #304060;
|
| 299 |
+
color: #99ccff;
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
.metadata-env {
|
| 303 |
+
background: #204a20;
|
| 304 |
+
border-color: #306030;
|
| 305 |
+
color: #99ff99;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
.metadata-choices {
|
| 309 |
+
background: #4a3020;
|
| 310 |
+
border-color: #604030;
|
| 311 |
+
color: #ffcc99;
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
/* Command sections */
|
| 316 |
+
.command-section {
|
| 317 |
+
margin-top: 32px;
|
| 318 |
+
padding-top: 16px;
|
| 319 |
+
border-top: 2px solid var(--border-color);
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
.command-section:first-child {
|
| 323 |
+
border-top: none;
|
| 324 |
+
}
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def generate_html_docs(
|
| 329 |
+
app: "App",
|
| 330 |
+
recursive: bool = True,
|
| 331 |
+
include_hidden: bool = False,
|
| 332 |
+
heading_level: int = 1,
|
| 333 |
+
max_heading_level: int = 6,
|
| 334 |
+
standalone: bool = True,
|
| 335 |
+
custom_css: str | None = None,
|
| 336 |
+
command_chain: list[str] | None = None,
|
| 337 |
+
generate_toc: bool = True,
|
| 338 |
+
flatten_commands: bool = False,
|
| 339 |
+
usage_name: str | None = None,
|
| 340 |
+
) -> str:
|
| 341 |
+
"""Generate HTML documentation for a CLI application.
|
| 342 |
+
|
| 343 |
+
Parameters
|
| 344 |
+
----------
|
| 345 |
+
app : App
|
| 346 |
+
The cyclopts App instance to document.
|
| 347 |
+
recursive : bool
|
| 348 |
+
If True, generate documentation for all subcommands recursively.
|
| 349 |
+
Default is True.
|
| 350 |
+
include_hidden : bool
|
| 351 |
+
If True, include hidden commands/parameters in documentation.
|
| 352 |
+
Default is False.
|
| 353 |
+
heading_level : int
|
| 354 |
+
Starting heading level for the main application title.
|
| 355 |
+
Default is 1.
|
| 356 |
+
max_heading_level : int
|
| 357 |
+
Maximum heading level to use. Headings deeper than this will be capped
|
| 358 |
+
at this level. HTML supports levels 1-6.
|
| 359 |
+
Default is 6.
|
| 360 |
+
standalone : bool
|
| 361 |
+
If True, generate a complete HTML document with <html>, <head>, etc.
|
| 362 |
+
If False, generate only the body content. Default is True.
|
| 363 |
+
custom_css : str
|
| 364 |
+
Custom CSS to use instead of the default styles.
|
| 365 |
+
command_chain : list[str]
|
| 366 |
+
Internal parameter to track command hierarchy.
|
| 367 |
+
Default is None.
|
| 368 |
+
generate_toc : bool
|
| 369 |
+
If True, generate a table of contents for multi-command apps.
|
| 370 |
+
Default is True.
|
| 371 |
+
flatten_commands : bool
|
| 372 |
+
If True, generate all commands at the same heading level instead of nested.
|
| 373 |
+
Default is False.
|
| 374 |
+
usage_name : str | None
|
| 375 |
+
Optional replacement for the root app name in every ``Usage:`` line
|
| 376 |
+
(root and subcommands). Section headings and anchors continue to use
|
| 377 |
+
``app.name[0]``. Default is None.
|
| 378 |
+
|
| 379 |
+
Returns
|
| 380 |
+
-------
|
| 381 |
+
str
|
| 382 |
+
The generated HTML documentation.
|
| 383 |
+
"""
|
| 384 |
+
from cyclopts.help.formatters.html import HtmlFormatter
|
| 385 |
+
|
| 386 |
+
# Initialize command chain if not provided
|
| 387 |
+
if command_chain is None:
|
| 388 |
+
command_chain = []
|
| 389 |
+
|
| 390 |
+
# Build the main documentation
|
| 391 |
+
lines = []
|
| 392 |
+
|
| 393 |
+
# Only add the outer div for standalone documents or root level
|
| 394 |
+
if standalone or not command_chain:
|
| 395 |
+
lines.append('<div class="cli-documentation">')
|
| 396 |
+
|
| 397 |
+
# Determine the app name and full command path
|
| 398 |
+
if not command_chain:
|
| 399 |
+
# Root level - use app name or derive from sys.argv
|
| 400 |
+
app_name = app.name[0]
|
| 401 |
+
full_command = app_name
|
| 402 |
+
title = app_name
|
| 403 |
+
# Add title for all levels
|
| 404 |
+
effective_level = min(heading_level, max_heading_level)
|
| 405 |
+
lines.append(f'<h{effective_level} class="app-title">{title}</h{effective_level}>')
|
| 406 |
+
else:
|
| 407 |
+
# Nested command - build full path
|
| 408 |
+
app_name = command_chain[0] if command_chain else app.name[0]
|
| 409 |
+
full_command = " ".join(command_chain)
|
| 410 |
+
# Create anchor-friendly ID using shared logic
|
| 411 |
+
anchor_id = generate_anchor(full_command)
|
| 412 |
+
effective_level = min(heading_level, max_heading_level)
|
| 413 |
+
lines.append('<section class="command-section">')
|
| 414 |
+
lines.append(
|
| 415 |
+
f'<h{effective_level} id="{anchor_id}" class="command-title"><code>{escape_html(full_command)}</code></h{effective_level}>'
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Add application description
|
| 419 |
+
help_format = app.app_stack.resolve("help_format", fallback="restructuredtext")
|
| 420 |
+
description = extract_description(app, help_format)
|
| 421 |
+
if description:
|
| 422 |
+
desc_text = extract_text(description, None)
|
| 423 |
+
if desc_text:
|
| 424 |
+
lines.append(f'<div class="app-description">{escape_html(desc_text)}</div>')
|
| 425 |
+
|
| 426 |
+
# Generate table of contents if this is the root level and has commands
|
| 427 |
+
if generate_toc and not command_chain and app._commands:
|
| 428 |
+
lines.append('<div class="table-of-contents">')
|
| 429 |
+
lines.append("<h2>Table of Contents</h2>")
|
| 430 |
+
lines.append("<ul>")
|
| 431 |
+
_generate_html_toc(lines, app, include_hidden, app_name, "", 0)
|
| 432 |
+
lines.append("</ul>")
|
| 433 |
+
lines.append("</div>")
|
| 434 |
+
|
| 435 |
+
# Add usage section if not suppressed
|
| 436 |
+
usage = extract_usage(app)
|
| 437 |
+
if usage:
|
| 438 |
+
usage_level = min(heading_level + 1, max_heading_level)
|
| 439 |
+
lines.append(f"<h{usage_level}>Usage</h{usage_level}>")
|
| 440 |
+
lines.append('<div class="usage-block">')
|
| 441 |
+
if isinstance(usage, str):
|
| 442 |
+
usage_text = usage
|
| 443 |
+
else:
|
| 444 |
+
usage_text = extract_text(usage, None)
|
| 445 |
+
display_chain = apply_usage_name(command_chain, usage_name)
|
| 446 |
+
usage_text = format_usage_line(usage_text, display_chain, prefix="$")
|
| 447 |
+
lines.append(f'<pre class="usage">{escape_html(usage_text)}</pre>')
|
| 448 |
+
lines.append("</div>")
|
| 449 |
+
|
| 450 |
+
# Get help panels for the current app
|
| 451 |
+
# Use app_stack context - if caller set up parent context, it will be stacked
|
| 452 |
+
with app.app_stack([app]):
|
| 453 |
+
help_panels_with_groups = app._assemble_help_panels([], help_format)
|
| 454 |
+
|
| 455 |
+
# Render panels
|
| 456 |
+
formatter = HtmlFormatter(
|
| 457 |
+
heading_level=heading_level + 1,
|
| 458 |
+
include_hidden=include_hidden,
|
| 459 |
+
app_name=app_name,
|
| 460 |
+
command_chain=command_chain,
|
| 461 |
+
)
|
| 462 |
+
formatter.reset()
|
| 463 |
+
for group, panel in help_panels_with_groups:
|
| 464 |
+
if not include_hidden and group and not group.show:
|
| 465 |
+
continue
|
| 466 |
+
# Filter out entries based on include_hidden
|
| 467 |
+
if not include_hidden:
|
| 468 |
+
panel.entries = filter_help_entries(app, panel, include_hidden)
|
| 469 |
+
if panel.entries: # Only render non-empty panels
|
| 470 |
+
formatter(None, None, panel)
|
| 471 |
+
|
| 472 |
+
panel_docs = formatter.get_output().strip()
|
| 473 |
+
if panel_docs:
|
| 474 |
+
lines.append(panel_docs)
|
| 475 |
+
|
| 476 |
+
# Handle recursive documentation for subcommands
|
| 477 |
+
if app._commands:
|
| 478 |
+
# Iterate through registered commands
|
| 479 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 480 |
+
# Build the command chain for this subcommand
|
| 481 |
+
sub_command_chain = build_command_chain(command_chain, name, app_name)
|
| 482 |
+
|
| 483 |
+
# Determine heading level for subcommand
|
| 484 |
+
if flatten_commands:
|
| 485 |
+
sub_heading_level = heading_level
|
| 486 |
+
else:
|
| 487 |
+
sub_heading_level = heading_level + 1
|
| 488 |
+
|
| 489 |
+
# Generate subcommand documentation
|
| 490 |
+
lines.append('<section class="command-section">')
|
| 491 |
+
# Create anchor-friendly ID
|
| 492 |
+
anchor_id = (
|
| 493 |
+
f"{app_name}-{'-'.join(sub_command_chain[1:])}".lower()
|
| 494 |
+
if len(sub_command_chain) > 1
|
| 495 |
+
else f"{app_name}-{name}".lower()
|
| 496 |
+
)
|
| 497 |
+
effective_sub_level = min(sub_heading_level, max_heading_level)
|
| 498 |
+
lines.append(
|
| 499 |
+
f'<h{effective_sub_level} id="{anchor_id}" class="command-title"><code>{escape_html(" ".join(sub_command_chain))}</code></h{effective_sub_level}>'
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# Get subapp help
|
| 503 |
+
# Include parent app in the stack so default_parameter is properly inherited
|
| 504 |
+
with subapp.app_stack([app, subapp]):
|
| 505 |
+
sub_help_format = subapp.app_stack.resolve("help_format", fallback=help_format)
|
| 506 |
+
sub_description = extract_description(subapp, sub_help_format)
|
| 507 |
+
if sub_description:
|
| 508 |
+
sub_desc_text = extract_text(sub_description, None)
|
| 509 |
+
if sub_desc_text:
|
| 510 |
+
lines.append(f'<div class="command-description">{escape_html(sub_desc_text)}</div>')
|
| 511 |
+
|
| 512 |
+
# Generate usage for subcommand
|
| 513 |
+
sub_usage = extract_usage(subapp)
|
| 514 |
+
if sub_usage:
|
| 515 |
+
if flatten_commands:
|
| 516 |
+
usage_heading_level = heading_level + 1
|
| 517 |
+
else:
|
| 518 |
+
usage_heading_level = heading_level + 2
|
| 519 |
+
usage_heading_level = min(usage_heading_level, max_heading_level)
|
| 520 |
+
lines.append(f"<h{usage_heading_level}>Usage</h{usage_heading_level}>")
|
| 521 |
+
lines.append('<div class="usage-block">')
|
| 522 |
+
if isinstance(sub_usage, str):
|
| 523 |
+
sub_usage_text = sub_usage
|
| 524 |
+
else:
|
| 525 |
+
sub_usage_text = extract_text(sub_usage, None)
|
| 526 |
+
sub_display_chain = apply_usage_name(sub_command_chain, usage_name)
|
| 527 |
+
sub_usage_text = format_usage_line(sub_usage_text, sub_display_chain, prefix="$")
|
| 528 |
+
lines.append(f'<pre class="usage">{escape_html(sub_usage_text)}</pre>')
|
| 529 |
+
lines.append("</div>")
|
| 530 |
+
|
| 531 |
+
# Only show subcommand panels if we're in recursive mode
|
| 532 |
+
if recursive:
|
| 533 |
+
# Get help panels for subcommand
|
| 534 |
+
sub_panels = subapp._assemble_help_panels([], sub_help_format)
|
| 535 |
+
|
| 536 |
+
# Render subcommand panels
|
| 537 |
+
if flatten_commands:
|
| 538 |
+
panel_heading_level = heading_level + 1
|
| 539 |
+
else:
|
| 540 |
+
panel_heading_level = heading_level + 2
|
| 541 |
+
panel_heading_level = min(panel_heading_level, max_heading_level)
|
| 542 |
+
sub_formatter = HtmlFormatter(
|
| 543 |
+
heading_level=panel_heading_level,
|
| 544 |
+
include_hidden=include_hidden,
|
| 545 |
+
app_name=app_name,
|
| 546 |
+
command_chain=sub_command_chain,
|
| 547 |
+
)
|
| 548 |
+
for sub_group, sub_panel in sub_panels:
|
| 549 |
+
if not include_hidden and sub_group and not sub_group.show:
|
| 550 |
+
continue
|
| 551 |
+
if not include_hidden:
|
| 552 |
+
sub_panel.entries = filter_help_entries(subapp, sub_panel, include_hidden)
|
| 553 |
+
if sub_panel.entries:
|
| 554 |
+
sub_formatter(None, None, sub_panel)
|
| 555 |
+
|
| 556 |
+
sub_panel_docs = sub_formatter.get_output().strip()
|
| 557 |
+
if sub_panel_docs:
|
| 558 |
+
lines.append(sub_panel_docs)
|
| 559 |
+
|
| 560 |
+
# Recursively handle nested subcommands
|
| 561 |
+
if recursive and subapp._commands:
|
| 562 |
+
for nested_name, nested_app in iterate_commands(subapp, include_hidden):
|
| 563 |
+
# Build nested command chain
|
| 564 |
+
nested_chain = build_command_chain(sub_command_chain, nested_name, app_name)
|
| 565 |
+
# Determine heading level for nested commands
|
| 566 |
+
if flatten_commands:
|
| 567 |
+
nested_heading_level = heading_level
|
| 568 |
+
else:
|
| 569 |
+
nested_heading_level = heading_level + 2
|
| 570 |
+
# Set up context for nested_app, then recurse
|
| 571 |
+
# The recursive call's app_stack([app]) will stack on top of this
|
| 572 |
+
with nested_app.app_stack([subapp, nested_app]):
|
| 573 |
+
nested_docs = generate_html_docs(
|
| 574 |
+
nested_app,
|
| 575 |
+
recursive=recursive,
|
| 576 |
+
include_hidden=include_hidden,
|
| 577 |
+
heading_level=nested_heading_level,
|
| 578 |
+
max_heading_level=max_heading_level,
|
| 579 |
+
standalone=False, # Not standalone for nested
|
| 580 |
+
custom_css=None,
|
| 581 |
+
command_chain=nested_chain, # Pass the command chain
|
| 582 |
+
generate_toc=False, # No TOC for nested commands
|
| 583 |
+
flatten_commands=flatten_commands,
|
| 584 |
+
usage_name=usage_name,
|
| 585 |
+
)
|
| 586 |
+
lines.append(nested_docs)
|
| 587 |
+
|
| 588 |
+
# Add back to top link if we're in a nested section
|
| 589 |
+
if command_chain:
|
| 590 |
+
lines.append('<a href="#top" class="back-to-top">↑ Back to top</a>')
|
| 591 |
+
lines.append("</section>")
|
| 592 |
+
|
| 593 |
+
# Close section if nested command
|
| 594 |
+
if command_chain:
|
| 595 |
+
lines.append("</section>")
|
| 596 |
+
|
| 597 |
+
# Only close cli-documentation div for standalone or root
|
| 598 |
+
if standalone or not command_chain:
|
| 599 |
+
lines.append("</div>") # Close cli-documentation div
|
| 600 |
+
|
| 601 |
+
# Join all lines into body content
|
| 602 |
+
body_content = "\n".join(lines)
|
| 603 |
+
|
| 604 |
+
# If standalone, wrap in complete HTML document
|
| 605 |
+
if standalone:
|
| 606 |
+
css = custom_css if custom_css else DEFAULT_CSS
|
| 607 |
+
doc = f"""<!DOCTYPE html>
|
| 608 |
+
<html lang="en">
|
| 609 |
+
<head>
|
| 610 |
+
<meta charset="UTF-8">
|
| 611 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 612 |
+
<title>{escape_html(app_name)} - CLI Documentation</title>
|
| 613 |
+
<style>
|
| 614 |
+
{css}
|
| 615 |
+
</style>
|
| 616 |
+
</head>
|
| 617 |
+
<body id="top">
|
| 618 |
+
{body_content}
|
| 619 |
+
</body>
|
| 620 |
+
</html>"""
|
| 621 |
+
return doc
|
| 622 |
+
else:
|
| 623 |
+
return body_content
|
.venv/lib/python3.10/site-packages/cyclopts/docs/markdown.py
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Documentation generation functions for cyclopts apps."""
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from cyclopts._markup import extract_text
|
| 6 |
+
from cyclopts.core import DEFAULT_FORMAT
|
| 7 |
+
from cyclopts.docs.base import (
|
| 8 |
+
adjust_filters_for_subcommand,
|
| 9 |
+
apply_usage_name,
|
| 10 |
+
build_command_chain,
|
| 11 |
+
extract_description,
|
| 12 |
+
extract_usage,
|
| 13 |
+
format_usage_line,
|
| 14 |
+
generate_anchor,
|
| 15 |
+
get_app_info,
|
| 16 |
+
is_all_builtin_flags,
|
| 17 |
+
iterate_commands,
|
| 18 |
+
normalize_command_filters,
|
| 19 |
+
should_include_command,
|
| 20 |
+
should_show_commands_list,
|
| 21 |
+
should_show_usage,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from cyclopts.core import App
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _collect_commands_for_toc(
|
| 29 |
+
app: "App",
|
| 30 |
+
include_hidden: bool = False,
|
| 31 |
+
prefix: str = "",
|
| 32 |
+
commands_filter: list[str] | None = None,
|
| 33 |
+
exclude_commands: list[str] | None = None,
|
| 34 |
+
parent_path: list[str] | None = None,
|
| 35 |
+
skip_filtered_command: bool = False,
|
| 36 |
+
) -> list[tuple[str, "App"]]:
|
| 37 |
+
"""Recursively collect all commands for table of contents.
|
| 38 |
+
|
| 39 |
+
Returns a list of (display_name, app) tuples.
|
| 40 |
+
"""
|
| 41 |
+
commands = []
|
| 42 |
+
|
| 43 |
+
if parent_path is None:
|
| 44 |
+
parent_path = []
|
| 45 |
+
|
| 46 |
+
normalized_commands_filter, normalized_exclude_commands = normalize_command_filters(
|
| 47 |
+
commands_filter, exclude_commands
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 51 |
+
if not should_include_command(
|
| 52 |
+
name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp
|
| 53 |
+
):
|
| 54 |
+
continue
|
| 55 |
+
|
| 56 |
+
# Skip the command itself if it's the single filtered command with subcommands
|
| 57 |
+
# (we'll include its children directly instead)
|
| 58 |
+
skip_this_command = skip_filtered_command and subapp._commands
|
| 59 |
+
|
| 60 |
+
if not skip_this_command:
|
| 61 |
+
display_name = f"{prefix}{name}" if prefix else name
|
| 62 |
+
commands.append((display_name, subapp))
|
| 63 |
+
|
| 64 |
+
# Collect nested commands
|
| 65 |
+
nested_path = parent_path + [name]
|
| 66 |
+
# Always include parent in prefix for nested commands (for correct paths)
|
| 67 |
+
nested_prefix = f"{prefix}{name} "
|
| 68 |
+
nested = _collect_commands_for_toc(
|
| 69 |
+
subapp,
|
| 70 |
+
include_hidden=include_hidden,
|
| 71 |
+
prefix=nested_prefix,
|
| 72 |
+
commands_filter=commands_filter,
|
| 73 |
+
exclude_commands=exclude_commands,
|
| 74 |
+
parent_path=nested_path,
|
| 75 |
+
skip_filtered_command=False, # Only skip at the top level
|
| 76 |
+
)
|
| 77 |
+
commands.extend(nested)
|
| 78 |
+
|
| 79 |
+
return commands
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _generate_toc_entries(lines: list[str], commands: list[tuple[str, "App"]]) -> None:
|
| 83 |
+
"""Generate TOC entries with proper indentation.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
lines : list[str]
|
| 88 |
+
List to append TOC entries to.
|
| 89 |
+
commands : list[tuple[str, "App"]]
|
| 90 |
+
List of (display_name, app) tuples.
|
| 91 |
+
"""
|
| 92 |
+
anchor_counts: dict[str, int] = {}
|
| 93 |
+
|
| 94 |
+
for display_name, _app in commands:
|
| 95 |
+
depth = display_name.count(" ") - 1
|
| 96 |
+
indent = " " * depth
|
| 97 |
+
|
| 98 |
+
cmd_name = display_name.split()[-1]
|
| 99 |
+
anchor = generate_anchor(display_name)
|
| 100 |
+
|
| 101 |
+
if anchor in anchor_counts:
|
| 102 |
+
anchor_counts[anchor] += 1
|
| 103 |
+
anchor = f"{anchor}_{anchor_counts[anchor]}"
|
| 104 |
+
else:
|
| 105 |
+
anchor_counts[anchor] = 0
|
| 106 |
+
|
| 107 |
+
lines.append(f"{indent}- [`{cmd_name}`](#{anchor})")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _build_command_map(app: "App", include_hidden: bool = True) -> dict[str, "App"]:
|
| 111 |
+
"""Build mapping of command names to App objects.
|
| 112 |
+
|
| 113 |
+
Parameters
|
| 114 |
+
----------
|
| 115 |
+
app : App
|
| 116 |
+
The app to extract commands from.
|
| 117 |
+
include_hidden : bool
|
| 118 |
+
Whether to include hidden commands.
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
dict[str, App]
|
| 123 |
+
Mapping of command names to App instances.
|
| 124 |
+
"""
|
| 125 |
+
command_map = {}
|
| 126 |
+
if app._commands:
|
| 127 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 128 |
+
command_map[name] = subapp
|
| 129 |
+
return command_map
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _append_if_present(lines: list[str], content: str, add_blank: bool = True) -> None:
|
| 133 |
+
"""Append content to lines if present, optionally adding blank line.
|
| 134 |
+
|
| 135 |
+
Parameters
|
| 136 |
+
----------
|
| 137 |
+
lines : list[str]
|
| 138 |
+
List to append to.
|
| 139 |
+
content : str
|
| 140 |
+
Content to append (only if non-empty).
|
| 141 |
+
add_blank : bool
|
| 142 |
+
Whether to add a blank line after content.
|
| 143 |
+
"""
|
| 144 |
+
if content:
|
| 145 |
+
lines.append(content)
|
| 146 |
+
if add_blank:
|
| 147 |
+
lines.append("")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _render_description_section(app: "App", help_format: str, lines: list[str]) -> None:
|
| 151 |
+
"""Extract and render app description.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
----------
|
| 155 |
+
app : App
|
| 156 |
+
The app to extract description from.
|
| 157 |
+
help_format : str
|
| 158 |
+
Help format (e.g., "markdown", "rich").
|
| 159 |
+
lines : list[str]
|
| 160 |
+
List to append description to.
|
| 161 |
+
"""
|
| 162 |
+
description = extract_description(app, help_format)
|
| 163 |
+
if description:
|
| 164 |
+
# Preserve markup when help_format matches output format (markdown)
|
| 165 |
+
preserve = help_format in ("markdown", "md")
|
| 166 |
+
desc_text = extract_text(description, None, preserve_markup=preserve)
|
| 167 |
+
if desc_text:
|
| 168 |
+
lines.append(desc_text.strip())
|
| 169 |
+
lines.append("")
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _render_usage_section(
|
| 173 |
+
app: "App",
|
| 174 |
+
command_chain: list[str],
|
| 175 |
+
lines: list[str],
|
| 176 |
+
usage_name: str | None = None,
|
| 177 |
+
) -> None:
|
| 178 |
+
"""Render usage console block.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
app : App
|
| 183 |
+
The app to extract usage from.
|
| 184 |
+
command_chain : list[str]
|
| 185 |
+
Command chain for usage line.
|
| 186 |
+
lines : list[str]
|
| 187 |
+
List to append usage to.
|
| 188 |
+
usage_name : str | None
|
| 189 |
+
Optional replacement for the chain's root in Usage: lines only.
|
| 190 |
+
"""
|
| 191 |
+
if should_show_usage(app):
|
| 192 |
+
usage = extract_usage(app)
|
| 193 |
+
if usage:
|
| 194 |
+
lines.append("```console")
|
| 195 |
+
if isinstance(usage, str):
|
| 196 |
+
usage_text = usage
|
| 197 |
+
else:
|
| 198 |
+
usage_text = extract_text(usage, None, preserve_markup=False)
|
| 199 |
+
display_chain = apply_usage_name(command_chain, usage_name)
|
| 200 |
+
usage_line = format_usage_line(usage_text, display_chain)
|
| 201 |
+
lines.append(usage_line)
|
| 202 |
+
lines.append("```")
|
| 203 |
+
lines.append("")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _render_toc(
|
| 207 |
+
app: "App",
|
| 208 |
+
app_name: str,
|
| 209 |
+
include_hidden: bool,
|
| 210 |
+
commands_filter: list[str] | None,
|
| 211 |
+
exclude_commands: list[str] | None,
|
| 212 |
+
skip_filtered_command: bool,
|
| 213 |
+
lines: list[str],
|
| 214 |
+
) -> None:
|
| 215 |
+
"""Generate and render table of contents.
|
| 216 |
+
|
| 217 |
+
Parameters
|
| 218 |
+
----------
|
| 219 |
+
app : App
|
| 220 |
+
The app to generate TOC for.
|
| 221 |
+
app_name : str
|
| 222 |
+
Application name for TOC prefixes.
|
| 223 |
+
include_hidden : bool
|
| 224 |
+
Whether to include hidden commands.
|
| 225 |
+
commands_filter : list[str] | None
|
| 226 |
+
Commands to include.
|
| 227 |
+
exclude_commands : list[str] | None
|
| 228 |
+
Commands to exclude.
|
| 229 |
+
skip_filtered_command : bool
|
| 230 |
+
Whether to skip the single filtered command in TOC.
|
| 231 |
+
lines : list[str]
|
| 232 |
+
List to append TOC to.
|
| 233 |
+
"""
|
| 234 |
+
# Collect all commands recursively for TOC
|
| 235 |
+
toc_commands = _collect_commands_for_toc(
|
| 236 |
+
app,
|
| 237 |
+
include_hidden=include_hidden,
|
| 238 |
+
prefix=f"{app_name} " if app_name else "",
|
| 239 |
+
commands_filter=commands_filter,
|
| 240 |
+
exclude_commands=exclude_commands,
|
| 241 |
+
skip_filtered_command=skip_filtered_command,
|
| 242 |
+
)
|
| 243 |
+
if toc_commands:
|
| 244 |
+
lines.append("## Table of Contents")
|
| 245 |
+
lines.append("")
|
| 246 |
+
_generate_toc_entries(lines, toc_commands)
|
| 247 |
+
lines.append("")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _render_parameter_panel(panel, formatter, lines: list[str]) -> None:
|
| 251 |
+
"""Render a parameter panel as-is.
|
| 252 |
+
|
| 253 |
+
Parameters
|
| 254 |
+
----------
|
| 255 |
+
panel : HelpPanel
|
| 256 |
+
The parameter panel to render.
|
| 257 |
+
formatter : MarkdownFormatter
|
| 258 |
+
Formatter to use for rendering.
|
| 259 |
+
lines : list[str]
|
| 260 |
+
List to append rendered content to.
|
| 261 |
+
"""
|
| 262 |
+
# Render panel content first to check if there's anything
|
| 263 |
+
formatter.reset()
|
| 264 |
+
panel_copy = panel.copy(title="")
|
| 265 |
+
formatter(None, None, panel_copy)
|
| 266 |
+
output = formatter.get_output().strip()
|
| 267 |
+
|
| 268 |
+
# Only render if there's actual content
|
| 269 |
+
if output:
|
| 270 |
+
if panel.title:
|
| 271 |
+
lines.append(f"**{panel.title}**:\n")
|
| 272 |
+
lines.append(output)
|
| 273 |
+
lines.append("")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _filter_command_entries(
|
| 277 |
+
entries: list,
|
| 278 |
+
command_map: dict[str, "App"],
|
| 279 |
+
parent_path: list[str],
|
| 280 |
+
normalized_filter: set[str] | None,
|
| 281 |
+
normalized_exclude: set[str] | None,
|
| 282 |
+
) -> list:
|
| 283 |
+
"""Filter command entries based on inclusion/exclusion rules.
|
| 284 |
+
|
| 285 |
+
Parameters
|
| 286 |
+
----------
|
| 287 |
+
entries : list
|
| 288 |
+
Command entries to filter.
|
| 289 |
+
command_map : dict[str, App]
|
| 290 |
+
Mapping of command names to App objects.
|
| 291 |
+
parent_path : list[str]
|
| 292 |
+
Parent command path.
|
| 293 |
+
normalized_filter : set[str] | None
|
| 294 |
+
Normalized filter set.
|
| 295 |
+
normalized_exclude : set[str] | None
|
| 296 |
+
Normalized exclude set.
|
| 297 |
+
|
| 298 |
+
Returns
|
| 299 |
+
-------
|
| 300 |
+
list
|
| 301 |
+
Filtered command entries.
|
| 302 |
+
"""
|
| 303 |
+
filtered_entries = []
|
| 304 |
+
for entry in entries:
|
| 305 |
+
if entry.names:
|
| 306 |
+
cmd_name = entry.names[0]
|
| 307 |
+
subapp = command_map.get(cmd_name)
|
| 308 |
+
if subapp is None:
|
| 309 |
+
# If command not in map and no filters, include it
|
| 310 |
+
if normalized_filter is None and normalized_exclude is None:
|
| 311 |
+
filtered_entries.append(entry)
|
| 312 |
+
else:
|
| 313 |
+
# Check if command should be included
|
| 314 |
+
if should_include_command(cmd_name, parent_path, normalized_filter, normalized_exclude, subapp):
|
| 315 |
+
filtered_entries.append(entry)
|
| 316 |
+
return filtered_entries
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def generate_markdown_docs(
|
| 320 |
+
app: "App",
|
| 321 |
+
recursive: bool = True,
|
| 322 |
+
include_hidden: bool = False,
|
| 323 |
+
heading_level: int = 1,
|
| 324 |
+
max_heading_level: int = 6,
|
| 325 |
+
command_chain: list[str] | None = None,
|
| 326 |
+
generate_toc: bool = True,
|
| 327 |
+
flatten_commands: bool = False,
|
| 328 |
+
commands_filter: list[str] | None = None,
|
| 329 |
+
exclude_commands: list[str] | None = None,
|
| 330 |
+
no_root_title: bool = False,
|
| 331 |
+
code_block_title: bool = False,
|
| 332 |
+
skip_preamble: bool = False,
|
| 333 |
+
usage_name: str | None = None,
|
| 334 |
+
) -> str:
|
| 335 |
+
"""Generate markdown documentation for a CLI application.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
----------
|
| 339 |
+
app : App
|
| 340 |
+
The cyclopts App instance to document.
|
| 341 |
+
recursive : bool
|
| 342 |
+
If True, generate documentation for all subcommands recursively.
|
| 343 |
+
Default is True.
|
| 344 |
+
include_hidden : bool
|
| 345 |
+
If True, include hidden commands/parameters in documentation.
|
| 346 |
+
Default is False.
|
| 347 |
+
heading_level : int
|
| 348 |
+
Starting heading level for the main application title.
|
| 349 |
+
Default is 1 (single #).
|
| 350 |
+
max_heading_level : int
|
| 351 |
+
Maximum heading level to use. Headings deeper than this will be capped
|
| 352 |
+
at this level. Standard Markdown supports levels 1-6.
|
| 353 |
+
Default is 6.
|
| 354 |
+
command_chain : list[str]
|
| 355 |
+
Internal parameter to track command hierarchy.
|
| 356 |
+
Default is None.
|
| 357 |
+
generate_toc : bool
|
| 358 |
+
If True, generate a table of contents for multi-command apps.
|
| 359 |
+
Default is True.
|
| 360 |
+
flatten_commands : bool
|
| 361 |
+
If True, generate all commands at the same heading level instead of nested.
|
| 362 |
+
Default is False.
|
| 363 |
+
commands_filter : list[str] | None
|
| 364 |
+
If specified, only include commands in this list.
|
| 365 |
+
Supports nested command paths like "db.migrate".
|
| 366 |
+
Default is None (include all commands).
|
| 367 |
+
exclude_commands : list[str] | None
|
| 368 |
+
If specified, exclude commands in this list.
|
| 369 |
+
Supports nested command paths like "db.migrate".
|
| 370 |
+
Default is None (no exclusions).
|
| 371 |
+
no_root_title : bool
|
| 372 |
+
If True, skip the root application title. Used for plugin contexts.
|
| 373 |
+
Default is False.
|
| 374 |
+
skip_preamble : bool
|
| 375 |
+
If True, skip the description and usage sections for the target command
|
| 376 |
+
when filtering to a single command via ``commands_filter``.
|
| 377 |
+
Useful when the user provides their own section introduction.
|
| 378 |
+
Default is False.
|
| 379 |
+
usage_name : str | None
|
| 380 |
+
Optional replacement for the root app name used in ``Usage:`` lines
|
| 381 |
+
only. Headings and TOC anchors still use ``app.name[0]``.
|
| 382 |
+
Default is None (use ``app.name[0]`` as before).
|
| 383 |
+
|
| 384 |
+
Returns
|
| 385 |
+
-------
|
| 386 |
+
str
|
| 387 |
+
The generated markdown documentation.
|
| 388 |
+
"""
|
| 389 |
+
from cyclopts.help.formatters.markdown import MarkdownFormatter
|
| 390 |
+
|
| 391 |
+
# Build the main documentation
|
| 392 |
+
lines = []
|
| 393 |
+
|
| 394 |
+
if command_chain is None:
|
| 395 |
+
command_chain = []
|
| 396 |
+
is_root = True
|
| 397 |
+
else:
|
| 398 |
+
is_root = False
|
| 399 |
+
|
| 400 |
+
# Determine if we should skip the current level's content
|
| 401 |
+
# When filtering to a single command, skip the root app content
|
| 402 |
+
skip_current_level = is_root and commands_filter is not None and len(commands_filter) == 1
|
| 403 |
+
|
| 404 |
+
# Determine the app name and full command path
|
| 405 |
+
app_name, full_command, base_title = get_app_info(app, command_chain)
|
| 406 |
+
# Always use full command path for nested commands to avoid anchor collisions
|
| 407 |
+
# (e.g., "files cp" and "other cp" would both generate #cp without this)
|
| 408 |
+
if command_chain:
|
| 409 |
+
# Show full command path (same for both hierarchical and flattened modes)
|
| 410 |
+
title = f"`{full_command}`" if code_block_title else full_command
|
| 411 |
+
else:
|
| 412 |
+
# Root app: use base title
|
| 413 |
+
title = base_title
|
| 414 |
+
|
| 415 |
+
# Add title for all levels (unless skipping root title or skipping current level entirely)
|
| 416 |
+
if not skip_current_level and not (no_root_title and is_root):
|
| 417 |
+
effective_level = min(heading_level, max_heading_level)
|
| 418 |
+
lines.append(f"{'#' * effective_level} {title}")
|
| 419 |
+
lines.append("")
|
| 420 |
+
|
| 421 |
+
# Get help format (needed for both current level and recursive docs)
|
| 422 |
+
help_format = app.app_stack.resolve("help_format", fallback=DEFAULT_FORMAT)
|
| 423 |
+
|
| 424 |
+
# Add usage section first (skip if skipping current level or skip_preamble is True)
|
| 425 |
+
if not skip_current_level and not skip_preamble:
|
| 426 |
+
_render_usage_section(app, command_chain, lines, usage_name=usage_name)
|
| 427 |
+
|
| 428 |
+
# Add application description (skip if skipping current level or skip_preamble is True)
|
| 429 |
+
if not skip_current_level and not skip_preamble:
|
| 430 |
+
_render_description_section(app, help_format, lines)
|
| 431 |
+
|
| 432 |
+
# Generate table of contents if this is the root level and has commands
|
| 433 |
+
if generate_toc and not command_chain and app._commands:
|
| 434 |
+
_render_toc(app, app_name, include_hidden, commands_filter, exclude_commands, skip_current_level, lines)
|
| 435 |
+
|
| 436 |
+
# Get help panels for the current app (skip if skipping current level)
|
| 437 |
+
# Use app_stack context - if caller set up parent context, it will be stacked
|
| 438 |
+
if not skip_current_level:
|
| 439 |
+
with app.app_stack([app]):
|
| 440 |
+
help_panels_with_groups = app._assemble_help_panels([], help_format)
|
| 441 |
+
|
| 442 |
+
# Set up command filtering (used for command panels only)
|
| 443 |
+
normalized_commands_filter, normalized_exclude_commands = normalize_command_filters(
|
| 444 |
+
commands_filter, exclude_commands
|
| 445 |
+
)
|
| 446 |
+
parent_path = []
|
| 447 |
+
|
| 448 |
+
# Build a mapping of command names to App objects for filtering
|
| 449 |
+
command_map = _build_command_map(app, include_hidden=True)
|
| 450 |
+
|
| 451 |
+
# Create formatter
|
| 452 |
+
formatter = MarkdownFormatter(
|
| 453 |
+
heading_level=heading_level + 1,
|
| 454 |
+
include_hidden=include_hidden,
|
| 455 |
+
table_style="list",
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
# Iterate through panels in the order provided by _assemble_help_panels (already sorted)
|
| 459 |
+
for group, panel in help_panels_with_groups:
|
| 460 |
+
# Skip hidden groups
|
| 461 |
+
if not include_hidden and group and not group.show:
|
| 462 |
+
continue
|
| 463 |
+
|
| 464 |
+
if panel.format == "command":
|
| 465 |
+
# Always filter out built-in flags (--help, --version) from command panels
|
| 466 |
+
# These are standard CLI flags, not commands, and shouldn't appear here
|
| 467 |
+
command_entries = [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))]
|
| 468 |
+
|
| 469 |
+
if not command_entries:
|
| 470 |
+
continue # Skip empty panel
|
| 471 |
+
|
| 472 |
+
# Apply command filtering
|
| 473 |
+
filtered_entries = _filter_command_entries(
|
| 474 |
+
command_entries, command_map, parent_path, normalized_commands_filter, normalized_exclude_commands
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
# Only render if there are filtered entries
|
| 478 |
+
if filtered_entries:
|
| 479 |
+
if panel.title:
|
| 480 |
+
lines.append(f"**{panel.title}**:\n")
|
| 481 |
+
|
| 482 |
+
# Render command entries with hyperlinks to their sections
|
| 483 |
+
for entry in filtered_entries:
|
| 484 |
+
if entry.names:
|
| 485 |
+
cmd_name = entry.names[0]
|
| 486 |
+
# Generate anchor for the full command path
|
| 487 |
+
# Use full_command (not app_name) to include the complete path for nested apps
|
| 488 |
+
full_cmd_path = f"{full_command} {cmd_name}"
|
| 489 |
+
anchor = generate_anchor(full_cmd_path)
|
| 490 |
+
desc_text = (
|
| 491 |
+
extract_text(entry.description, None, preserve_markup=True) if entry.description else ""
|
| 492 |
+
)
|
| 493 |
+
if desc_text:
|
| 494 |
+
lines.append(f"* [`{cmd_name}`](#{anchor}): {desc_text}")
|
| 495 |
+
else:
|
| 496 |
+
lines.append(f"* [`{cmd_name}`](#{anchor})")
|
| 497 |
+
lines.append("")
|
| 498 |
+
elif panel.format == "parameter":
|
| 499 |
+
# Handle parameter panels - split into arguments and options if needed
|
| 500 |
+
_render_parameter_panel(panel, formatter, lines)
|
| 501 |
+
else:
|
| 502 |
+
# When skipping current level, still need to set up filter variables for recursive docs
|
| 503 |
+
normalized_commands_filter, normalized_exclude_commands = normalize_command_filters(
|
| 504 |
+
commands_filter, exclude_commands
|
| 505 |
+
)
|
| 506 |
+
parent_path = []
|
| 507 |
+
|
| 508 |
+
# Handle recursive documentation for subcommands
|
| 509 |
+
if app._commands:
|
| 510 |
+
# Iterate through registered commands using iterate_commands helper
|
| 511 |
+
# This automatically resolves CommandSpec instances
|
| 512 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 513 |
+
if not should_include_command(
|
| 514 |
+
name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp
|
| 515 |
+
):
|
| 516 |
+
continue
|
| 517 |
+
|
| 518 |
+
# Build the command chain for this subcommand
|
| 519 |
+
sub_command_chain = build_command_chain(command_chain, name, app_name)
|
| 520 |
+
|
| 521 |
+
# Determine heading level for subcommand
|
| 522 |
+
if flatten_commands:
|
| 523 |
+
sub_heading_level = heading_level
|
| 524 |
+
elif no_root_title and not command_chain:
|
| 525 |
+
# When root title is skipped, subcommands "take over" the root heading level
|
| 526 |
+
sub_heading_level = heading_level
|
| 527 |
+
else:
|
| 528 |
+
sub_heading_level = heading_level + 1
|
| 529 |
+
|
| 530 |
+
# Check if we should skip this command's title heading
|
| 531 |
+
# Skip title when: root was skipped (single command filter) AND this is the direct target
|
| 532 |
+
# OR this is an intermediate command on the path to a nested target
|
| 533 |
+
# This allows the markdown author's section title to serve as the heading
|
| 534 |
+
is_single_filter = commands_filter is not None and len(commands_filter) == 1
|
| 535 |
+
is_exact_target = is_single_filter and commands_filter is not None and name == commands_filter[0]
|
| 536 |
+
is_intermediate_path = (
|
| 537 |
+
is_single_filter and commands_filter is not None and commands_filter[0].startswith(name + ".")
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
skip_this_command_title = skip_current_level and is_exact_target
|
| 541 |
+
# Also skip intermediate commands entirely when skip_preamble is set
|
| 542 |
+
skip_intermediate = skip_preamble and skip_current_level and is_intermediate_path
|
| 543 |
+
# Skip preamble for the exact target when skip_preamble is set (even in recursive calls)
|
| 544 |
+
skip_target_preamble = skip_preamble and is_exact_target
|
| 545 |
+
|
| 546 |
+
# Generate subcommand title (skip if this is the single filtered command at root level,
|
| 547 |
+
# or if this is an intermediate command and skip_preamble is set)
|
| 548 |
+
if not skip_this_command_title and not skip_intermediate:
|
| 549 |
+
# Always use full command path to avoid anchor collisions
|
| 550 |
+
display_name = " ".join(sub_command_chain)
|
| 551 |
+
display_fmt = f"`{display_name}`" if code_block_title else display_name
|
| 552 |
+
effective_sub_level = min(sub_heading_level, max_heading_level)
|
| 553 |
+
lines.append(f"{'#' * effective_sub_level} {display_fmt}")
|
| 554 |
+
lines.append("")
|
| 555 |
+
|
| 556 |
+
# Get subapp help - show description, usage, and panels for included commands
|
| 557 |
+
# Skip preamble (description + usage) if:
|
| 558 |
+
# - skip_preamble is True and this is the exact target (even in recursive calls)
|
| 559 |
+
# - or this is an intermediate command on the path to a nested target
|
| 560 |
+
skip_this_preamble = skip_target_preamble or skip_intermediate
|
| 561 |
+
|
| 562 |
+
# Include parent app in the stack so default_parameter is properly inherited
|
| 563 |
+
with subapp.app_stack([app, subapp]):
|
| 564 |
+
sub_help_format = subapp.app_stack.resolve("help_format", fallback=help_format)
|
| 565 |
+
# Preserve markup when sub_help_format matches output format (markdown)
|
| 566 |
+
preserve_sub = sub_help_format in ("markdown", "md")
|
| 567 |
+
|
| 568 |
+
if not skip_this_preamble:
|
| 569 |
+
# Generate usage first for subcommand
|
| 570 |
+
_render_usage_section(subapp, sub_command_chain, lines, usage_name=usage_name)
|
| 571 |
+
_render_description_section(subapp, sub_help_format, lines)
|
| 572 |
+
|
| 573 |
+
# Only show subcommand panels if we're in recursive mode
|
| 574 |
+
# (Otherwise we just show the basic info about this command)
|
| 575 |
+
if recursive:
|
| 576 |
+
# Get help panels for subcommand (already sorted)
|
| 577 |
+
sub_panels = subapp._assemble_help_panels([], sub_help_format)
|
| 578 |
+
|
| 579 |
+
# Set up command filtering for this subcommand
|
| 580 |
+
sub_commands_filter_for_panel, sub_exclude_commands_for_panel = adjust_filters_for_subcommand(
|
| 581 |
+
name, normalized_commands_filter, normalized_exclude_commands
|
| 582 |
+
)
|
| 583 |
+
normalized_sub_filter_panel, normalized_sub_exclude_panel = normalize_command_filters(
|
| 584 |
+
sub_commands_filter_for_panel, sub_exclude_commands_for_panel
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
# Build a map of command names to App objects for filtering
|
| 588 |
+
sub_command_map = _build_command_map(subapp, include_hidden=True)
|
| 589 |
+
|
| 590 |
+
# Build parent path for nested commands
|
| 591 |
+
# Use empty path since filter was already adjusted to strip current level's prefix
|
| 592 |
+
nested_parent_path_for_panel = []
|
| 593 |
+
|
| 594 |
+
# Create formatter
|
| 595 |
+
if flatten_commands:
|
| 596 |
+
panel_heading_level = heading_level + 1
|
| 597 |
+
else:
|
| 598 |
+
panel_heading_level = heading_level + 2
|
| 599 |
+
sub_formatter = MarkdownFormatter(
|
| 600 |
+
heading_level=panel_heading_level, include_hidden=include_hidden, table_style="list"
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
# Check if we'll be recursively documenting commands
|
| 604 |
+
will_recurse = recursive and subapp._commands
|
| 605 |
+
|
| 606 |
+
# Iterate through panels in order
|
| 607 |
+
for group, panel in sub_panels:
|
| 608 |
+
# Skip hidden groups
|
| 609 |
+
if not include_hidden and group and not group.show:
|
| 610 |
+
continue
|
| 611 |
+
|
| 612 |
+
if panel.format == "command" and should_show_commands_list(subapp):
|
| 613 |
+
# Always filter out built-in flags (--help, --version) from command panels
|
| 614 |
+
command_entries_list = [
|
| 615 |
+
e for e in panel.entries if not (e.names and is_all_builtin_flags(subapp, e.names))
|
| 616 |
+
]
|
| 617 |
+
|
| 618 |
+
if not command_entries_list:
|
| 619 |
+
continue # Skip empty panel
|
| 620 |
+
|
| 621 |
+
# Apply command filtering for command panels
|
| 622 |
+
if will_recurse:
|
| 623 |
+
# Show simple command list
|
| 624 |
+
command_entries = []
|
| 625 |
+
for entry in command_entries_list:
|
| 626 |
+
if entry.names:
|
| 627 |
+
cmd_name = entry.names[0]
|
| 628 |
+
sub_cmd_app = sub_command_map.get(cmd_name)
|
| 629 |
+
if sub_cmd_app and not should_include_command(
|
| 630 |
+
cmd_name,
|
| 631 |
+
nested_parent_path_for_panel,
|
| 632 |
+
normalized_sub_filter_panel,
|
| 633 |
+
normalized_sub_exclude_panel,
|
| 634 |
+
sub_cmd_app,
|
| 635 |
+
):
|
| 636 |
+
continue
|
| 637 |
+
|
| 638 |
+
desc_text = (
|
| 639 |
+
extract_text(entry.description, None, preserve_markup=preserve_sub)
|
| 640 |
+
if entry.description
|
| 641 |
+
else ""
|
| 642 |
+
)
|
| 643 |
+
# Generate anchor for the full command path
|
| 644 |
+
full_cmd_path = " ".join(sub_command_chain + [cmd_name])
|
| 645 |
+
anchor = generate_anchor(full_cmd_path)
|
| 646 |
+
if desc_text:
|
| 647 |
+
command_entries.append(f"* [`{cmd_name}`](#{anchor}): {desc_text}")
|
| 648 |
+
else:
|
| 649 |
+
command_entries.append(f"* [`{cmd_name}`](#{anchor})")
|
| 650 |
+
|
| 651 |
+
if command_entries:
|
| 652 |
+
if panel.title:
|
| 653 |
+
lines.append(f"**{panel.title}**:\n")
|
| 654 |
+
lines.extend(command_entries)
|
| 655 |
+
lines.append("")
|
| 656 |
+
else:
|
| 657 |
+
# Show full command panel
|
| 658 |
+
filtered_entries = []
|
| 659 |
+
for entry in command_entries_list:
|
| 660 |
+
if entry.names:
|
| 661 |
+
cmd_name = entry.names[0]
|
| 662 |
+
sub_cmd_app = sub_command_map.get(cmd_name)
|
| 663 |
+
if sub_cmd_app and not should_include_command(
|
| 664 |
+
cmd_name,
|
| 665 |
+
nested_parent_path_for_panel,
|
| 666 |
+
normalized_sub_filter_panel,
|
| 667 |
+
normalized_sub_exclude_panel,
|
| 668 |
+
sub_cmd_app,
|
| 669 |
+
):
|
| 670 |
+
continue
|
| 671 |
+
filtered_entries.append(entry)
|
| 672 |
+
|
| 673 |
+
if filtered_entries:
|
| 674 |
+
if panel.title:
|
| 675 |
+
lines.append(f"**{panel.title}**:\n")
|
| 676 |
+
|
| 677 |
+
sub_formatter.reset()
|
| 678 |
+
filtered_panel = panel.__class__(
|
| 679 |
+
title="",
|
| 680 |
+
entries=filtered_entries,
|
| 681 |
+
format=panel.format,
|
| 682 |
+
description=panel.description,
|
| 683 |
+
)
|
| 684 |
+
sub_formatter(None, None, filtered_panel)
|
| 685 |
+
output = sub_formatter.get_output().strip()
|
| 686 |
+
if output:
|
| 687 |
+
lines.append(output)
|
| 688 |
+
lines.append("")
|
| 689 |
+
elif panel.format == "parameter":
|
| 690 |
+
# Handle parameter panels - split into arguments and options if needed
|
| 691 |
+
_render_parameter_panel(panel, sub_formatter, lines)
|
| 692 |
+
|
| 693 |
+
# Process nested commands INSIDE the with block so context is preserved
|
| 694 |
+
if recursive and subapp._commands:
|
| 695 |
+
sub_commands_filter, sub_exclude_commands = adjust_filters_for_subcommand(
|
| 696 |
+
name, normalized_commands_filter, normalized_exclude_commands
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
normalized_sub_filter, normalized_sub_exclude = normalize_command_filters(
|
| 700 |
+
sub_commands_filter, sub_exclude_commands
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
# Build parent path for nested commands
|
| 704 |
+
# Use empty path since filter was already adjusted to strip current level's prefix
|
| 705 |
+
nested_parent_path = []
|
| 706 |
+
|
| 707 |
+
for nested_name, nested_app in iterate_commands(subapp, include_hidden):
|
| 708 |
+
if not should_include_command(
|
| 709 |
+
nested_name, nested_parent_path, normalized_sub_filter, normalized_sub_exclude, nested_app
|
| 710 |
+
):
|
| 711 |
+
continue
|
| 712 |
+
|
| 713 |
+
# Build nested command chain (always use full path for correct usage)
|
| 714 |
+
nested_command_chain = build_command_chain(sub_command_chain, nested_name, app_name)
|
| 715 |
+
# Determine heading level for nested commands
|
| 716 |
+
if flatten_commands:
|
| 717 |
+
nested_heading_level = heading_level
|
| 718 |
+
elif skip_this_command_title:
|
| 719 |
+
# When parent command's title was skipped, promote nested commands to parent's level
|
| 720 |
+
nested_heading_level = sub_heading_level
|
| 721 |
+
else:
|
| 722 |
+
nested_heading_level = sub_heading_level + 1
|
| 723 |
+
# Determine commands_filter for the recursive call
|
| 724 |
+
# Adjust filter to strip current command's prefix for the nested level
|
| 725 |
+
if normalized_sub_filter:
|
| 726 |
+
nested_commands_filter, _ = adjust_filters_for_subcommand(
|
| 727 |
+
nested_name, normalized_sub_filter, normalized_sub_exclude
|
| 728 |
+
)
|
| 729 |
+
else:
|
| 730 |
+
nested_commands_filter = None
|
| 731 |
+
|
| 732 |
+
# Check if this nested command is the target for skip_preamble purposes
|
| 733 |
+
# This handles nested paths like "parent.child" where "child" is the target
|
| 734 |
+
nested_is_target = (
|
| 735 |
+
skip_preamble
|
| 736 |
+
and sub_commands_filter is not None
|
| 737 |
+
and len(sub_commands_filter) == 1
|
| 738 |
+
and nested_name == sub_commands_filter[0]
|
| 739 |
+
)
|
| 740 |
+
# Also check if this is an intermediate on a deeper path
|
| 741 |
+
nested_is_intermediate = (
|
| 742 |
+
skip_preamble
|
| 743 |
+
and sub_commands_filter is not None
|
| 744 |
+
and len(sub_commands_filter) == 1
|
| 745 |
+
and sub_commands_filter[0].startswith(nested_name + ".")
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
# Set up context for nested_app, then recurse
|
| 749 |
+
# The recursive call's app_stack([app]) will stack on top of this
|
| 750 |
+
with nested_app.app_stack([subapp, nested_app]):
|
| 751 |
+
nested_docs = generate_markdown_docs(
|
| 752 |
+
nested_app,
|
| 753 |
+
recursive=recursive,
|
| 754 |
+
include_hidden=include_hidden,
|
| 755 |
+
heading_level=nested_heading_level,
|
| 756 |
+
max_heading_level=max_heading_level,
|
| 757 |
+
command_chain=nested_command_chain,
|
| 758 |
+
generate_toc=False, # Don't generate TOC for nested commands
|
| 759 |
+
flatten_commands=flatten_commands,
|
| 760 |
+
commands_filter=nested_commands_filter,
|
| 761 |
+
exclude_commands=sub_exclude_commands,
|
| 762 |
+
no_root_title=nested_is_intermediate, # Skip title for intermediate paths
|
| 763 |
+
code_block_title=code_block_title,
|
| 764 |
+
skip_preamble=nested_is_target or nested_is_intermediate,
|
| 765 |
+
usage_name=usage_name,
|
| 766 |
+
)
|
| 767 |
+
# Just append the generated docs - no title replacement
|
| 768 |
+
lines.append(nested_docs)
|
| 769 |
+
lines.append("")
|
| 770 |
+
|
| 771 |
+
# Join all lines into final document
|
| 772 |
+
doc = "\n".join(lines).rstrip() + "\n"
|
| 773 |
+
|
| 774 |
+
# Normalize multiple consecutive blank lines to a single blank line
|
| 775 |
+
# This ensures consistent spacing regardless of how content was assembled
|
| 776 |
+
import re
|
| 777 |
+
|
| 778 |
+
doc = re.sub(r"\n{3,}", "\n\n", doc)
|
| 779 |
+
|
| 780 |
+
return doc
|
.venv/lib/python3.10/site-packages/cyclopts/docs/rst.py
ADDED
|
@@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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RST documentation generation functions for cyclopts apps."""
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from cyclopts._markup import extract_text
|
| 6 |
+
from cyclopts.docs.base import (
|
| 7 |
+
adjust_filters_for_subcommand,
|
| 8 |
+
apply_usage_name,
|
| 9 |
+
extract_description,
|
| 10 |
+
extract_usage,
|
| 11 |
+
generate_anchor,
|
| 12 |
+
get_app_info,
|
| 13 |
+
is_all_builtin_flags,
|
| 14 |
+
iterate_commands,
|
| 15 |
+
normalize_command_filters,
|
| 16 |
+
should_include_command,
|
| 17 |
+
should_show_usage,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from cyclopts.core import App
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def make_rst_code_block_title(title: str) -> list[str]:
|
| 25 |
+
"""Create an RST code block containing the title.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
title : str
|
| 30 |
+
Title text to display in code block.
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
list[str]
|
| 35 |
+
RST formatted code block lines.
|
| 36 |
+
"""
|
| 37 |
+
return [
|
| 38 |
+
".. code-block:: text",
|
| 39 |
+
"",
|
| 40 |
+
f" {title}",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def make_rst_section_header(title: str, level: int) -> list[str]:
|
| 45 |
+
"""Create an RST section header.
|
| 46 |
+
|
| 47 |
+
Parameters
|
| 48 |
+
----------
|
| 49 |
+
title : str
|
| 50 |
+
Section title.
|
| 51 |
+
level : int
|
| 52 |
+
Heading level (1-6).
|
| 53 |
+
|
| 54 |
+
Returns
|
| 55 |
+
-------
|
| 56 |
+
list[str]
|
| 57 |
+
RST formatted section header lines.
|
| 58 |
+
"""
|
| 59 |
+
markers = {
|
| 60 |
+
1: "=",
|
| 61 |
+
2: "-",
|
| 62 |
+
3: "^",
|
| 63 |
+
4: '"',
|
| 64 |
+
5: "'",
|
| 65 |
+
6: "~",
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
if level < 1:
|
| 69 |
+
level = 1
|
| 70 |
+
elif level > 6:
|
| 71 |
+
level = 6
|
| 72 |
+
|
| 73 |
+
marker = markers[level]
|
| 74 |
+
underline = marker * len(title)
|
| 75 |
+
|
| 76 |
+
if level == 1:
|
| 77 |
+
return [underline, title, underline]
|
| 78 |
+
else:
|
| 79 |
+
return [title, underline]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _build_command_map(app: "App", include_hidden: bool = True) -> dict[str, "App"]:
|
| 83 |
+
"""Build mapping of command names to App objects.
|
| 84 |
+
|
| 85 |
+
Parameters
|
| 86 |
+
----------
|
| 87 |
+
app : App
|
| 88 |
+
The app to extract commands from.
|
| 89 |
+
include_hidden : bool
|
| 90 |
+
Whether to include hidden commands.
|
| 91 |
+
|
| 92 |
+
Returns
|
| 93 |
+
-------
|
| 94 |
+
dict[str, App]
|
| 95 |
+
Mapping of command names to App instances.
|
| 96 |
+
"""
|
| 97 |
+
command_map = {}
|
| 98 |
+
if app._commands:
|
| 99 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 100 |
+
command_map[name] = subapp
|
| 101 |
+
return command_map
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _filter_command_entries(
|
| 105 |
+
entries: list,
|
| 106 |
+
command_map: dict[str, "App"],
|
| 107 |
+
parent_path: list[str],
|
| 108 |
+
normalized_filter: set[str] | None,
|
| 109 |
+
normalized_exclude: set[str] | None,
|
| 110 |
+
) -> list:
|
| 111 |
+
"""Filter command entries based on inclusion/exclusion rules.
|
| 112 |
+
|
| 113 |
+
Parameters
|
| 114 |
+
----------
|
| 115 |
+
entries : list
|
| 116 |
+
Command entries to filter.
|
| 117 |
+
command_map : dict[str, App]
|
| 118 |
+
Mapping of command names to App objects.
|
| 119 |
+
parent_path : list[str]
|
| 120 |
+
Parent command path.
|
| 121 |
+
normalized_filter : set[str] | None
|
| 122 |
+
Normalized filter set.
|
| 123 |
+
normalized_exclude : set[str] | None
|
| 124 |
+
Normalized exclude set.
|
| 125 |
+
|
| 126 |
+
Returns
|
| 127 |
+
-------
|
| 128 |
+
list
|
| 129 |
+
Filtered command entries.
|
| 130 |
+
"""
|
| 131 |
+
filtered_entries = []
|
| 132 |
+
for entry in entries:
|
| 133 |
+
if entry.names:
|
| 134 |
+
cmd_name = entry.names[0]
|
| 135 |
+
subapp = command_map.get(cmd_name)
|
| 136 |
+
if subapp is None:
|
| 137 |
+
# If command not in map and no filters, include it
|
| 138 |
+
if normalized_filter is None and normalized_exclude is None:
|
| 139 |
+
filtered_entries.append(entry)
|
| 140 |
+
else:
|
| 141 |
+
# Check if command should be included
|
| 142 |
+
if should_include_command(cmd_name, parent_path, normalized_filter, normalized_exclude, subapp):
|
| 143 |
+
filtered_entries.append(entry)
|
| 144 |
+
return filtered_entries
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _generate_toc(lines: list[str]) -> None:
|
| 148 |
+
"""Generate table of contents using RST contents directive.
|
| 149 |
+
|
| 150 |
+
The `.. contents::` directive automatically generates a TOC from
|
| 151 |
+
section headings, which is the idiomatic approach for RST/Sphinx.
|
| 152 |
+
"""
|
| 153 |
+
lines.append(".. contents:: Table of Contents")
|
| 154 |
+
lines.append(" :local:")
|
| 155 |
+
lines.append(" :depth: 6")
|
| 156 |
+
lines.append("")
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def generate_rst_docs(
|
| 160 |
+
app: "App",
|
| 161 |
+
recursive: bool = True,
|
| 162 |
+
include_hidden: bool = False,
|
| 163 |
+
heading_level: int = 1,
|
| 164 |
+
max_heading_level: int = 6,
|
| 165 |
+
command_chain: list[str] | None = None,
|
| 166 |
+
generate_toc: bool = True,
|
| 167 |
+
flatten_commands: bool = False,
|
| 168 |
+
commands_filter: list[str] | None = None,
|
| 169 |
+
exclude_commands: list[str] | None = None,
|
| 170 |
+
no_root_title: bool = False,
|
| 171 |
+
code_block_title: bool = False,
|
| 172 |
+
skip_preamble: bool = False,
|
| 173 |
+
usage_name: str | None = None,
|
| 174 |
+
) -> str:
|
| 175 |
+
"""Generate reStructuredText documentation for a CLI application.
|
| 176 |
+
|
| 177 |
+
Parameters
|
| 178 |
+
----------
|
| 179 |
+
app : App
|
| 180 |
+
The cyclopts App instance to document.
|
| 181 |
+
recursive : bool
|
| 182 |
+
If True, generate documentation for all subcommands recursively.
|
| 183 |
+
Default is True.
|
| 184 |
+
include_hidden : bool
|
| 185 |
+
If True, include hidden commands/parameters in documentation.
|
| 186 |
+
Default is False.
|
| 187 |
+
heading_level : int
|
| 188 |
+
Starting heading level for the main application title.
|
| 189 |
+
Default is 1 (uses '=' markers).
|
| 190 |
+
max_heading_level : int
|
| 191 |
+
Maximum heading level to use. Headings deeper than this will be capped
|
| 192 |
+
at this level. RST uses different underline characters for each level.
|
| 193 |
+
Default is 6.
|
| 194 |
+
command_chain : list[str]
|
| 195 |
+
Internal parameter to track command hierarchy.
|
| 196 |
+
Default is None.
|
| 197 |
+
generate_toc : bool
|
| 198 |
+
If True, generate a table of contents for multi-command apps.
|
| 199 |
+
Default is True.
|
| 200 |
+
flatten_commands : bool
|
| 201 |
+
If True, generate all commands at the same heading level instead of nested.
|
| 202 |
+
Default is False.
|
| 203 |
+
commands_filter : list[str], optional
|
| 204 |
+
If specified, only include commands in this list.
|
| 205 |
+
Supports nested command paths like "db.migrate".
|
| 206 |
+
Default is None (include all commands).
|
| 207 |
+
exclude_commands : list[str], optional
|
| 208 |
+
If specified, exclude commands in this list.
|
| 209 |
+
Supports nested command paths like "db.migrate".
|
| 210 |
+
Default is None (no exclusions).
|
| 211 |
+
no_root_title : bool
|
| 212 |
+
If True, skip generating the root application title.
|
| 213 |
+
Useful when embedding in existing documentation with its own title.
|
| 214 |
+
Default is False.
|
| 215 |
+
skip_preamble : bool
|
| 216 |
+
If True, skip the description and usage sections for the target command
|
| 217 |
+
when filtering to a single command via ``commands_filter``.
|
| 218 |
+
Useful when the user provides their own section introduction.
|
| 219 |
+
Default is False.
|
| 220 |
+
usage_name : str | None
|
| 221 |
+
Optional replacement for the root app name used in ``Usage:`` lines
|
| 222 |
+
only. Section headings, anchors, and TOC continue to use ``app.name[0]``.
|
| 223 |
+
Default is None.
|
| 224 |
+
|
| 225 |
+
Returns
|
| 226 |
+
-------
|
| 227 |
+
str
|
| 228 |
+
The generated RST documentation.
|
| 229 |
+
"""
|
| 230 |
+
from cyclopts.help.formatters.rst import RstFormatter
|
| 231 |
+
|
| 232 |
+
lines = []
|
| 233 |
+
|
| 234 |
+
if command_chain is None:
|
| 235 |
+
command_chain = []
|
| 236 |
+
|
| 237 |
+
app_name, full_command, base_title = get_app_info(app, command_chain)
|
| 238 |
+
# Title logic: match markdown behavior for consistency
|
| 239 |
+
# - Hierarchical mode: show just command name (last part of chain)
|
| 240 |
+
# - Flattened mode: show full command path
|
| 241 |
+
# - Root: use base title
|
| 242 |
+
if command_chain and not flatten_commands:
|
| 243 |
+
# Hierarchical: show just the command name (last part of chain)
|
| 244 |
+
title = command_chain[-1]
|
| 245 |
+
elif command_chain:
|
| 246 |
+
# Flattened: show full command path
|
| 247 |
+
title = full_command
|
| 248 |
+
else:
|
| 249 |
+
# Root app: use base title
|
| 250 |
+
title = base_title
|
| 251 |
+
|
| 252 |
+
# Always generate RST anchor/label with improved namespacing
|
| 253 |
+
# RST uses a "cyclopts-" prefix for namespacing
|
| 254 |
+
anchor_parts = ["cyclopts"]
|
| 255 |
+
if command_chain:
|
| 256 |
+
anchor_parts.extend(command_chain)
|
| 257 |
+
else:
|
| 258 |
+
anchor_parts.append(app_name)
|
| 259 |
+
# Use shared anchor generation logic, then add RST-specific slash replacement
|
| 260 |
+
anchor_name = generate_anchor(" ".join(anchor_parts)).replace("/", "-")
|
| 261 |
+
lines.append(f".. _{anchor_name}:")
|
| 262 |
+
lines.append("")
|
| 263 |
+
|
| 264 |
+
# Determine effective heading level for this command
|
| 265 |
+
if no_root_title and not command_chain:
|
| 266 |
+
# Skip title entirely for root when no_root_title is True
|
| 267 |
+
effective_heading_level = heading_level
|
| 268 |
+
elif flatten_commands and command_chain:
|
| 269 |
+
# When flattening, all commands use the same heading level
|
| 270 |
+
effective_heading_level = heading_level
|
| 271 |
+
else:
|
| 272 |
+
# Normal hierarchical: increment level for nested commands
|
| 273 |
+
effective_heading_level = heading_level + len(command_chain) - 1 if command_chain else heading_level
|
| 274 |
+
|
| 275 |
+
# Cap at max_heading_level
|
| 276 |
+
effective_heading_level = min(effective_heading_level, max_heading_level)
|
| 277 |
+
|
| 278 |
+
if not (no_root_title and not command_chain):
|
| 279 |
+
if code_block_title:
|
| 280 |
+
header_lines = make_rst_code_block_title(title)
|
| 281 |
+
else:
|
| 282 |
+
header_lines = make_rst_section_header(title, effective_heading_level)
|
| 283 |
+
lines.extend(header_lines)
|
| 284 |
+
lines.append("")
|
| 285 |
+
|
| 286 |
+
help_format = app.app_stack.resolve("help_format", fallback="restructuredtext")
|
| 287 |
+
|
| 288 |
+
# Add usage section first if appropriate (skip if skip_preamble is True)
|
| 289 |
+
if not skip_preamble and should_show_usage(app):
|
| 290 |
+
# Generate usage line - only if we're documenting a specific command.
|
| 291 |
+
# When no_root_title is set at the root (e.g., in Sphinx contexts), the
|
| 292 |
+
# root Usage: line is intentionally suppressed; usage_name still applies
|
| 293 |
+
# to every subcommand usage block below.
|
| 294 |
+
if not (no_root_title and not command_chain):
|
| 295 |
+
# Extract usage from app
|
| 296 |
+
usage = extract_usage(app)
|
| 297 |
+
usage_text = None
|
| 298 |
+
if usage:
|
| 299 |
+
if isinstance(usage, str):
|
| 300 |
+
usage_text = usage
|
| 301 |
+
else:
|
| 302 |
+
usage_text = extract_text(usage, None, preserve_markup=False)
|
| 303 |
+
|
| 304 |
+
# Apply usage_name override to the display chain (only for the Usage: line)
|
| 305 |
+
display_chain = apply_usage_name(command_chain, usage_name)
|
| 306 |
+
|
| 307 |
+
# Format usage with the display chain when one is present
|
| 308 |
+
if display_chain:
|
| 309 |
+
parts = usage_text.split(None, 1)
|
| 310 |
+
if len(parts) > 1:
|
| 311 |
+
usage_text = f"{' '.join(display_chain)} {parts[1]}"
|
| 312 |
+
else:
|
| 313 |
+
usage_text = " ".join(display_chain)
|
| 314 |
+
|
| 315 |
+
if usage_text:
|
| 316 |
+
# Use literal block with double colon
|
| 317 |
+
lines.append("::")
|
| 318 |
+
lines.append("")
|
| 319 |
+
# Indent usage text with 4 spaces for literal block
|
| 320 |
+
for line in usage_text.split("\n"):
|
| 321 |
+
lines.append(f" {line}")
|
| 322 |
+
lines.append("")
|
| 323 |
+
|
| 324 |
+
# Add description (skip if skip_preamble is True)
|
| 325 |
+
if not skip_preamble:
|
| 326 |
+
description = extract_description(app, help_format)
|
| 327 |
+
if description:
|
| 328 |
+
# Extract plain text from description
|
| 329 |
+
# Preserve markup when help_format matches output format (RST)
|
| 330 |
+
preserve = help_format in ("restructuredtext", "rst")
|
| 331 |
+
desc_text = extract_text(description, None, preserve_markup=preserve)
|
| 332 |
+
if desc_text:
|
| 333 |
+
lines.append(desc_text.strip())
|
| 334 |
+
lines.append("")
|
| 335 |
+
|
| 336 |
+
# Generate table of contents at root level only
|
| 337 |
+
if generate_toc and not command_chain and app._commands:
|
| 338 |
+
_generate_toc(lines)
|
| 339 |
+
|
| 340 |
+
# Get help panels for the current app
|
| 341 |
+
# Use app_stack context - if caller set up parent context, it will be stacked
|
| 342 |
+
with app.app_stack([app]):
|
| 343 |
+
help_panels_with_groups = app._assemble_help_panels([], help_format)
|
| 344 |
+
|
| 345 |
+
# Set up command filtering
|
| 346 |
+
normalized_commands_filter, normalized_exclude_commands = normalize_command_filters(
|
| 347 |
+
commands_filter, exclude_commands
|
| 348 |
+
)
|
| 349 |
+
parent_path: list[str] = []
|
| 350 |
+
|
| 351 |
+
# Build a mapping of command names to App objects for filtering
|
| 352 |
+
command_map = _build_command_map(app, include_hidden=True)
|
| 353 |
+
|
| 354 |
+
# Create formatter for help panels
|
| 355 |
+
formatter = RstFormatter(heading_level=heading_level + 1, include_hidden=include_hidden)
|
| 356 |
+
|
| 357 |
+
# Render panels as-is without categorization
|
| 358 |
+
for group, panel in help_panels_with_groups:
|
| 359 |
+
# Skip hidden panels unless include_hidden is True
|
| 360 |
+
if not include_hidden and group and not group.show:
|
| 361 |
+
continue
|
| 362 |
+
|
| 363 |
+
# Skip if no_root_title and we're at root
|
| 364 |
+
if no_root_title and not command_chain:
|
| 365 |
+
continue
|
| 366 |
+
|
| 367 |
+
# Render command panels as grouped command lists
|
| 368 |
+
if panel.format == "command":
|
| 369 |
+
# Filter out built-in flags (--help, --version) from command panels
|
| 370 |
+
command_entries = [e for e in panel.entries if not (e.names and is_all_builtin_flags(app, e.names))]
|
| 371 |
+
|
| 372 |
+
if not command_entries:
|
| 373 |
+
continue # Skip empty panel
|
| 374 |
+
|
| 375 |
+
# Apply command filtering
|
| 376 |
+
filtered_entries = _filter_command_entries(
|
| 377 |
+
command_entries, command_map, parent_path, normalized_commands_filter, normalized_exclude_commands
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
if not filtered_entries:
|
| 381 |
+
continue # Skip if nothing after filtering
|
| 382 |
+
|
| 383 |
+
# Render group title
|
| 384 |
+
if panel.title:
|
| 385 |
+
lines.append(f"**{panel.title}:**")
|
| 386 |
+
lines.append("")
|
| 387 |
+
|
| 388 |
+
# Render commands as RST definition list
|
| 389 |
+
for entry in filtered_entries:
|
| 390 |
+
primary_name = entry.names[0] if entry.names else ""
|
| 391 |
+
desc = extract_text(entry.description, None)
|
| 392 |
+
lines.append(f"``{primary_name}``")
|
| 393 |
+
if desc:
|
| 394 |
+
lines.append(f" {desc}")
|
| 395 |
+
lines.append("")
|
| 396 |
+
|
| 397 |
+
# Render parameter panels as-is
|
| 398 |
+
elif panel.format == "parameter":
|
| 399 |
+
# Render content first to check if there's anything
|
| 400 |
+
formatter.reset()
|
| 401 |
+
panel_copy = panel.copy(title="")
|
| 402 |
+
formatter(None, None, panel_copy)
|
| 403 |
+
output = formatter.get_output().strip()
|
| 404 |
+
|
| 405 |
+
# Only render if there's actual content
|
| 406 |
+
if output:
|
| 407 |
+
if panel.title:
|
| 408 |
+
lines.append(f"**{panel.title}:**")
|
| 409 |
+
lines.append("")
|
| 410 |
+
lines.append(output)
|
| 411 |
+
lines.append("")
|
| 412 |
+
|
| 413 |
+
if recursive and app._commands:
|
| 414 |
+
normalized_commands_filter, normalized_exclude_commands = normalize_command_filters(
|
| 415 |
+
commands_filter, exclude_commands
|
| 416 |
+
)
|
| 417 |
+
parent_path = []
|
| 418 |
+
|
| 419 |
+
for name, subapp in iterate_commands(app, include_hidden):
|
| 420 |
+
if not should_include_command(
|
| 421 |
+
name, parent_path, normalized_commands_filter, normalized_exclude_commands, subapp
|
| 422 |
+
):
|
| 423 |
+
continue
|
| 424 |
+
|
| 425 |
+
lines.append("")
|
| 426 |
+
|
| 427 |
+
subcommand_chain = command_chain + [name] if command_chain else [app_name, name]
|
| 428 |
+
if flatten_commands:
|
| 429 |
+
next_heading_level = heading_level
|
| 430 |
+
elif no_root_title and not command_chain:
|
| 431 |
+
next_heading_level = heading_level - 1
|
| 432 |
+
else:
|
| 433 |
+
next_heading_level = heading_level
|
| 434 |
+
|
| 435 |
+
sub_commands_filter, sub_exclude_commands = adjust_filters_for_subcommand(
|
| 436 |
+
name, normalized_commands_filter, normalized_exclude_commands
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
# Determine if this subcommand should skip its preamble
|
| 440 |
+
# Skip preamble when: we're at root, skip_preamble is True, and this is the single target command
|
| 441 |
+
# OR this is an intermediate command on the path to a nested target
|
| 442 |
+
is_single_target = (
|
| 443 |
+
not command_chain
|
| 444 |
+
and skip_preamble
|
| 445 |
+
and commands_filter is not None
|
| 446 |
+
and len(commands_filter) == 1
|
| 447 |
+
and name == commands_filter[0]
|
| 448 |
+
)
|
| 449 |
+
is_intermediate_path = (
|
| 450 |
+
not command_chain
|
| 451 |
+
and skip_preamble
|
| 452 |
+
and commands_filter is not None
|
| 453 |
+
and len(commands_filter) == 1
|
| 454 |
+
and commands_filter[0].startswith(name + ".")
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
# Push subapp onto app_stack - context will stack with recursive call's app_stack([app])
|
| 458 |
+
with subapp.app_stack([app, subapp]):
|
| 459 |
+
subdocs = generate_rst_docs(
|
| 460 |
+
subapp,
|
| 461 |
+
recursive=recursive,
|
| 462 |
+
include_hidden=include_hidden,
|
| 463 |
+
heading_level=next_heading_level,
|
| 464 |
+
max_heading_level=max_heading_level,
|
| 465 |
+
command_chain=subcommand_chain,
|
| 466 |
+
generate_toc=False, # Only generate TOC at root level
|
| 467 |
+
flatten_commands=flatten_commands,
|
| 468 |
+
commands_filter=sub_commands_filter,
|
| 469 |
+
exclude_commands=sub_exclude_commands,
|
| 470 |
+
no_root_title=is_intermediate_path, # Skip title for intermediate path commands
|
| 471 |
+
code_block_title=code_block_title,
|
| 472 |
+
skip_preamble=is_single_target or is_intermediate_path, # Skip preamble for target or intermediate
|
| 473 |
+
usage_name=usage_name,
|
| 474 |
+
)
|
| 475 |
+
lines.append(subdocs)
|
| 476 |
+
|
| 477 |
+
# Join and normalize multiple consecutive blank lines to a single blank line
|
| 478 |
+
import re
|
| 479 |
+
|
| 480 |
+
doc = "\n".join(lines)
|
| 481 |
+
doc = re.sub(r"\n{3,}", "\n\n", doc)
|
| 482 |
+
|
| 483 |
+
return doc
|
.venv/lib/python3.10/site-packages/cyclopts/docs/types.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type definitions and utilities for documentation generation."""
|
| 2 |
+
|
| 3 |
+
from typing import Literal
|
| 4 |
+
|
| 5 |
+
# All accepted format values (canonical and aliases)
|
| 6 |
+
DocFormat = Literal["markdown", "md", "html", "htm", "rst", "rest", "restructuredtext"]
|
| 7 |
+
|
| 8 |
+
# Canonical format values only
|
| 9 |
+
CanonicalDocFormat = Literal["markdown", "html", "rst"]
|
| 10 |
+
|
| 11 |
+
# Map all aliases to their canonical format
|
| 12 |
+
# Also used for suffix lookups by stripping the leading period
|
| 13 |
+
FORMAT_ALIASES: dict[str, CanonicalDocFormat] = {
|
| 14 |
+
"md": "markdown",
|
| 15 |
+
"markdown": "markdown",
|
| 16 |
+
"html": "html",
|
| 17 |
+
"htm": "html",
|
| 18 |
+
"rst": "rst",
|
| 19 |
+
"rest": "rst",
|
| 20 |
+
"restructuredtext": "rst",
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def normalize_format(format_value: str) -> CanonicalDocFormat:
|
| 25 |
+
"""Normalize format aliases to standard format names.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
format_value : str
|
| 30 |
+
The format string to normalize (case-insensitive).
|
| 31 |
+
|
| 32 |
+
Returns
|
| 33 |
+
-------
|
| 34 |
+
CanonicalDocFormat
|
| 35 |
+
The canonical format name.
|
| 36 |
+
|
| 37 |
+
Raises
|
| 38 |
+
------
|
| 39 |
+
ValueError
|
| 40 |
+
If the format is not recognized.
|
| 41 |
+
"""
|
| 42 |
+
format_lower = format_value.lower()
|
| 43 |
+
canonical_format = FORMAT_ALIASES.get(format_lower)
|
| 44 |
+
|
| 45 |
+
if canonical_format is None:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f'Unsupported format "{format_value}". Supported formats: {", ".join(sorted(FORMAT_ALIASES.keys()))}'
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return canonical_format
|