bykcli-plugin 1.0.0a5__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 (38) hide show
  1. bykcli_plugin-1.0.0a5/LICENSE +21 -0
  2. bykcli_plugin-1.0.0a5/PKG-INFO +73 -0
  3. bykcli_plugin-1.0.0a5/README.md +45 -0
  4. bykcli_plugin-1.0.0a5/pyproject.toml +50 -0
  5. bykcli_plugin-1.0.0a5/setup.cfg +4 -0
  6. bykcli_plugin-1.0.0a5/src/bykcli/__init__.py +5 -0
  7. bykcli_plugin-1.0.0a5/src/bykcli/__main__.py +23 -0
  8. bykcli_plugin-1.0.0a5/src/bykcli/api/__init__.py +35 -0
  9. bykcli_plugin-1.0.0a5/src/bykcli/api/context.py +65 -0
  10. bykcli_plugin-1.0.0a5/src/bykcli/api/network.py +91 -0
  11. bykcli_plugin-1.0.0a5/src/bykcli/api/paths.py +30 -0
  12. bykcli_plugin-1.0.0a5/src/bykcli/app.py +151 -0
  13. bykcli_plugin-1.0.0a5/src/bykcli/core/__init__.py +14 -0
  14. bykcli_plugin-1.0.0a5/src/bykcli/core/context.py +50 -0
  15. bykcli_plugin-1.0.0a5/src/bykcli/core/environment.py +29 -0
  16. bykcli_plugin-1.0.0a5/src/bykcli/core/errors.py +7 -0
  17. bykcli_plugin-1.0.0a5/src/bykcli/core/persistence.py +53 -0
  18. bykcli_plugin-1.0.0a5/src/bykcli/core/plugin.py +21 -0
  19. bykcli_plugin-1.0.0a5/src/bykcli/core/state.py +20 -0
  20. bykcli_plugin-1.0.0a5/src/bykcli/infra/__init__.py +0 -0
  21. bykcli_plugin-1.0.0a5/src/bykcli/infra/cache.py +109 -0
  22. bykcli_plugin-1.0.0a5/src/bykcli/infra/logging.py +70 -0
  23. bykcli_plugin-1.0.0a5/src/bykcli/infra/persistence.py +93 -0
  24. bykcli_plugin-1.0.0a5/src/bykcli/infra/registry.py +26 -0
  25. bykcli_plugin-1.0.0a5/src/bykcli/infra/state.py +53 -0
  26. bykcli_plugin-1.0.0a5/src/bykcli/infra/view.py +25 -0
  27. bykcli_plugin-1.0.0a5/src/bykcli/runtime.py +58 -0
  28. bykcli_plugin-1.0.0a5/src/bykcli_plugin.egg-info/PKG-INFO +73 -0
  29. bykcli_plugin-1.0.0a5/src/bykcli_plugin.egg-info/SOURCES.txt +36 -0
  30. bykcli_plugin-1.0.0a5/src/bykcli_plugin.egg-info/dependency_links.txt +1 -0
  31. bykcli_plugin-1.0.0a5/src/bykcli_plugin.egg-info/requires.txt +11 -0
  32. bykcli_plugin-1.0.0a5/src/bykcli_plugin.egg-info/top_level.txt +1 -0
  33. bykcli_plugin-1.0.0a5/tests/test_cli.py +34 -0
  34. bykcli_plugin-1.0.0a5/tests/test_network.py +131 -0
  35. bykcli_plugin-1.0.0a5/tests/test_paths.py +51 -0
  36. bykcli_plugin-1.0.0a5/tests/test_persistence.py +183 -0
  37. bykcli_plugin-1.0.0a5/tests/test_state.py +88 -0
  38. bykcli_plugin-1.0.0a5/tests/test_view.py +57 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yoki
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: bykcli-plugin
3
+ Version: 1.0.0a5
4
+ Summary: Plugin infrastructure for bykcli
5
+ Author-email: fcbyk <731240932@qq.com>
6
+ License: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: click>=8.0.0
19
+ Requires-Dist: bykcli<2.0,>=1.0.0a5
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest<8.0.0,>=7.0.0; extra == "test"
22
+ Requires-Dist: pytest-cov<5.0.0,>=4.0.0; extra == "test"
23
+ Provides-Extra: build
24
+ Requires-Dist: commitizen; extra == "build"
25
+ Requires-Dist: build; extra == "build"
26
+ Requires-Dist: twine; extra == "build"
27
+ Dynamic: license-file
28
+
29
+ # bykcli-plugin
30
+
31
+ [![Python](https://img.shields.io/badge/python-%E2%89%A53.10-blue?logo=python&logoColor=white)](https://www.python.org/downloads/)
32
+ [![Tests](https://github.com/fcbyk/bykcli/actions/workflows/test.yml/badge.svg)](https://github.com/fcbyk/bykcli/actions/workflows/test.yml)
33
+ [![Coverage](https://codecov.io/gh/fcbyk/bykcli/branch/main/graph/badge.svg)](https://codecov.io/gh/fcbyk/bykcli)
34
+ [![License](https://img.shields.io/github/license/fcbyk/bykcli.svg)](https://github.com/fcbyk/bykcli/blob/main/LICENSE)
35
+
36
+ Plugin infrastructure for [bykcli](https://github.com/fcbyk/bykcli).
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install bykcli-plugin
42
+ ```
43
+
44
+ ## Usage
45
+
46
+ Implement `PluginProtocol` and register your commands:
47
+
48
+ ```python
49
+ # my_plugin.py
50
+ import click
51
+ from bykcli import PluginProtocol
52
+
53
+ class MyPlugin(PluginProtocol):
54
+ commands = {"hello": "say hello"}
55
+
56
+ def register(self, cli: click.Group) -> None:
57
+ @cli.command()
58
+ @click.pass_context
59
+ def hello(ctx):
60
+ click.echo("Hello from my plugin!")
61
+ ```
62
+
63
+ ## API
64
+
65
+ - **PluginProtocol** — class-based plugin registration protocol
66
+ - **CommandContext / pass_command_context / get_app_context** — command runtime context
67
+ - **PathItem / PathProvider / register_path_provider** — path management
68
+ - **get_private_networks / ensure_port_available** — network utilities
69
+ - **StateStore** — persistent key-value storage per command
70
+
71
+ ## License
72
+
73
+ MIT
@@ -0,0 +1,45 @@
1
+ # bykcli-plugin
2
+
3
+ [![Python](https://img.shields.io/badge/python-%E2%89%A53.10-blue?logo=python&logoColor=white)](https://www.python.org/downloads/)
4
+ [![Tests](https://github.com/fcbyk/bykcli/actions/workflows/test.yml/badge.svg)](https://github.com/fcbyk/bykcli/actions/workflows/test.yml)
5
+ [![Coverage](https://codecov.io/gh/fcbyk/bykcli/branch/main/graph/badge.svg)](https://codecov.io/gh/fcbyk/bykcli)
6
+ [![License](https://img.shields.io/github/license/fcbyk/bykcli.svg)](https://github.com/fcbyk/bykcli/blob/main/LICENSE)
7
+
8
+ Plugin infrastructure for [bykcli](https://github.com/fcbyk/bykcli).
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install bykcli-plugin
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ Implement `PluginProtocol` and register your commands:
19
+
20
+ ```python
21
+ # my_plugin.py
22
+ import click
23
+ from bykcli import PluginProtocol
24
+
25
+ class MyPlugin(PluginProtocol):
26
+ commands = {"hello": "say hello"}
27
+
28
+ def register(self, cli: click.Group) -> None:
29
+ @cli.command()
30
+ @click.pass_context
31
+ def hello(ctx):
32
+ click.echo("Hello from my plugin!")
33
+ ```
34
+
35
+ ## API
36
+
37
+ - **PluginProtocol** — class-based plugin registration protocol
38
+ - **CommandContext / pass_command_context / get_app_context** — command runtime context
39
+ - **PathItem / PathProvider / register_path_provider** — path management
40
+ - **get_private_networks / ensure_port_available** — network utilities
41
+ - **StateStore** — persistent key-value storage per command
42
+
43
+ ## License
44
+
45
+ MIT
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=75"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bykcli-plugin"
7
+ version = "1.0.0a5"
8
+ description = "Plugin infrastructure for bykcli"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ authors = [
12
+ {name = "fcbyk", email = "731240932@qq.com"}
13
+ ]
14
+ license = {text = "MIT"}
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ ]
25
+ dependencies = [
26
+ "click>=8.0.0",
27
+ "bykcli>=1.0.0a5,<2.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ test = [
32
+ "pytest>=7.0.0,<8.0.0",
33
+ "pytest-cov>=4.0.0,<5.0.0",
34
+ ]
35
+ build = [
36
+ "commitizen",
37
+ "build",
38
+ "twine",
39
+ ]
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = ["src"]
43
+
44
+ [tool.pytest.ini_options]
45
+ testpaths = ["tests"]
46
+ python_files = ["test_*.py"]
47
+ addopts = "-v --cov=bykcli --cov-report=term-missing"
48
+
49
+ [tool.pyright]
50
+ extraPaths = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ from bykcli.core.plugin import PluginProtocol
2
+
3
+ __version__ = "1.0.0a5"
4
+
5
+
@@ -0,0 +1,23 @@
1
+ """支持 ``python -m bykcli`` 运行。"""
2
+
3
+ import sys
4
+
5
+
6
+ if __name__ == "__main__":
7
+ # --scan-plugins: Rust 调用的无头模式,仅扫描插件并写缓存,不启动 CLI
8
+ if len(sys.argv) >= 2 and sys.argv[1] == "--scan-plugins":
9
+ from pathlib import Path
10
+
11
+ from bykcli.infra.cache import _build_cache
12
+ from bykcli.infra.persistence import write_json
13
+
14
+ cache_dir = Path.home() / ".bykcli" / "cache"
15
+ cache_dir.mkdir(parents=True, exist_ok=True)
16
+
17
+ data = _build_cache()
18
+ write_json(cache_dir / "app.json", data)
19
+ sys.exit(0)
20
+
21
+ from bykcli.app import create_cli
22
+
23
+ create_cli()()
@@ -0,0 +1,35 @@
1
+ """面向子命令和插件的公开运行时 API。"""
2
+
3
+ from bykcli.api.context import CommandContext, pass_command_context, get_app_context
4
+ from bykcli.api.paths import (
5
+ PathItem,
6
+ PathProvider,
7
+ register_path_provider,
8
+ get_path_provider,
9
+ global_path_items,
10
+ )
11
+
12
+ from bykcli.api.network import (
13
+ get_private_networks,
14
+ ensure_port_available,
15
+ )
16
+
17
+ from bykcli.core.state import StateStore
18
+
19
+ __all__ = [
20
+ # 上下文
21
+ "CommandContext",
22
+ "pass_command_context",
23
+ "get_app_context",
24
+ # 路径管理
25
+ "PathItem",
26
+ "PathProvider",
27
+ "register_path_provider",
28
+ "get_path_provider",
29
+ "global_path_items",
30
+ # 网络工具
31
+ "get_private_networks",
32
+ "ensure_port_available",
33
+ # 状态存储
34
+ "StateStore",
35
+ ]
@@ -0,0 +1,65 @@
1
+ """面向子命令的上下文封装。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from functools import update_wrapper
7
+ import logging
8
+ from typing import Any, Callable, TypeVar, cast
9
+
10
+ import click
11
+
12
+ from bykcli.app import CliState
13
+ from bykcli.core.context import AppContext, CommandContextLike
14
+ from bykcli.core.state import StateStore
15
+
16
+ F = TypeVar("F", bound=Callable[..., Any])
17
+
18
+
19
+ @dataclass(slots=True)
20
+ class CommandContext(CommandContextLike):
21
+ """提供给子命令的便捷上下文。"""
22
+
23
+ name: str
24
+ app: AppContext
25
+ logger: logging.Logger
26
+ _state_cache: dict[str, StateStore] = field(default_factory=dict, init=False, repr=False)
27
+
28
+ def state(self, name: str = "state") -> StateStore:
29
+ """获取当前命令的专属存储。"""
30
+ if name not in self._state_cache:
31
+ self._state_cache[name] = self.app.command_store(self.name, name)
32
+ return self._state_cache[name]
33
+
34
+ def _get_group_name(ctx: click.Context) -> str:
35
+ """获取二级命令名"""
36
+ node = ctx
37
+ while node.parent and node.parent.parent is not None:
38
+ node = node.parent
39
+ return node.command.name or "unknown"
40
+
41
+ def build_command_context(ctx: click.Context) -> CommandContext:
42
+ """根据当前 Click 上下文构建命令上下文"""
43
+ state = cast(CliState, ctx.obj)
44
+ command_name = _get_group_name(ctx)
45
+ return CommandContext(
46
+ name=command_name,
47
+ app=state.context,
48
+ logger=state.context.get_command_logger(command_name),
49
+ )
50
+
51
+
52
+ def pass_command_context(func: F) -> F:
53
+ """向子命令注入便捷上下文。"""
54
+
55
+ @click.pass_context
56
+ def new_func(ctx: click.Context, *args: Any, **kwargs: Any) -> Any:
57
+ return ctx.invoke(func, build_command_context(ctx), *args, **kwargs)
58
+
59
+ return cast(F, update_wrapper(new_func, func))
60
+
61
+
62
+ def get_app_context() -> AppContext:
63
+ """获取当前应用上下文。"""
64
+ from bykcli.runtime import build_runtime
65
+ return build_runtime()
@@ -0,0 +1,91 @@
1
+ """网络工具函数。"""
2
+ import socket
3
+ from typing import List, Dict
4
+
5
+
6
+ # 网络接口分类规则:(关键词列表,类型名称,是否虚拟接口,优先级)
7
+ IFACE_RULES = [
8
+ (['vmware', 'vmnet'], 'vmware', True, 30),
9
+ (['vbox', 'virtualbox'], 'virtualbox', True, 30),
10
+ (['docker', 'wsl'], 'container', True, 40),
11
+ (['bluetooth'], 'bluetooth', True, 60),
12
+ (['ethernet', '以太网'], 'ethernet', False, 10),
13
+ (['wlan', 'wi-fi', '无线'], 'wifi', False, 10),
14
+ (['loopback'], 'loopback', True, 100),
15
+ ]
16
+
17
+
18
+ def detect_iface_type(iface: str) -> tuple[str, bool, int]:
19
+ """检测网络接口类型。"""
20
+ lname = iface.lower()
21
+ for keywords, t, virtual, prio in IFACE_RULES:
22
+ if any(k in lname for k in keywords):
23
+ return t, virtual, prio
24
+ return 'unknown', False, 50
25
+
26
+
27
+ def get_private_networks() -> List[Dict]:
28
+ """获取所有局域网 IP 地址信息。"""
29
+ try:
30
+ import psutil
31
+ except ImportError:
32
+ return [{
33
+ "iface": "localhost",
34
+ "ips": ["127.0.0.1"],
35
+ "type": "loopback",
36
+ "virtual": True,
37
+ "priority": 100
38
+ }]
39
+
40
+ results = []
41
+ interfaces = psutil.net_if_addrs()
42
+
43
+ for iface, addrs in interfaces.items():
44
+ ips = []
45
+ iface_type, is_virtual, priority = detect_iface_type(iface)
46
+
47
+ for addr in addrs:
48
+ if addr.family != socket.AF_INET:
49
+ continue
50
+
51
+ ip = addr.address
52
+
53
+ # 跳过回环地址和链路本地地址
54
+ if ip.startswith('127.'):
55
+ continue
56
+ if ip.startswith('169.254.'):
57
+ continue
58
+ # 只保留私有 IP 地址
59
+ if ip.startswith(('10.', '192.168.', '172.')):
60
+ ips.append(ip)
61
+
62
+ if ips:
63
+ results.append({
64
+ "iface": iface,
65
+ "ips": ips,
66
+ "type": iface_type,
67
+ "virtual": is_virtual,
68
+ "priority": priority
69
+ })
70
+
71
+ # 按优先级排序(数字越小优先级越高)
72
+ results.sort(key=lambda x: x['priority'])
73
+
74
+ # 如果没有找到任何局域网 IP,返回 localhost
75
+ if not results:
76
+ results.append({
77
+ "iface": "localhost",
78
+ "ips": ["127.0.0.1"],
79
+ "type": "loopback",
80
+ "virtual": True,
81
+ "priority": 100
82
+ })
83
+
84
+ return results
85
+
86
+
87
+ def ensure_port_available(port: int, host: str = "0.0.0.0") -> None:
88
+ """检查端口是否可用。"""
89
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
90
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
91
+ s.bind((host, int(port)))
@@ -0,0 +1,30 @@
1
+ """路径展示注册与渲染。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+
7
+ from bykcli.core.context import AppContext
8
+
9
+ PathItem = tuple[str, str]
10
+ PathProvider = Callable[[AppContext], list[PathItem]]
11
+
12
+ _PATH_PROVIDERS: dict[str, PathProvider] = {}
13
+
14
+
15
+ def register_path_provider(command_name: str, provider: PathProvider) -> None:
16
+ """注册子命令路径提供器。"""
17
+ _PATH_PROVIDERS[command_name] = provider
18
+
19
+
20
+ def get_path_provider(command_name: str) -> PathProvider | None:
21
+ """获取某个子命令的路径提供器。"""
22
+ return _PATH_PROVIDERS.get(command_name)
23
+
24
+
25
+ def global_path_items(context: AppContext) -> list[PathItem]:
26
+ """返回默认展示的全局路径。"""
27
+ return [
28
+ ("CLI Home", str(context.paths.root_dir)),
29
+ ("Logs Directory", str(context.paths.logs_dir)),
30
+ ]
@@ -0,0 +1,151 @@
1
+ """CLI 应用装配。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import click
10
+
11
+ from bykcli.core.context import AppContext
12
+ from bykcli.core.errors import CliError
13
+
14
+ logger = logging.getLogger("bykcli")
15
+
16
+
17
+ class PluginAwareGroup(click.Group):
18
+ """支持插件动态加载的命令组。"""
19
+
20
+ runtime_provider: Any = None
21
+
22
+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
23
+ return super().parse_args(ctx, args)
24
+
25
+ def resolve_command(
26
+ self,
27
+ ctx: click.Context,
28
+ args: list[str],
29
+ ) -> tuple[str | None, click.Command | None, list[str]]:
30
+ orig_args = list(args)
31
+ try:
32
+ return super().resolve_command(ctx, args)
33
+ except click.UsageError:
34
+ pass
35
+
36
+ if not orig_args:
37
+ return super().resolve_command(ctx, orig_args)
38
+
39
+ context = self._get_context(ctx)
40
+
41
+ # 检查缓存中的插件命令,按需加载单个插件
42
+ from bykcli.infra.cache import load_cache
43
+ from bykcli.infra.registry import load_single_plugin
44
+
45
+ cache_data = load_cache(context.paths.cache_dir / "app.json")
46
+ if orig_args[0] in cache_data.get("commands", {}):
47
+ cmd_name = orig_args[0]
48
+ module_path = cache_data["commands"][cmd_name]["module"]
49
+ load_single_plugin(self, cmd_name, module_path)
50
+ return super().resolve_command(ctx, orig_args)
51
+
52
+ # 未知命令
53
+ raise click.UsageError(f"Unknown command: {orig_args[0]}")
54
+
55
+ def _get_context(self, ctx: click.Context) -> AppContext:
56
+ """在命令解析阶段获取运行时上下文。"""
57
+ if ctx.obj is not None:
58
+ return ctx.obj.context
59
+ if callable(self.runtime_provider):
60
+ return self.runtime_provider() # type: ignore[return-type]
61
+ raise click.ClickException("Runtime context not yet initialized")
62
+
63
+ def invoke(self, ctx: click.Context) -> Any:
64
+ """统一兜底未处理异常"""
65
+ try:
66
+ return super().invoke(ctx)
67
+ except click.ClickException:
68
+ raise
69
+ except click.exceptions.Exit:
70
+ raise
71
+ except CliError as exc:
72
+ logger.warning("cli error: %s", exc)
73
+ raise click.ClickException(str(exc)) from exc
74
+ except SystemExit:
75
+ raise
76
+ except Exception as exc: # noqa: BLE001
77
+ logger.exception("unexpected cli error")
78
+ log_file = "log file"
79
+ try:
80
+ if ctx.obj and hasattr(ctx.obj, 'context'):
81
+ log_file = getattr(ctx.obj.context.paths, 'app_log_file', 'log file')
82
+ except Exception:
83
+ pass
84
+
85
+ raise click.ClickException(
86
+ f"Unexpected error occurred, see logs at: {log_file}"
87
+ ) from exc
88
+
89
+
90
+ @dataclass(slots=True)
91
+ class CliState:
92
+ """Click 根命令共享状态。"""
93
+
94
+ context: AppContext
95
+
96
+
97
+ def version_callback(
98
+ ctx: click.Context,
99
+ _param: click.Parameter,
100
+ value: bool,
101
+ ) -> None:
102
+ """Show version and exit."""
103
+ if not value or ctx.resilient_parsing:
104
+ return
105
+
106
+ from bykcli.runtime import build_runtime
107
+
108
+ app_context: AppContext = ctx.obj.context if ctx.obj else build_runtime()
109
+ click.echo(f"v{app_context.version}")
110
+ ctx.exit()
111
+
112
+
113
+ def create_cli() -> click.Group:
114
+ """创建根 CLI 对象。"""
115
+
116
+ from bykcli.runtime import build_runtime
117
+
118
+ runtime: AppContext | None = None
119
+
120
+ def get_runtime() -> AppContext:
121
+ nonlocal runtime
122
+ if runtime is None:
123
+ runtime = build_runtime()
124
+ return runtime
125
+
126
+ @click.group(
127
+ cls=PluginAwareGroup,
128
+ context_settings={"help_option_names": ["-h", "--help"]},
129
+ add_help_option=False,
130
+ invoke_without_command=True,
131
+ )
132
+ @click.option(
133
+ "--version",
134
+ "-v",
135
+ is_flag=True,
136
+ callback=version_callback,
137
+ expose_value=False,
138
+ is_eager=True,
139
+ help="Show version and exit.",
140
+ )
141
+ @click.pass_context
142
+ def cli(ctx: click.Context) -> None:
143
+ ctx.obj = CliState(context=get_runtime())
144
+ ctx.obj.context.logger.info("BYK CLI v%s started", ctx.obj.context.version)
145
+ if ctx.invoked_subcommand is None:
146
+ from bykcli.infra.view import render_dashboard
147
+
148
+ render_dashboard(ctx.obj.context, cli)
149
+
150
+ cli.runtime_provider = get_runtime
151
+ return cli
@@ -0,0 +1,14 @@
1
+ """核心能力模块。"""
2
+
3
+ from bykcli.core.context import AppContext, CommandContextLike
4
+ from bykcli.core.environment import EnvironmentInfo
5
+ from bykcli.core.persistence import PathLayout
6
+ from bykcli.core.state import StateStore
7
+
8
+ __all__ = [
9
+ "AppContext",
10
+ "CommandContextLike",
11
+ "EnvironmentInfo",
12
+ "PathLayout",
13
+ "StateStore",
14
+ ]
@@ -0,0 +1,50 @@
1
+ """CLI 运行时上下文。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import logging
7
+ from typing import TYPE_CHECKING, Protocol
8
+
9
+ from bykcli.core.environment import EnvironmentInfo
10
+ from bykcli.core.persistence import PathLayout
11
+
12
+ if TYPE_CHECKING:
13
+ from bykcli.core.state import StateStore
14
+
15
+
16
+ class CommandContextLike(Protocol):
17
+ """命令上下文协议。"""
18
+
19
+ name: str
20
+ app: "AppContext"
21
+ logger: logging.Logger
22
+
23
+ def state(self, name: str = "state") -> "StateStore": ...
24
+
25
+
26
+ @dataclass(slots=True)
27
+ class AppContext:
28
+ """子命令共享的核心上下文。"""
29
+
30
+ app_name: str
31
+ version: str
32
+ paths: PathLayout
33
+ environment: EnvironmentInfo
34
+ logger: logging.Logger
35
+
36
+ def command_store(
37
+ self,
38
+ command_name: str,
39
+ name: str = "state",
40
+ ) -> StateStore:
41
+ """返回某个子命令的状态存储。"""
42
+ raise NotImplementedError
43
+
44
+ def store(self, name: str = "byk.config") -> StateStore:
45
+ """返回应用级共享状态存储。"""
46
+ raise NotImplementedError
47
+
48
+ def get_command_logger(self, command_name: str) -> logging.Logger:
49
+ """获取命令专属 logger。"""
50
+ raise NotImplementedError