python-tty 0.1.1__tar.gz

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.
Files changed (50) hide show
  1. python_tty-0.1.1/LICENSE +176 -0
  2. python_tty-0.1.1/MANIFEST.in +3 -0
  3. python_tty-0.1.1/NOTICE +3 -0
  4. python_tty-0.1.1/PKG-INFO +75 -0
  5. python_tty-0.1.1/README.md +48 -0
  6. python_tty-0.1.1/README_zh.md +46 -0
  7. python_tty-0.1.1/pyproject.toml +3 -0
  8. python_tty-0.1.1/setup.cfg +4 -0
  9. python_tty-0.1.1/setup.py +29 -0
  10. python_tty-0.1.1/src/python_tty/__init__.py +15 -0
  11. python_tty-0.1.1/src/python_tty/commands/__init__.py +24 -0
  12. python_tty-0.1.1/src/python_tty/commands/core.py +119 -0
  13. python_tty-0.1.1/src/python_tty/commands/decorators.py +58 -0
  14. python_tty-0.1.1/src/python_tty/commands/examples/__init__.py +8 -0
  15. python_tty-0.1.1/src/python_tty/commands/examples/root_commands.py +33 -0
  16. python_tty-0.1.1/src/python_tty/commands/examples/sub_commands.py +11 -0
  17. python_tty-0.1.1/src/python_tty/commands/general.py +107 -0
  18. python_tty-0.1.1/src/python_tty/commands/mixins.py +52 -0
  19. python_tty-0.1.1/src/python_tty/commands/registry.py +185 -0
  20. python_tty-0.1.1/src/python_tty/config/__init__.py +9 -0
  21. python_tty-0.1.1/src/python_tty/config/config.py +35 -0
  22. python_tty-0.1.1/src/python_tty/console_factory.py +100 -0
  23. python_tty-0.1.1/src/python_tty/consoles/__init__.py +16 -0
  24. python_tty-0.1.1/src/python_tty/consoles/core.py +140 -0
  25. python_tty-0.1.1/src/python_tty/consoles/decorators.py +42 -0
  26. python_tty-0.1.1/src/python_tty/consoles/examples/__init__.py +8 -0
  27. python_tty-0.1.1/src/python_tty/consoles/examples/root_console.py +34 -0
  28. python_tty-0.1.1/src/python_tty/consoles/examples/sub_console.py +34 -0
  29. python_tty-0.1.1/src/python_tty/consoles/loader.py +14 -0
  30. python_tty-0.1.1/src/python_tty/consoles/manager.py +146 -0
  31. python_tty-0.1.1/src/python_tty/consoles/registry.py +102 -0
  32. python_tty-0.1.1/src/python_tty/exceptions/__init__.py +7 -0
  33. python_tty-0.1.1/src/python_tty/exceptions/console_exception.py +12 -0
  34. python_tty-0.1.1/src/python_tty/executor/__init__.py +10 -0
  35. python_tty-0.1.1/src/python_tty/executor/executor.py +335 -0
  36. python_tty-0.1.1/src/python_tty/executor/models.py +38 -0
  37. python_tty-0.1.1/src/python_tty/frontends/__init__.py +0 -0
  38. python_tty-0.1.1/src/python_tty/meta/__init__.py +0 -0
  39. python_tty-0.1.1/src/python_tty/ui/__init__.py +13 -0
  40. python_tty-0.1.1/src/python_tty/ui/events.py +55 -0
  41. python_tty-0.1.1/src/python_tty/ui/output.py +102 -0
  42. python_tty-0.1.1/src/python_tty/utils/__init__.py +13 -0
  43. python_tty-0.1.1/src/python_tty/utils/table.py +126 -0
  44. python_tty-0.1.1/src/python_tty/utils/tokenize.py +45 -0
  45. python_tty-0.1.1/src/python_tty/utils/ui_logger.py +17 -0
  46. python_tty-0.1.1/src/python_tty.egg-info/PKG-INFO +75 -0
  47. python_tty-0.1.1/src/python_tty.egg-info/SOURCES.txt +48 -0
  48. python_tty-0.1.1/src/python_tty.egg-info/dependency_links.txt +1 -0
  49. python_tty-0.1.1/src/python_tty.egg-info/requires.txt +2 -0
  50. python_tty-0.1.1/src/python_tty.egg-info/top_level.txt +1 -0
