pytypeform 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytypeform
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: A Type-Safe UI/CLI Generator powered by Pydantic.
|
|
5
|
+
Project-URL: Homepage, https://github.com/sthitaprajnas/pytypeform
|
|
6
|
+
Project-URL: Repository, https://github.com/sthitaprajnas/pytypeform
|
|
7
|
+
Project-URL: Documentation, https://github.com/sthitaprajnas/pytypeform#readme
|
|
8
|
+
Project-URL: Issues, https://github.com/sthitaprajnas/pytypeform/issues
|
|
9
|
+
Author-email: Sthitaprajna Sahoo <papu.sahoo@gmail.com>
|
|
10
|
+
Maintainer-email: Sthitaprajna Sahoo <papu.sahoo@gmail.com>
|
|
11
|
+
License: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
License-File: NOTICE
|
|
14
|
+
Keywords: cli,form,prompt,pydantic,rich,type-safe,wizard
|
|
15
|
+
Classifier: Development Status :: 4 - Beta
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: <3.14,>=3.10
|
|
29
|
+
Requires-Dist: prompt-toolkit>=3.0.0
|
|
30
|
+
Requires-Dist: pydantic>=2.0.0
|
|
31
|
+
Requires-Dist: rich>=13.0.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: build>=1.0; extra == 'dev'
|
|
34
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
37
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
38
|
+
Requires-Dist: twine>=5.0; extra == 'dev'
|
|
39
|
+
Description-Content-Type: text/markdown
|
|
40
|
+
|
|
41
|
+
# Typerform
|
|
42
|
+
|
|
43
|
+
A Type-Safe UI/CLI Generator powered by Pydantic and Prompt-Toolkit.
|
|
44
|
+
|
|
45
|
+
[](https://pypi.org/project/typeform/)
|
|
46
|
+
[](https://pypi.org/project/typeform/)
|
|
47
|
+
[](https://github.com/sthitaprajnas/typeform/actions/workflows/ci.yml)
|
|
48
|
+
[](LICENSE)
|
|
49
|
+
[](src/typeform/py.typed)
|
|
50
|
+
|
|
51
|
+
Typerform transforms your Pydantic models into professional, interactive CLI wizards. Stop writing boilerplate input loops and manual validation—let your schemas drive the user experience.
|
|
52
|
+
|
|
53
|
+
## Features
|
|
54
|
+
|
|
55
|
+
| Feature | Description |
|
|
56
|
+
|---------|-------------|
|
|
57
|
+
| **Zero Boilerplate** | Just one line of code to generate an entire multi-step wizard. |
|
|
58
|
+
| **Type-Safe** | Inherits all constraints (min_length, ge, EmailStr) from Pydantic. |
|
|
59
|
+
| **Backtracking** | Full backtracking support—type :b or :back to edit previous fields. |
|
|
60
|
+
| **Conditional Logic** | Dynamically skip fields based on previous answers using 'when' metadata. |
|
|
61
|
+
| **Secure by Default** | Automatic masking for SecretStr fields (API keys, passwords). |
|
|
62
|
+
| **Enterprise Ready** | Pluggable prompt engines for 100% automated testing in CI/CD. |
|
|
63
|
+
| **Smart Autocomplete**| Fuzzy search and real-time suggestions for Enums and Literals. |
|
|
64
|
+
| **Hydration** | Pre-fill forms from Environment variables or configuration files. |
|
|
65
|
+
|
|
66
|
+
## Installation
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pip install typeform
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Quick Start
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from typing import Literal
|
|
76
|
+
from pydantic import BaseModel, Field
|
|
77
|
+
from typeform import form
|
|
78
|
+
|
|
79
|
+
class SetupConfig(BaseModel):
|
|
80
|
+
project_name: str = Field(description="Project Name", min_length=3)
|
|
81
|
+
environment: Literal["dev", "staging", "prod"] = Field(default="dev")
|
|
82
|
+
enable_telemetry: bool = Field(default=True, description="Enable Telemetry")
|
|
83
|
+
|
|
84
|
+
# Generate the wizard!
|
|
85
|
+
config = form(SetupConfig, title="Project Setup")
|
|
86
|
+
|
|
87
|
+
print(config.model_dump())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Advanced Usage
|
|
91
|
+
|
|
92
|
+
### Backtracking and Navigation
|
|
93
|
+
Typerform maintains a navigation stack. At any prompt, you can use special commands:
|
|
94
|
+
* `:back` or `:b` - Move to the previous field.
|
|
95
|
+
* `:?` - Show extended help text (if provided in `json_schema_extra`).
|
|
96
|
+
|
|
97
|
+
### Conditional Logic
|
|
98
|
+
Hide or show fields dynamically based on the current state of the form:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
class CloudConfig(BaseModel):
|
|
102
|
+
provider: Literal["aws", "gcp"]
|
|
103
|
+
# Only asked if provider is 'aws'
|
|
104
|
+
aws_region: str = Field(
|
|
105
|
+
"us-east-1",
|
|
106
|
+
json_schema_extra={"when": "provider == 'aws'"}
|
|
107
|
+
)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Collection Wizard (Lists)
|
|
111
|
+
Typerform handles `List[T]` by entering a collection loop:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
class Team(BaseModel):
|
|
115
|
+
members: list[str] = Field(description="Team Members")
|
|
116
|
+
|
|
117
|
+
# User will be prompted to add multiple items sequentially.
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Hydration (Auto-filling)
|
|
121
|
+
Speed up workflows by pre-filling fields from the environment:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
import os
|
|
125
|
+
config = form(MyModel, hydrate_from=[os.environ])
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Contributing
|
|
129
|
+
|
|
130
|
+
Contributions are welcome! Whether it's bug reports, feature requests, or new prompt engines.
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
git clone https://github.com/sthitaprajnas/typeform.git
|
|
134
|
+
cd typeform
|
|
135
|
+
pip install -e ".[dev]"
|
|
136
|
+
pytest # run test suite
|
|
137
|
+
ruff check src/typeform # lint
|
|
138
|
+
mypy src/typeform # type-check
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
|
|
144
|
+
|
|
145
|
+
Copyright (c) 2026 Sthitaprajna Sahoo and contributors.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
typeform/__init__.py,sha256=rF9837SxT3NpDAVOlbuhBBB7lvDHGqXx5bq_dEVYJdg,65
|
|
2
|
+
typeform/core.py,sha256=38vHhG3Hu1saj03VjO1jq74Wq-tdDMjghGfXr7_r7XE,10110
|
|
3
|
+
pytypeform-0.2.1.dist-info/METADATA,sha256=mgW5cfZUURLycpwaqOtdNIs-4BxMcubVJPda27emj_c,5390
|
|
4
|
+
pytypeform-0.2.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
5
|
+
pytypeform-0.2.1.dist-info/licenses/LICENSE,sha256=V00twBu18q-Qz53Ow0LYTGM3LRhCnerVvCnr86eiILA,10166
|
|
6
|
+
pytypeform-0.2.1.dist-info/licenses/NOTICE,sha256=eFkcwH0FjLFBNmXH6WFfb9W09jQdPxUkwzQmlfMOXAE,146
|
|
7
|
+
pytypeform-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submit" means any form of electronic, verbal, or
|
|
51
|
+
written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of discussing and
|
|
55
|
+
improving the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or designated in writing by the copyright owner as "Not a
|
|
57
|
+
Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and included
|
|
61
|
+
within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent contributions
|
|
76
|
+
Licensable by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or any
|
|
81
|
+
Contribution embodied within the Work constitutes direct or contributory
|
|
82
|
+
patent infringement, then any patent licenses granted to You under this
|
|
83
|
+
License for that Work shall terminate as of the date such litigation is
|
|
84
|
+
filed.
|
|
85
|
+
|
|
86
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
87
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
88
|
+
modifications, and in Source or Object form, provided that You
|
|
89
|
+
meet the following conditions:
|
|
90
|
+
|
|
91
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
92
|
+
Works a copy of this License; and
|
|
93
|
+
|
|
94
|
+
(b) You must cause any modified files to carry prominent notices
|
|
95
|
+
stating that You changed the files; and
|
|
96
|
+
|
|
97
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
98
|
+
that You distribute, all copyright, patent, trademark, and
|
|
99
|
+
attribution notices from the Source form of the Work,
|
|
100
|
+
excluding those notices that do not pertain to any part of
|
|
101
|
+
the Derivative Works; and
|
|
102
|
+
|
|
103
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
104
|
+
distribution, You must include a readable copy of the
|
|
105
|
+
attribution notices contained within such NOTICE file, in
|
|
106
|
+
at least one of the following places: within a NOTICE text
|
|
107
|
+
file distributed as part of the Derivative Works; within
|
|
108
|
+
the Source form or documentation, if provided along with the
|
|
109
|
+
Derivative Works; or, within a display generated by the
|
|
110
|
+
Derivative Works, if and wherever such third-party notices
|
|
111
|
+
normally appear. The contents of the NOTICE file are for
|
|
112
|
+
informational purposes only and do not modify the License.
|
|
113
|
+
You may add Your own attribution notices within Derivative
|
|
114
|
+
Works that You distribute, alongside or in addition to the
|
|
115
|
+
NOTICE text from the Work, provided that such additional
|
|
116
|
+
attribution notices cannot be construed as modifying the
|
|
117
|
+
License.
|
|
118
|
+
|
|
119
|
+
You may add Your own license statement for Your modifications and
|
|
120
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
121
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
122
|
+
Derivative Works, as opposed to the original Work.
|
|
123
|
+
|
|
124
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
125
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
126
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
127
|
+
this License, without any additional terms or conditions.
|
|
128
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
129
|
+
the terms of any separate license agreement you may have executed
|
|
130
|
+
with Licensor regarding such Contributions.
|
|
131
|
+
|
|
132
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
133
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
134
|
+
except as required for reasonable and customary use in describing the
|
|
135
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
136
|
+
|
|
137
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
138
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
139
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
140
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
141
|
+
implied, including, without limitation, any conditions of TITLE,
|
|
142
|
+
MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely
|
|
143
|
+
responsible for determining the appropriateness of using or
|
|
144
|
+
redistributing the Work and assume any risks associated with Your
|
|
145
|
+
exercise of permissions under this License.
|
|
146
|
+
|
|
147
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
148
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
149
|
+
unless required by applicable law (such as deliberate and grossly
|
|
150
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
151
|
+
liable to You for damages, including any direct, indirect, special,
|
|
152
|
+
incidental, or exemplary damages of any character arising as a
|
|
153
|
+
result of this License or out of the use or inability to use the
|
|
154
|
+
Work (even if such Contributor has been advised of the possibility
|
|
155
|
+
of such damages).
|
|
156
|
+
|
|
157
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
158
|
+
the Work or Derivative Works thereof, You may choose to offer, and
|
|
159
|
+
charge a fee for, acceptance of support, warranty, indemnity,
|
|
160
|
+
or other liability obligations and/or rights consistent with this
|
|
161
|
+
License. However, in accepting such obligations, You may offer only
|
|
162
|
+
conditions consistent with this License and charge a reasonable fee.
|
|
163
|
+
|
|
164
|
+
END OF TERMS AND CONDITIONS
|
|
165
|
+
|
|
166
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
167
|
+
|
|
168
|
+
To apply the Apache License to your work, attach the following
|
|
169
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
170
|
+
replaced with your own identifying information. (Don't include
|
|
171
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
172
|
+
comment syntax for the file format in question.
|
|
173
|
+
|
|
174
|
+
Copyright 2026 Sthitaprajna Sahoo
|
|
175
|
+
|
|
176
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
177
|
+
you may not use this file except in compliance with the License.
|
|
178
|
+
You may obtain a copy of the License at
|
|
179
|
+
|
|
180
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
181
|
+
|
|
182
|
+
Unless required by applicable law or agreed to in writing, software
|
|
183
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
184
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
185
|
+
See the License for the specific language governing permissions and
|
|
186
|
+
limitations under the License.
|
typeform/__init__.py
ADDED
typeform/core.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import typing
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from typing import Any, TypeVar, get_args, get_origin
|
|
5
|
+
|
|
6
|
+
from prompt_toolkit import prompt as pt_prompt
|
|
7
|
+
from prompt_toolkit.completion import WordCompleter
|
|
8
|
+
from prompt_toolkit.shortcuts import confirm as pt_confirm
|
|
9
|
+
from pydantic import BaseModel, SecretStr, ValidationError, create_model
|
|
10
|
+
from pydantic.fields import FieldInfo
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.panel import Panel
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T", bound=BaseModel)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PromptEngine:
|
|
18
|
+
"""Pluggable engine for handling user prompts using prompt_toolkit."""
|
|
19
|
+
|
|
20
|
+
def ask_text(self, message: str, default: str = "", password: bool = False) -> str:
|
|
21
|
+
return pt_prompt(f"{message}: ", default=default, is_password=password)
|
|
22
|
+
|
|
23
|
+
def ask_confirm(self, message: str, default: bool = False) -> bool:
|
|
24
|
+
return pt_confirm(f"{message}")
|
|
25
|
+
|
|
26
|
+
def ask_choice(self, message: str, choices: list[str], default: str = "") -> str:
|
|
27
|
+
msg = f"{message} ({'/'.join(choices)})"
|
|
28
|
+
completer = WordCompleter(choices, ignore_case=True)
|
|
29
|
+
return pt_prompt(f"{msg}: ", default=str(default), completer=completer)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TyperformConfig:
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self.console = Console(force_terminal=False)
|
|
35
|
+
self.engine = PromptEngine()
|
|
36
|
+
self.verbose = True
|
|
37
|
+
self.show_progress = True
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
config = TyperformConfig()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def set_engine(engine: PromptEngine) -> None:
|
|
44
|
+
config.engine = engine
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _is_list_type(annotation: Any) -> bool:
|
|
48
|
+
origin = get_origin(annotation)
|
|
49
|
+
return origin in (list, list, Sequence, list)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _is_optional_type(annotation: Any) -> bool:
|
|
53
|
+
origin = get_origin(annotation)
|
|
54
|
+
if origin is typing.Union or origin is getattr(typing, "UnionType", type(None)):
|
|
55
|
+
args = get_args(annotation)
|
|
56
|
+
return type(None) in args
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _extract_base_type(annotation: Any) -> Any:
|
|
61
|
+
origin = get_origin(annotation)
|
|
62
|
+
if origin is typing.Union or origin is getattr(typing, "UnionType", type(None)):
|
|
63
|
+
args = get_args(annotation)
|
|
64
|
+
non_none_args = [a for a in args if a is not type(None)]
|
|
65
|
+
if len(non_none_args) == 1:
|
|
66
|
+
return non_none_args[0]
|
|
67
|
+
return annotation
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _get_prompt_class_and_choices(annotation: Any) -> tuple[type | None, list[str] | None]:
|
|
71
|
+
base_type = _extract_base_type(annotation)
|
|
72
|
+
origin = get_origin(base_type)
|
|
73
|
+
args = get_args(base_type)
|
|
74
|
+
if base_type is bool:
|
|
75
|
+
return bool, None
|
|
76
|
+
if origin is typing.Literal or (isinstance(base_type, type) and issubclass(base_type, Enum)):
|
|
77
|
+
choices = (
|
|
78
|
+
[str(arg) for arg in args] if origin is typing.Literal else [e.name for e in base_type]
|
|
79
|
+
)
|
|
80
|
+
return base_type, choices
|
|
81
|
+
return None, None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _should_show_field(field_info: FieldInfo, current_data: dict[str, Any]) -> bool:
|
|
85
|
+
if not field_info.json_schema_extra or "when" not in field_info.json_schema_extra: # type: ignore
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
when_condition = field_info.json_schema_extra["when"] # type: ignore
|
|
89
|
+
if isinstance(when_condition, str):
|
|
90
|
+
try:
|
|
91
|
+
return bool(eval(when_condition, {}, current_data))
|
|
92
|
+
except Exception:
|
|
93
|
+
return True
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _prompt_for_field(
|
|
98
|
+
field_name: str,
|
|
99
|
+
field_info: FieldInfo,
|
|
100
|
+
current_data: dict[str, Any],
|
|
101
|
+
current_step: int = 0,
|
|
102
|
+
total_steps: int = 0,
|
|
103
|
+
) -> Any:
|
|
104
|
+
prompt_text = field_info.description or field_name.replace("_", " ").title()
|
|
105
|
+
is_required = field_info.is_required()
|
|
106
|
+
|
|
107
|
+
# DYNAMIC DEFAULTING
|
|
108
|
+
default = field_info.default if not is_required else None
|
|
109
|
+
if callable(default):
|
|
110
|
+
try:
|
|
111
|
+
default = default(current_data)
|
|
112
|
+
except Exception:
|
|
113
|
+
default = None
|
|
114
|
+
|
|
115
|
+
base_type = _extract_base_type(field_info.annotation)
|
|
116
|
+
|
|
117
|
+
# 1. Handle Lists (Collection Wizard)
|
|
118
|
+
if _is_list_type(base_type):
|
|
119
|
+
item_type = get_args(base_type)[0]
|
|
120
|
+
items: list[Any] = []
|
|
121
|
+
config.console.print(
|
|
122
|
+
f"\n[bold blue]Entering list collection for: {prompt_text}[/bold blue]"
|
|
123
|
+
)
|
|
124
|
+
while True:
|
|
125
|
+
item_field_info = FieldInfo(
|
|
126
|
+
annotation=item_type, description=f"{prompt_text} Item #{len(items) + 1}"
|
|
127
|
+
)
|
|
128
|
+
if items and not config.engine.ask_confirm(f"Add another item to '{prompt_text}'?"):
|
|
129
|
+
break
|
|
130
|
+
|
|
131
|
+
items_context = {**current_data, "_items": items}
|
|
132
|
+
val = _prompt_for_field(f"{field_name}_item", item_field_info, items_context)
|
|
133
|
+
items.append(val)
|
|
134
|
+
if not items:
|
|
135
|
+
break
|
|
136
|
+
return items
|
|
137
|
+
|
|
138
|
+
# 2. Handle Nested Models
|
|
139
|
+
if isinstance(base_type, type) and issubclass(base_type, BaseModel):
|
|
140
|
+
if config.verbose:
|
|
141
|
+
config.console.print(
|
|
142
|
+
f"\n[bold yellow]↳ Step {current_step}/{total_steps} (Nested): {prompt_text}[/bold yellow]"
|
|
143
|
+
)
|
|
144
|
+
return form(base_type, title=f"Nested: {prompt_text}")
|
|
145
|
+
|
|
146
|
+
# 3. Standard Field Logic
|
|
147
|
+
is_secret = base_type is SecretStr or (
|
|
148
|
+
isinstance(base_type, type) and "Secret" in base_type.__name__
|
|
149
|
+
)
|
|
150
|
+
prompt_type, choices = _get_prompt_class_and_choices(field_info.annotation)
|
|
151
|
+
step_prefix = f"[{current_step}/{total_steps}] " if total_steps > 0 else ""
|
|
152
|
+
|
|
153
|
+
while True:
|
|
154
|
+
try:
|
|
155
|
+
display_msg = f"{step_prefix}{prompt_text}"
|
|
156
|
+
help_hint = ""
|
|
157
|
+
if field_info.json_schema_extra and "help" in field_info.json_schema_extra: # type: ignore
|
|
158
|
+
help_hint = " [dim](type ':?' for help)[/dim]"
|
|
159
|
+
|
|
160
|
+
if prompt_type is bool:
|
|
161
|
+
val = config.engine.ask_confirm(
|
|
162
|
+
display_msg + help_hint,
|
|
163
|
+
default=bool(default) if default is not None and default != ... else False,
|
|
164
|
+
)
|
|
165
|
+
elif choices:
|
|
166
|
+
def_val = (
|
|
167
|
+
default.name
|
|
168
|
+
if isinstance(default, Enum)
|
|
169
|
+
else str(default if (default is not None and default != ...) else "")
|
|
170
|
+
)
|
|
171
|
+
val = config.engine.ask_choice(display_msg + help_hint, choices, default=def_val)
|
|
172
|
+
else:
|
|
173
|
+
def_val = str(default) if default is not None and default != ... else ""
|
|
174
|
+
val = config.engine.ask_text(
|
|
175
|
+
display_msg + help_hint, default=def_val, password=is_secret
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
if isinstance(val, str):
|
|
179
|
+
if val == ":?":
|
|
180
|
+
config.console.print(
|
|
181
|
+
f"[cyan]Help:[/cyan] {field_info.json_schema_extra.get('help', 'No help available')}" # type: ignore
|
|
182
|
+
)
|
|
183
|
+
continue
|
|
184
|
+
if val in (":b", ":back"):
|
|
185
|
+
return "__BACK__"
|
|
186
|
+
|
|
187
|
+
if (
|
|
188
|
+
_is_optional_type(field_info.annotation)
|
|
189
|
+
and val == ""
|
|
190
|
+
and (default is None or default == ...)
|
|
191
|
+
):
|
|
192
|
+
return None
|
|
193
|
+
|
|
194
|
+
field_type = field_info.annotation or Any
|
|
195
|
+
ValidatorModel = create_model(
|
|
196
|
+
"_ValidatorModel", **{field_name: (field_type, field_info)}
|
|
197
|
+
) # type: ignore
|
|
198
|
+
instance = ValidatorModel(**{field_name: val})
|
|
199
|
+
return getattr(instance, field_name)
|
|
200
|
+
except ValidationError as e:
|
|
201
|
+
if config.verbose:
|
|
202
|
+
config.console.print(
|
|
203
|
+
f"[bold red]Validation Error:[/bold red] {e.errors()[0]['msg']}"
|
|
204
|
+
)
|
|
205
|
+
continue
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def form(
|
|
209
|
+
model_class: type[T],
|
|
210
|
+
title: str | None = None,
|
|
211
|
+
exclude: set[str] | None = None,
|
|
212
|
+
hydrate_from: list[dict[str, Any]] | None = None,
|
|
213
|
+
) -> T:
|
|
214
|
+
display_title = title or model_class.__name__
|
|
215
|
+
exclude_set = exclude or set()
|
|
216
|
+
hydration_sources = hydrate_from or []
|
|
217
|
+
|
|
218
|
+
if config.verbose and not (title and title.startswith("Nested:")):
|
|
219
|
+
config.console.print(Panel(f"[bold cyan]Completing Form:[/bold cyan] {display_title}"))
|
|
220
|
+
|
|
221
|
+
collected_data: dict[str, Any] = {}
|
|
222
|
+
fields = list(model_class.model_fields.items())
|
|
223
|
+
active_fields = [(n, f) for n, f in fields if n not in exclude_set]
|
|
224
|
+
|
|
225
|
+
idx = 0
|
|
226
|
+
while idx < len(active_fields):
|
|
227
|
+
field_name, field_info = active_fields[idx]
|
|
228
|
+
if not _should_show_field(field_info, collected_data):
|
|
229
|
+
idx += 1
|
|
230
|
+
continue
|
|
231
|
+
|
|
232
|
+
hydrated_val = None
|
|
233
|
+
for source in hydration_sources:
|
|
234
|
+
if field_name.upper() in source:
|
|
235
|
+
hydrated_val = source[field_name.upper()]
|
|
236
|
+
elif field_name in source:
|
|
237
|
+
hydrated_val = source[field_name]
|
|
238
|
+
|
|
239
|
+
if hydrated_val is not None:
|
|
240
|
+
try:
|
|
241
|
+
ValidatorModel = create_model(
|
|
242
|
+
"_V", **{field_name: (field_info.annotation, field_info)}
|
|
243
|
+
) # type: ignore
|
|
244
|
+
instance = ValidatorModel(**{field_name: hydrated_val})
|
|
245
|
+
collected_data[field_name] = getattr(instance, field_name)
|
|
246
|
+
if config.verbose:
|
|
247
|
+
config.console.print(f"[dim][Auto-filled {field_name}][/dim]")
|
|
248
|
+
break
|
|
249
|
+
except ValidationError:
|
|
250
|
+
hydrated_val = None
|
|
251
|
+
|
|
252
|
+
if hydrated_val is not None:
|
|
253
|
+
idx += 1
|
|
254
|
+
continue
|
|
255
|
+
|
|
256
|
+
res = _prompt_for_field(
|
|
257
|
+
field_name,
|
|
258
|
+
field_info,
|
|
259
|
+
collected_data,
|
|
260
|
+
current_step=idx + 1,
|
|
261
|
+
total_steps=len(active_fields),
|
|
262
|
+
)
|
|
263
|
+
if res == "__BACK__":
|
|
264
|
+
if idx > 0:
|
|
265
|
+
idx -= 1
|
|
266
|
+
collected_data.pop(active_fields[idx][0], None)
|
|
267
|
+
continue
|
|
268
|
+
else:
|
|
269
|
+
config.console.print("[yellow]Already at the first field.[/yellow]")
|
|
270
|
+
continue
|
|
271
|
+
|
|
272
|
+
collected_data[field_name] = res
|
|
273
|
+
idx += 1
|
|
274
|
+
|
|
275
|
+
if config.verbose and not (title and title.startswith("Nested:")):
|
|
276
|
+
config.console.print(
|
|
277
|
+
f"\n[bold green]✔ Form {display_title} completed successfully![/bold green]"
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return model_class(**collected_data)
|