@@ -0,0 +1,176 @@
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, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include README_zh.md
3
+ include LICENSE
@@ -0,0 +1,3 @@
1
+ python-tty
2
+ Copyright 2026 ROOKIEMIE
3
+ Licensed under the Apache License, Version 2.0
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-tty
3
+ Version: 0.1.1
4
+ Summary: A multi-console TTY framework for complex CLI/TTY apps
5
+ Home-page: https://github.com/ROOKIEMIE/python-tty
6
+ Author: ROOKIEMIE
7
+ License: Apache-2.0
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ License-File: NOTICE
15
+ Requires-Dist: prompt_toolkit>=3.0.32
16
+ Requires-Dist: tqdm
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: requires-python
26
+ Dynamic: summary
27
+
28
+ # Command Line Framework (V2: Web/RPC-ready)
29
+
30
+ [中文](README_zh.md)
31
+
32
+ V2 extends the TTY core toward Web + RPC, while keeping the current codebase focused on the TTY runtime. At the moment, Web/RPC is planned but not yet implemented.
33
+
34
+ ## Quick Start (TTY Core)
35
+
36
+ 1) Define your consoles and commands (see examples in `python_tty/consoles/examples` and `python_tty/commands/examples`).
37
+ 2) Ensure console modules are imported so decorators can register them:
38
+ - Update `DEFAULT_CONSOLE_MODULES` in `python_tty/consoles/loader.py`, or
39
+ - Call `load_consoles([...])` manually.
40
+ 3) Start the factory:
41
+
42
+ ```python
43
+ from python_tty.console_factory import ConsoleFactory
44
+
45
+ factory = ConsoleFactory(service=my_business_core)
46
+ factory.start()
47
+ ```
48
+
49
+ The `service` instance is available in all consoles via `console.service`, and in commands via `self.console.service`. If `service` does not inherit `UIEventSpeaker`, a warning is emitted at startup.
50
+
51
+ ## Current Capabilities (TTY Core)
52
+
53
+ Console layer:
54
+ - `python_tty/consoles/core.py`: `BaseConsole`, `MainConsole`, `SubConsole`
55
+ - `python_tty/consoles/manager.py` and `python_tty/consoles/registry.py` for lifecycle and registration
56
+
57
+ Commands layer:
58
+ - `python_tty/commands/core.py`: `BaseCommands`, `CommandValidator`
59
+ - `python_tty/commands/registry.py`: `CommandRegistry`, `ArgSpec`
60
+ - `python_tty/commands/general.py`: `GeneralValidator`, `GeneralCompleter`
61
+ - `python_tty/commands/mixins.py`: `CommandMixin` and built-in mixins
62
+
63
+ UI and utilities:
64
+ - `python_tty/core/events.py`: `UIEvent`, `UIEventLevel`, `UIEventSpeaker`
65
+ - `python_tty/ui/output.py`: `proxy_print`
66
+ - `python_tty/utils/`: `tokenize.py`, `table.py`, `ui_logger.py`
67
+
68
+ ## Roadmap (V2)
69
+
70
+ Planned milestones for Web + RPC:
71
+ - M1: Meta Descriptor v1 + Exporter
72
+ - M2: RPC proto v1 + local (de)serialization
73
+ - M3: Meta Web Server (HTTP + WS)
74
+ - M4: RPC Server (mTLS + allowlist + audit)
75
+ - M5: Unified execution system (CommandExecutor)
@@ -0,0 +1,48 @@
1
+ # Command Line Framework (V2: Web/RPC-ready)
2
+
3
+ [中文](README_zh.md)
4
+
5
+ V2 extends the TTY core toward Web + RPC, while keeping the current codebase focused on the TTY runtime. At the moment, Web/RPC is planned but not yet implemented.
6
+
7
+ ## Quick Start (TTY Core)
8
+
9
+ 1) Define your consoles and commands (see examples in `python_tty/consoles/examples` and `python_tty/commands/examples`).
10
+ 2) Ensure console modules are imported so decorators can register them:
11
+ - Update `DEFAULT_CONSOLE_MODULES` in `python_tty/consoles/loader.py`, or
12
+ - Call `load_consoles([...])` manually.
13
+ 3) Start the factory:
14
+
15
+ ```python
16
+ from python_tty.console_factory import ConsoleFactory
17
+
18
+ factory = ConsoleFactory(service=my_business_core)
19
+ factory.start()
20
+ ```
21
+
22
+ The `service` instance is available in all consoles via `console.service`, and in commands via `self.console.service`. If `service` does not inherit `UIEventSpeaker`, a warning is emitted at startup.
23
+
24
+ ## Current Capabilities (TTY Core)
25
+
26
+ Console layer:
27
+ - `python_tty/consoles/core.py`: `BaseConsole`, `MainConsole`, `SubConsole`
28
+ - `python_tty/consoles/manager.py` and `python_tty/consoles/registry.py` for lifecycle and registration
29
+
30
+ Commands layer:
31
+ - `python_tty/commands/core.py`: `BaseCommands`, `CommandValidator`
32
+ - `python_tty/commands/registry.py`: `CommandRegistry`, `ArgSpec`
33
+ - `python_tty/commands/general.py`: `GeneralValidator`, `GeneralCompleter`
34
+ - `python_tty/commands/mixins.py`: `CommandMixin` and built-in mixins
35
+
36
+ UI and utilities:
37
+ - `python_tty/core/events.py`: `UIEvent`, `UIEventLevel`, `UIEventSpeaker`
38
+ - `python_tty/ui/output.py`: `proxy_print`
39
+ - `python_tty/utils/`: `tokenize.py`, `table.py`, `ui_logger.py`
40
+
41
+ ## Roadmap (V2)
42
+
43
+ Planned milestones for Web + RPC:
44
+ - M1: Meta Descriptor v1 + Exporter
45
+ - M2: RPC proto v1 + local (de)serialization
46
+ - M3: Meta Web Server (HTTP + WS)
47
+ - M4: RPC Server (mTLS + allowlist + audit)
48
+ - M5: Unified execution system (CommandExecutor)
@@ -0,0 +1,46 @@
1
+ # 命令行框架 (V2: Web/RPC 方向)
2
+
3
+ 该分支面向 Web + RPC 能力扩展,目前代码仍以 TTY 核心为主,Web/RPC 尚未落地。
4
+
5
+ ## 快速开始(TTY 核心)
6
+
7
+ 1) 定义 consoles 与 commands(示例见 `python_tty/consoles/examples` 与 `python_tty/commands/examples`)。
8
+ 2) 确保 console 模块被导入以触发装饰器注册:
9
+ - 修改 `python_tty/consoles/loader.py` 中的 `DEFAULT_CONSOLE_MODULES`,或
10
+ - 手动调用 `load_consoles([...])`。
11
+ 3) 启动工厂:
12
+
13
+ ```python
14
+ from python_tty.console_factory import ConsoleFactory
15
+
16
+ factory = ConsoleFactory(service=my_business_core)
17
+ factory.start()
18
+ ```
19
+
20
+ 传入的 `service` 可在 console 中通过 `console.service` 访问,在 commands 中通过 `self.console.service` 访问。若 `service` 未继承 `UIEventSpeaker`,启动时会给出警告。
21
+
22
+ ## 当前能力(TTY 核心)
23
+
24
+ Console 层:
25
+ - `python_tty/consoles/core.py`:`BaseConsole`、`MainConsole`、`SubConsole`
26
+ - `python_tty/consoles/manager.py` 与 `python_tty/consoles/registry.py` 负责生命周期与注册
27
+
28
+ Commands 层:
29
+ - `python_tty/commands/core.py`:`BaseCommands`、`CommandValidator`
30
+ - `python_tty/commands/registry.py`:`CommandRegistry`、`ArgSpec`
31
+ - `python_tty/commands/general.py`:`GeneralValidator`、`GeneralCompleter`
32
+ - `python_tty/commands/mixins.py`:`CommandMixin` 及内置 mixins
33
+
34
+ UI 与工具:
35
+ - `python_tty/core/events.py`:`UIEvent`、`UIEventLevel`、`UIEventSpeaker`
36
+ - `python_tty/ui/output.py`:`proxy_print`
37
+ - `python_tty/utils/`:`tokenize.py`、`table.py`、`ui_logger.py`
38
+
39
+ ## V2 路线图
40
+
41
+ Web + RPC 规划里程碑:
42
+ - M1:Meta Descriptor v1 + Exporter
43
+ - M2:RPC proto v1 + 本地序列化/反序列化
44
+ - M3:Meta Web Server(HTTP + WS)
45
+ - M4:RPC Server(mTLS + allowlist + audit)
46
+ - M5:统一执行系统(CommandExecutor)
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,29 @@
1
+ from setuptools import setup, find_packages
2
+ from pathlib import Path
3
+
4
+ ROOT = Path(__file__).parent
5
+ long_description = (ROOT / "README.md").read_text(encoding="utf-8")
6
+
7
+ setup(
8
+ name="python-tty",
9
+ version="0.1.1",
10
+ description="A multi-console TTY framework for complex CLI/TTY apps",
11
+ long_description=long_description,
12
+ long_description_content_type="text/markdown",
13
+ author="ROOKIEMIE",
14
+ url="https://github.com/ROOKIEMIE/python-tty",
15
+ package_dir={"": "src"},
16
+ packages=find_packages(where="src", exclude=("tests*", "demos*", "docs*")),
17
+ include_package_data=True,
18
+ python_requires=">=3.10",
19
+ install_requires=[
20
+ "prompt_toolkit>=3.0.32",
21
+ "tqdm",
22
+ ],
23
+ license="Apache-2.0",
24
+ classifiers=[
25
+ "License :: OSI Approved :: Apache Software License",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3 :: Only",
28
+ ],
29
+ )
@@ -0,0 +1,15 @@
1
+ from python_tty.config import Config
2
+ from python_tty.console_factory import ConsoleFactory
3
+ from python_tty.ui.events import UIEvent, UIEventLevel, UIEventListener, UIEventSpeaker
4
+ from python_tty.ui.output import proxy_print
5
+
6
+ __all__ = [
7
+ "UIEvent",
8
+ "UIEventLevel",
9
+ "UIEventListener",
10
+ "UIEventSpeaker",
11
+ "ConsoleFactory",
12
+ "Config",
13
+ "proxy_print",
14
+ ]
15
+
@@ -0,0 +1,24 @@
1
+ from python_tty.commands.core import BaseCommands, CommandValidator
2
+ from python_tty.commands.registry import (
3
+ ArgSpec,
4
+ CommandDef,
5
+ CommandInfo,
6
+ CommandRegistry,
7
+ CommandStyle,
8
+ COMMAND_REGISTRY,
9
+ define_command_style,
10
+ )
11
+
12
+ __all__ = [
13
+ "ArgSpec",
14
+ "BaseCommands",
15
+ "CommandDef",
16
+ "CommandInfo",
17
+ "CommandRegistry",
18
+ "CommandStyle",
19
+ "COMMAND_REGISTRY",
20
+ "CommandValidator",
21
+ "define_command_style",
22
+ ]
23
+
24
+
@@ -0,0 +1,119 @@
1
+ from prompt_toolkit.completion import NestedCompleter
2
+ from prompt_toolkit.document import Document
3
+ from prompt_toolkit.validation import DummyValidator, Validator, ValidationError
4
+
5
+ from python_tty.commands.registry import COMMAND_REGISTRY, ArgSpec
6
+ from python_tty.exceptions.console_exception import ConsoleInitException
7
+ from python_tty.utils import split_cmd
8
+
9
+
10
+ class CommandValidator(Validator):
11
+ def __init__(self, command_validators: dict, enable_undefined_command=False):
12
+ self.command_validators = command_validators
13
+ self.enable_undefined_command = enable_undefined_command
14
+ super().__init__()
15
+
16
+ def validate(self, document: Document) -> None:
17
+ try:
18
+ token, arg_text, _ = split_cmd(document.text)
19
+ if token in self.command_validators.keys():
20
+ cmd_validator = self.command_validators[token]
21
+ cmd_validator.validate(Document(text=arg_text))
22
+ else:
23
+ if not self.enable_undefined_command:
24
+ raise ValidationError(message="Bad command")
25
+ except ValueError:
26
+ return
27
+
28
+
29
+ class BaseCommands:
30
+ def __init__(self, console, registry=None):
31
+ self.console = console
32
+ self.registry = registry if registry is not None else COMMAND_REGISTRY
33
+ self.command_defs = []
34
+ self.command_defs_by_name = {}
35
+ self.command_defs_by_id = {}
36
+ self.command_completers = {}
37
+ self.command_validators = {}
38
+ self.command_funcs = {}
39
+ self._init_funcs()
40
+ self.completer = NestedCompleter.from_nested_dict(self.command_completers)
41
+ self.validator = CommandValidator(self.command_validators, self.enable_undefined_command)
42
+
43
+ @property
44
+ def enable_undefined_command(self):
45
+ return False
46
+
47
+ def _init_funcs(self):
48
+ if self.console is None:
49
+ raise ConsoleInitException("Console is None")
50
+ defs = self.registry.get_command_defs_for_console(self.console.__class__)
51
+ if len(defs) == 0:
52
+ defs = self.registry.collect_from_commands_cls(self.__class__)
53
+ self.command_defs = defs
54
+ self._collect_completer_and_validator(defs)
55
+
56
+ def _collect_completer_and_validator(self, defs):
57
+ for command_def in defs:
58
+ self._map_components(command_def)
59
+
60
+ def _map_components(self, command_def):
61
+ command_id = self._build_command_id(command_def)
62
+ if command_id is not None:
63
+ self.command_defs_by_id[command_id] = command_def
64
+ for command_name in command_def.all_names():
65
+ self.command_funcs[command_name] = command_def.func
66
+ self.command_defs_by_name[command_name] = command_def
67
+ if command_def.completer is None:
68
+ self.command_completers[command_name] = None
69
+ else:
70
+ self.command_completers[command_name] = self._build_completer(command_def)
71
+ self.command_validators[command_name] = self._build_validator(command_def)
72
+
73
+ def _build_completer(self, command_def):
74
+ try:
75
+ return command_def.completer(self.console, command_def.arg_spec)
76
+ except TypeError:
77
+ try:
78
+ return command_def.completer(self.console)
79
+ except TypeError as exc:
80
+ raise ConsoleInitException(
81
+ "Completer init failed. Use completer_from(...) to adapt "
82
+ "prompt_toolkit completers."
83
+ ) from exc
84
+
85
+ def _build_validator(self, command_def):
86
+ if command_def.validator is None:
87
+ return DummyValidator()
88
+ try:
89
+ return command_def.validator(self.console, command_def.func, command_def.arg_spec)
90
+ except TypeError:
91
+ return command_def.validator(self.console, command_def.func)
92
+
93
+ def get_command_def(self, command_name):
94
+ command_def = self.command_defs_by_id.get(command_name)
95
+ if command_def is not None:
96
+ return command_def
97
+ return self.command_defs_by_name.get(command_name)
98
+
99
+ def get_command_def_by_id(self, command_id):
100
+ return self.command_defs_by_id.get(command_id)
101
+
102
+ def get_command_id(self, command_name):
103
+ command_def = self.command_defs_by_name.get(command_name)
104
+ if command_def is None:
105
+ return None
106
+ return self._build_command_id(command_def)
107
+
108
+ def _build_command_id(self, command_def):
109
+ console_name = getattr(self.console, "console_name", None)
110
+ if not console_name:
111
+ console_name = self.console.__class__.__name__.lower()
112
+ return f"cmd:{console_name}:{command_def.func_name}"
113
+
114
+ def deserialize_args(self, command_def, raw_text):
115
+ if command_def.arg_spec is None:
116
+ arg_spec = ArgSpec.from_signature(command_def.func)
117
+ return arg_spec.parse(raw_text)
118
+ return command_def.arg_spec.parse(raw_text)
119
+
@@ -0,0 +1,58 @@
1
+ from functools import wraps
2
+
3
+ from prompt_toolkit.completion import Completer
4
+ from prompt_toolkit.validation import Validator
5
+
6
+ from python_tty.commands import BaseCommands
7
+ from python_tty.commands.registry import COMMAND_REGISTRY, CommandInfo, CommandStyle, define_command_style
8
+ from python_tty.exceptions.console_exception import ConsoleInitException
9
+
10
+
11
+ def commands(commands_cls):
12
+ """Bind a BaseCommands subclass to a Console class for auto command wiring."""
13
+ if not issubclass(commands_cls, BaseCommands):
14
+ raise ConsoleInitException("Commands must inherit BaseCommands")
15
+
16
+ def decorator(console_cls):
17
+ from python_tty.consoles import MainConsole, SubConsole
18
+ if not issubclass(console_cls, (MainConsole, SubConsole)):
19
+ raise ConsoleInitException("commands decorator must target a Console class")
20
+ existing = getattr(console_cls, "__commands_cls__", None)
21
+ if existing is not None and existing is not commands_cls:
22
+ raise ConsoleInitException(
23
+ f"{console_cls.__name__} already binds to {existing.__name__}; "
24
+ f"cannot bind to {commands_cls.__name__} again"
25
+ )
26
+ setattr(console_cls, "__commands_cls__", commands_cls)
27
+ COMMAND_REGISTRY.register_console_commands(console_cls, commands_cls)
28
+ return console_cls
29
+
30
+ return decorator
31
+
32
+
33
+ def register_command(command_name: str, command_description: str, command_alias=None,
34
+ command_style=CommandStyle.LOWERCASE,
35
+ completer=None, validator=None, arg_spec=None):
36
+ """Declare command metadata for a command method on a BaseCommands subclass."""
37
+ if completer is not None and not isinstance(completer, type):
38
+ raise ConsoleInitException("Command completer must be a class")
39
+ if validator is not None and not isinstance(validator, type):
40
+ raise ConsoleInitException("Command validator must be a class")
41
+ if completer is not None and not issubclass(completer, Completer):
42
+ raise ConsoleInitException("Command completer must inherit Completer")
43
+ if validator is not None and not issubclass(validator, Validator):
44
+ raise ConsoleInitException("Command validator must inherit Validator")
45
+ def inner_wrapper(func):
46
+ func.info = CommandInfo(define_command_style(command_name, command_style), command_description,
47
+ completer, validator, command_alias, arg_spec)
48
+ func.type = None
49
+
50
+ @wraps(func)
51
+ def wrapper(*args, **kwargs):
52
+ result = func(*args, **kwargs)
53
+ return result
54
+
55
+ return wrapper
56
+
57
+ return inner_wrapper
58
+
@@ -0,0 +1,8 @@
1
+ from python_tty.commands.examples.root_commands import RootCommands
2
+ from python_tty.commands.examples.sub_commands import SubCommands
3
+
4
+ __all__ = [
5
+ "RootCommands",
6
+ "SubCommands",
7
+ ]
8
+
@@ -0,0 +1,33 @@
1
+ from python_tty.commands import BaseCommands
2
+ from python_tty.commands.decorators import register_command
3
+ from python_tty.commands.general import GeneralValidator
4
+ from python_tty.commands.mixins import HelpMixin, QuitMixin
5
+ from python_tty.ui.events import UIEventLevel
6
+ from python_tty.ui.output import proxy_print
7
+
8
+
9
+ class RootCommands(BaseCommands, HelpMixin, QuitMixin):
10
+ @property
11
+ def enable_undefined_command(self):
12
+ return True
13
+
14
+ @register_command("use", "Enter sub console", validator=GeneralValidator)
15
+ def run_use(self, console_name):
16
+ manager = getattr(self.console, "manager", None)
17
+ if manager is None:
18
+ proxy_print("Console manager not configured", UIEventLevel.WARNING)
19
+ return
20
+ if not manager.is_registered(console_name):
21
+ proxy_print(f"Console [{console_name}] not registered", UIEventLevel.ERROR)
22
+ return
23
+ manager.push(console_name)
24
+
25
+ @register_command("debug", "Debug root console, display some information", validator=GeneralValidator)
26
+ def run_debug(self, *args):
27
+ framework = self.console.service
28
+ proxy_print(str(framework))
29
+
30
+
31
+ if __name__ == '__main__':
32
+ pass
33
+
@@ -0,0 +1,11 @@
1
+ from python_tty.commands import BaseCommands
2
+ from python_tty.commands.decorators import register_command
3
+ from python_tty.commands.general import GeneralValidator
4
+ from python_tty.commands.mixins import BackMixin, HelpMixin, QuitMixin
5
+
6
+
7
+ class SubCommands(BaseCommands, HelpMixin, QuitMixin, BackMixin):
8
+ @register_command("debug", "Debug command, display some information", [], validator=GeneralValidator)
9
+ def run_debug(self):
10
+ pass
11
+