pboot-cli 1.0.0__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.
pboot/cli/__init__.py ADDED
@@ -0,0 +1,348 @@
1
+ """The ``pboot`` command line interface, built on :mod:`argparse`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import os
8
+ import sys
9
+ import typing as t
10
+
11
+ from ._app import (
12
+ NoAppException,
13
+ ensure_cwd_importable,
14
+ find_app_attribute,
15
+ find_app_by_string,
16
+ find_best_app,
17
+ load_app,
18
+ locate_app,
19
+ prepare_import,
20
+ resolve_import_string,
21
+ )
22
+ from ._commands import error, routes_command, run_command, shell_command
23
+ from ._group import AppGroup, Command
24
+
25
+ __version__ = "1.0.0"
26
+
27
+ __all__ = [
28
+ "AppGroup",
29
+ "Command",
30
+ "NoAppException",
31
+ "ScriptInfo",
32
+ "build_parser",
33
+ "cli",
34
+ "ensure_cwd_importable",
35
+ "find_app_attribute",
36
+ "find_app_by_string",
37
+ "find_best_app",
38
+ "get_version",
39
+ "load_app",
40
+ "load_dotenv",
41
+ "locate_app",
42
+ "main",
43
+ "prepare_import",
44
+ "resolve_import_string",
45
+ "show_server_banner",
46
+ "with_appcontext",
47
+ ]
48
+
49
+ _TRUE = {"1", "true", "yes", "on"}
50
+
51
+
52
+ class _VersionAction(argparse.Action):
53
+ """``--version``, printed in the ``pboot, version X`` form."""
54
+
55
+ def __init__(self, option_strings: t.Sequence[str], dest: str, **kwargs: t.Any) -> None:
56
+ super().__init__(option_strings, dest, nargs=0, **kwargs)
57
+
58
+ def __call__(self, parser: argparse.ArgumentParser, namespace: t.Any, values: t.Any, option_string: str | None = None) -> t.NoReturn:
59
+ parser.exit(0, f"pboot, version {get_version()}\n")
60
+
61
+
62
+ class ScriptInfo:
63
+ """Holds the information about the application a command runs against."""
64
+
65
+ def __init__(
66
+ self,
67
+ app_import_path: str | None = None,
68
+ app: t.Any = None,
69
+ set_debug_flag: bool = True,
70
+ ) -> None:
71
+ self.app_import_path = app_import_path
72
+ self.app = app
73
+ self.set_debug_flag = set_debug_flag
74
+ self._loaded_app: t.Any = None
75
+
76
+ def load_app(self) -> t.Any:
77
+ """Load the application, once."""
78
+ if self._loaded_app is not None:
79
+ return self._loaded_app
80
+
81
+ if self.app is not None:
82
+ self._loaded_app = self.app
83
+ elif self.app_import_path:
84
+ self._loaded_app = load_app(self.app_import_path)
85
+
86
+ return self._loaded_app
87
+
88
+ def load_dotenv(self) -> bool:
89
+ """Load the ``.env`` file."""
90
+ from pboot.core.helpers import get_load_dotenv
91
+
92
+ if not get_load_dotenv():
93
+ return False
94
+
95
+ return load_dotenv()
96
+
97
+
98
+ def with_appcontext(f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
99
+ """Wrap a command so it runs inside the application context."""
100
+ f.with_appcontext = True # type: ignore[attr-defined]
101
+ return f
102
+
103
+
104
+ def load_dotenv(path: str | os.PathLike[str] | None = None, stream: t.IO[str] | None = None) -> bool:
105
+ """Load the ``.env`` file, when python-dotenv is installed."""
106
+ try:
107
+ from dotenv import load_dotenv as _load_dotenv
108
+ except ImportError:
109
+ return False
110
+
111
+ return bool(_load_dotenv(path, stream=stream))
112
+
113
+
114
+ def get_version() -> str:
115
+ """Return the version of the framework the CLI ships with."""
116
+ try:
117
+ from pboot.core._internal.version import __version__
118
+ except Exception: # pragma: no cover
119
+ try:
120
+ from importlib.metadata import version
121
+ except ImportError: # pragma: no cover
122
+ return "0.0.0"
123
+ return version("pboot")
124
+
125
+ return __version__
126
+
127
+
128
+ def show_server_banner(debug: bool, app_import_path: str | None) -> None:
129
+ """Print the banner shown when the server starts."""
130
+ if app_import_path is not None:
131
+ message = f" * Serving Pboot app {app_import_path!r}"
132
+ else:
133
+ message = " * Serving Pboot app"
134
+
135
+ if debug:
136
+ message += " (debug mode)"
137
+
138
+ print(message)
139
+
140
+
141
+ def _use_utf8_output() -> None:
142
+ """Force UTF-8 on the console streams."""
143
+ for stream in (sys.stdout, sys.stderr):
144
+ reconfigure = getattr(stream, "reconfigure", None)
145
+
146
+ if reconfigure is None: # pragma: no cover
147
+ continue
148
+
149
+ try:
150
+ reconfigure(encoding="utf-8", errors="replace")
151
+ except Exception: # pragma: no cover
152
+ pass
153
+
154
+
155
+ def _common_options() -> argparse.ArgumentParser:
156
+ """Options accepted both before and after the subcommand."""
157
+ common = argparse.ArgumentParser(add_help=False)
158
+ common.add_argument(
159
+ "--app",
160
+ dest="import_name",
161
+ metavar="MODULE:ATTR",
162
+ default=argparse.SUPPRESS,
163
+ help="The application to load, in the form 'module:attribute'.",
164
+ )
165
+ common.add_argument(
166
+ "--debug",
167
+ dest="debug",
168
+ action="store_true",
169
+ default=argparse.SUPPRESS,
170
+ help="Run with debug mode.",
171
+ )
172
+ common.add_argument(
173
+ "--no-debug",
174
+ dest="debug",
175
+ action="store_false",
176
+ default=argparse.SUPPRESS,
177
+ help="Run without debug mode.",
178
+ )
179
+ return common
180
+
181
+
182
+ def build_parser(app: t.Any = None, prog: str = "pboot") -> argparse.ArgumentParser:
183
+ """Build the argument parser, including the application's own commands."""
184
+ common = _common_options()
185
+ parser = argparse.ArgumentParser(
186
+ prog=prog,
187
+ description="The Pboot command line interface.",
188
+ parents=[common],
189
+ )
190
+ parser.add_argument("--version", action=_VersionAction, help="Show the version and exit.")
191
+
192
+ subparsers = parser.add_subparsers(dest="command", metavar="COMMAND")
193
+
194
+ run = subparsers.add_parser(
195
+ "run",
196
+ help="Run the development server.",
197
+ description="Run the development server.",
198
+ parents=[common],
199
+ )
200
+ run.add_argument("--host", default="127.0.0.1", help="The interface to bind to.")
201
+ run.add_argument("--port", type=int, default=8000, help="The port to bind to.")
202
+ run.add_argument("--reload", action="store_true", help="Reload on code changes.")
203
+ run.add_argument("--workers", type=int, default=None, help="Number of worker processes.")
204
+ run.add_argument("--root-path", default="", help="The ASGI root path the application is served from.")
205
+ run.set_defaults(_builtin=run_command)
206
+
207
+ routes = subparsers.add_parser(
208
+ "routes",
209
+ help="Show the registered routes.",
210
+ description="Show the registered routes.",
211
+ parents=[common],
212
+ )
213
+ routes.add_argument("--sort", "-s", choices=["endpoint", "methods", "rule"], default="endpoint")
214
+ routes.add_argument("--all-methods", "-a", action="store_true", help="Show every HTTP method.")
215
+ routes.set_defaults(_builtin=routes_command)
216
+
217
+ shell = subparsers.add_parser(
218
+ "shell",
219
+ help="Run a shell in the application context.",
220
+ description="Run a shell in the application context.",
221
+ parents=[common],
222
+ )
223
+ shell.set_defaults(_builtin=shell_command)
224
+
225
+ if app is not None:
226
+ app_group = getattr(app, "cli", None)
227
+
228
+ if isinstance(app_group, AppGroup):
229
+ for name, command in app_group.commands.items():
230
+ sub = subparsers.add_parser(
231
+ name,
232
+ help=command.help.splitlines()[0] if command.help else None,
233
+ description=command.help or None,
234
+ parents=[common],
235
+ )
236
+ sub.set_defaults(_command=command)
237
+
238
+ return parser
239
+
240
+
241
+ def _prescan_app(argv: t.Sequence[str]) -> str | None:
242
+ """Find ``--app`` before the parser exists.
243
+
244
+ The application's own commands have to be known while building the
245
+ subparsers, so the value is read in a first pass.
246
+ """
247
+ for index, argument in enumerate(argv):
248
+ if argument == "--app" and index + 1 < len(argv):
249
+ return argv[index + 1]
250
+
251
+ if argument.startswith("--app="):
252
+ return argument.partition("=")[2]
253
+
254
+ return None
255
+
256
+
257
+ def _resolve_debug(ns: argparse.Namespace) -> bool:
258
+ value = getattr(ns, "debug", None)
259
+
260
+ if value is not None:
261
+ return bool(value)
262
+
263
+ env = os.environ.get("PBOOT_DEBUG", "")
264
+ return env.strip().lower() in _TRUE
265
+
266
+
267
+ def main(argv: t.Sequence[str] | None = None, prog: str = "pboot") -> int:
268
+ """Entry point of the ``pboot`` command.
269
+
270
+ :return: The process exit code.
271
+ """
272
+ _use_utf8_output()
273
+
274
+ args = list(sys.argv[1:] if argv is None else argv)
275
+ import_name = _prescan_app(args) or os.environ.get("PBOOT_APP") or None
276
+
277
+ app = None
278
+ load_error: NoAppException | None = None
279
+
280
+ if import_name:
281
+ try:
282
+ app = load_app(import_name)
283
+ except NoAppException as e:
284
+ load_error = e
285
+
286
+ parser = build_parser(app, prog=prog)
287
+
288
+ try:
289
+ ns, extras = parser.parse_known_args(args)
290
+ except SystemExit as e: # --help / --version / usage errors
291
+ return int(e.code or 0)
292
+
293
+ ns.import_name = getattr(ns, "import_name", None) or import_name
294
+ ns.debug = _resolve_debug(ns)
295
+
296
+ command = getattr(ns, "command", None)
297
+
298
+ if command is None:
299
+ parser.print_help()
300
+ return 2
301
+
302
+ builtin = getattr(ns, "_builtin", None)
303
+
304
+ if builtin is not None:
305
+ if extras:
306
+ return error(f"unrecognized arguments: {' '.join(extras)}")
307
+
308
+ if app is None:
309
+ return error(
310
+ str(load_error)
311
+ if load_error is not None
312
+ else "Could not locate a Pboot application. Use the '--app' option, or set the PBOOT_APP environment variable."
313
+ )
314
+
315
+ return builtin(app, ns)
316
+
317
+ command_obj: Command = getattr(ns, "_command")
318
+
319
+ if app is None:
320
+ return error(str(load_error) if load_error else "Could not locate a Pboot application.")
321
+
322
+ return _run_app_command(app, command_obj, extras)
323
+
324
+
325
+ def _run_app_command(app: t.Any, command: Command, argv: list[str]) -> int:
326
+ """Call a command registered with ``@app.cli.command()``."""
327
+ if command.takes_argv:
328
+ call: t.Callable[[], t.Any] = lambda: command.func(argv) # noqa: E731
329
+ elif argv:
330
+ return error(f"{command.name} does not take arguments: {' '.join(argv)}")
331
+ else:
332
+ call = command.func
333
+
334
+ if command.with_appcontext and hasattr(app, "app_context"):
335
+ with app.app_context():
336
+ result = call()
337
+ else:
338
+ result = call()
339
+
340
+ return int(result) if isinstance(result, int) else 0
341
+
342
+
343
+ #: The entry point of the ``pboot`` command.
344
+ cli = main
345
+
346
+
347
+ if __name__ == "__main__": # pragma: no cover
348
+ sys.exit(main())
pboot/cli/_app.py ADDED
@@ -0,0 +1,205 @@
1
+ """Finding and loading the application a command should run against."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import os
7
+ import sys
8
+ import typing as t
9
+
10
+ if t.TYPE_CHECKING: # pragma: no cover
11
+ from pboot.core.app import Pboot
12
+
13
+
14
+ class NoAppException(Exception):
15
+ """Raised when no application could be found."""
16
+
17
+ exit_code = 2
18
+
19
+
20
+ def _app_class() -> type:
21
+ """Import ``Pboot`` lazily.
22
+
23
+ This distribution deliberately does not depend on pboot at import time:
24
+ pboot depends on it, and both live in the same ``pboot`` namespace.
25
+ """
26
+ from pboot.core.app import Pboot
27
+
28
+ return Pboot
29
+
30
+
31
+ def find_best_app(module: t.Any) -> Pboot:
32
+ """Find the best application in the given module.
33
+
34
+ The module must expose ``app``, ``application``, a ``Pboot`` subclass, or
35
+ a zero-argument callable returning one.
36
+ """
37
+ Pboot = _app_class()
38
+ candidates: list[t.Any] = []
39
+
40
+ for name in ("app", "application"):
41
+ candidate = getattr(module, name, None)
42
+
43
+ if candidate is None:
44
+ continue
45
+
46
+ if isinstance(candidate, Pboot):
47
+ return candidate
48
+
49
+ if isinstance(candidate, type) and issubclass(candidate, Pboot):
50
+ return candidate()
51
+
52
+ candidates.append(candidate)
53
+
54
+ for candidate in candidates:
55
+ if callable(candidate):
56
+ try:
57
+ app = candidate()
58
+ except TypeError: # pragma: no cover
59
+ continue
60
+
61
+ if isinstance(app, Pboot):
62
+ return app
63
+
64
+ for name in dir(module):
65
+ candidate = getattr(module, name, None)
66
+
67
+ if isinstance(candidate, Pboot):
68
+ return candidate
69
+
70
+ raise NoAppException(
71
+ "Failed to find a Pboot application in the given module. Use"
72
+ " 'Pboot(__name__)' or name the application 'app'."
73
+ )
74
+
75
+
76
+ def prepare_import(path: str) -> str:
77
+ """Normalize the ``--app`` value to an import string."""
78
+ path = path.replace("\\", "/")
79
+
80
+ if path.startswith("."):
81
+ raise NoAppException(
82
+ "The app path must not start with a '.', it must be an import"
83
+ " path such as 'myapp.app:app'."
84
+ )
85
+
86
+ if ":" in path:
87
+ module, _, attr = path.partition(":")
88
+
89
+ if not module or not attr:
90
+ raise NoAppException("The app path must be in the form 'module:attribute' or 'module'.")
91
+
92
+ return f"{module}:{attr}"
93
+
94
+ return path
95
+
96
+
97
+ def ensure_cwd_importable() -> None:
98
+ """Make the current working directory importable.
99
+
100
+ Console scripts do not put the working directory on ``sys.path``, so
101
+ ``pboot --app app routes`` would not find ``app.py`` otherwise.
102
+ """
103
+ cwd = os.getcwd()
104
+
105
+ if cwd not in sys.path:
106
+ sys.path.insert(0, cwd)
107
+
108
+
109
+ def find_app_attribute(module: t.Any) -> str:
110
+ """Find the name of the application attribute in the given module."""
111
+ Pboot = _app_class()
112
+
113
+ for name in ("app", "application"):
114
+ if isinstance(getattr(module, name, None), Pboot):
115
+ return name
116
+
117
+ for name in dir(module):
118
+ if isinstance(getattr(module, name, None), Pboot):
119
+ return name
120
+
121
+ raise NoAppException(
122
+ "Failed to find a Pboot application in the given module. Use"
123
+ " 'Pboot(__name__)' or name the application 'app'."
124
+ )
125
+
126
+
127
+ def resolve_import_string(import_string: str) -> tuple[str, bool]:
128
+ """Normalize an import string to ``module:attribute``.
129
+
130
+ :return: The import string and whether the attribute looks like a factory.
131
+ """
132
+ Pboot = _app_class()
133
+
134
+ ensure_cwd_importable()
135
+
136
+ module_name, _, attr_name = import_string.partition(":")
137
+
138
+ if attr_name:
139
+ module = importlib.import_module(module_name)
140
+ candidate = getattr(module, attr_name, None)
141
+ is_factory = not isinstance(candidate, Pboot) and callable(candidate)
142
+ return import_string, is_factory
143
+
144
+ module = importlib.import_module(module_name)
145
+ attr_name = find_app_attribute(module)
146
+ return f"{module_name}:{attr_name}", False
147
+
148
+
149
+ def load_app(import_string: str) -> Pboot:
150
+ """Load the application from the given import string."""
151
+ ensure_cwd_importable()
152
+
153
+ import_string = prepare_import(import_string)
154
+ module_name, _, attr_name = import_string.partition(":")
155
+
156
+ try:
157
+ module = importlib.import_module(module_name)
158
+ except ImportError as e:
159
+ raise NoAppException(f"Could not import {module_name!r}: {e}") from None
160
+
161
+ if not attr_name:
162
+ return find_best_app(module)
163
+
164
+ try:
165
+ app = getattr(module, attr_name)
166
+ except AttributeError:
167
+ raise NoAppException(f"Failed to find attribute {attr_name!r} in {module_name!r}.") from None
168
+
169
+ if isinstance(app, type):
170
+ app = app()
171
+
172
+ if not hasattr(app, "router"):
173
+ raise NoAppException(f"{import_string!r} does not look like a Pboot application.")
174
+
175
+ return t.cast("Pboot", app)
176
+
177
+
178
+ def locate_app(module: t.Any) -> Pboot | None:
179
+ """Find the application in the given module, if there is one."""
180
+ Pboot = _app_class()
181
+
182
+ for name in ("app", "application"):
183
+ candidate = getattr(module, name, None)
184
+
185
+ if isinstance(candidate, Pboot):
186
+ return candidate
187
+
188
+ if isinstance(candidate, type) and issubclass(candidate, Pboot):
189
+ return candidate()
190
+
191
+ return None
192
+
193
+
194
+ def find_app_by_string(module: t.Any, app_name: str) -> Pboot | None:
195
+ """Find the application in the module by attribute name."""
196
+ Pboot = _app_class()
197
+ candidate = getattr(module, app_name, None)
198
+
199
+ if isinstance(candidate, Pboot):
200
+ return candidate
201
+
202
+ if isinstance(candidate, type) and issubclass(candidate, Pboot):
203
+ return candidate()
204
+
205
+ return None
pboot/cli/_commands.py ADDED
@@ -0,0 +1,107 @@
1
+ """The built-in subcommands: ``run``, ``routes`` and ``shell``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ import typing as t
7
+
8
+ from ._app import NoAppException, resolve_import_string
9
+
10
+ if t.TYPE_CHECKING: # pragma: no cover
11
+ from pboot.core.app import Pboot
12
+
13
+ __all__ = ["error", "run_command", "routes_command", "shell_command"]
14
+
15
+
16
+ def error(message: str) -> int:
17
+ """Report a command failure the way the CLI has always done."""
18
+ print(f"Error: {message}", file=sys.stderr)
19
+ return 1
20
+
21
+
22
+ def run_command(app: Pboot, ns: t.Any) -> int:
23
+ """Run the application with an ASGI server."""
24
+ try:
25
+ import uvicorn
26
+ except ImportError: # pragma: no cover
27
+ return error('The "uvicorn" package is required. Install it with "pip install pboot[standard]".')
28
+
29
+ root_path = getattr(ns, "root_path", "") or ""
30
+
31
+ if root_path:
32
+ app.root_path = root_path
33
+
34
+ if getattr(ns, "debug", None):
35
+ app.debug = True
36
+
37
+ print(f" * Running on http://{ns.host}:{ns.port}{root_path}")
38
+
39
+ if ns.reload:
40
+ import_string = getattr(ns, "import_name", None)
41
+
42
+ if not import_string:
43
+ return error("Reloading requires the application to be importable by name.")
44
+
45
+ try:
46
+ import_string, is_factory = resolve_import_string(import_string)
47
+ except NoAppException as e:
48
+ return error(str(e))
49
+
50
+ uvicorn.run(import_string, host=ns.host, port=ns.port, reload=True, workers=ns.workers, factory=is_factory)
51
+ else:
52
+ uvicorn.run(app, host=ns.host, port=ns.port, workers=ns.workers)
53
+
54
+ return 0
55
+
56
+
57
+ def routes_command(app: Pboot, ns: t.Any) -> int:
58
+ """Print the registered routes."""
59
+ from pboot.core.routing import iter_route_contexts
60
+
61
+ rows: list[tuple[str, str, str]] = []
62
+
63
+ for context in iter_route_contexts(app.router.routes):
64
+ path = context.path
65
+
66
+ if not path:
67
+ continue
68
+
69
+ methods = sorted(getattr(context.original_route, "methods", None) or [])
70
+ name = context.name or ""
71
+
72
+ if ns.all_methods:
73
+ shown = methods
74
+ else:
75
+ shown = [m for m in methods if m not in {"HEAD", "OPTIONS"}] or methods
76
+
77
+ for method in shown:
78
+ rows.append((method, path, name))
79
+
80
+ if ns.sort == "methods":
81
+ rows.sort(key=lambda row: (row[0], row[1]))
82
+ elif ns.sort == "rule":
83
+ rows.sort(key=lambda row: (row[1], row[0]))
84
+ else:
85
+ rows.sort(key=lambda row: (row[2], row[1]))
86
+
87
+ widths = [max((len(row[i]) for row in rows), default=0) for i in range(3)]
88
+
89
+ for method, path, name in rows:
90
+ print(f"{method:<{widths[0]}} {path:<{widths[1]}} {name:<{widths[2]}}")
91
+
92
+ return 0
93
+
94
+
95
+ def shell_command(app: Pboot, ns: t.Any) -> int:
96
+ """Start an interactive shell with the application context pushed."""
97
+ import code
98
+
99
+ with app.app_context():
100
+ banner = (
101
+ f"Python {sys.version} on {sys.platform}\n"
102
+ f"App: {app.name}\n"
103
+ f"App path: {app.app_root_path}\n"
104
+ )
105
+ code.interact(banner=banner, local=app.make_shell_context())
106
+
107
+ return 0
pboot/cli/_group.py ADDED
@@ -0,0 +1,96 @@
1
+ """Application command groups, the argparse counterpart of ``app.cli``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import typing as t
7
+ from dataclasses import dataclass
8
+
9
+ __all__ = ["AppGroup", "Command"]
10
+
11
+
12
+ @dataclass
13
+ class Command:
14
+ """A command registered on an application.
15
+
16
+ ``takes_argv`` commands receive the arguments that argparse did not
17
+ consume (``def seed(argv): ...``), everything else is called with no
18
+ arguments. That keeps the decorator free of a CLI framework.
19
+ """
20
+
21
+ name: str
22
+ func: t.Callable[..., t.Any]
23
+ help: str = ""
24
+ with_appcontext: bool = True
25
+ takes_argv: bool = False
26
+ is_group: bool = False
27
+
28
+
29
+ def _accepts_argv(func: t.Callable[..., t.Any]) -> bool:
30
+ try:
31
+ parameters = inspect.signature(func).parameters.values()
32
+ except (TypeError, ValueError): # pragma: no cover
33
+ return False
34
+
35
+ for parameter in parameters:
36
+ if parameter.name == "argv" or parameter.kind is parameter.VAR_POSITIONAL:
37
+ return True
38
+
39
+ return False
40
+
41
+
42
+ class AppGroup:
43
+ """Holds the commands an application exposes to the ``pboot`` command."""
44
+
45
+ def __init__(self, name: str | None = None) -> None:
46
+ self.name = name
47
+ self.commands: dict[str, Command] = {}
48
+
49
+ def add_command(self, command: Command, name: str | None = None) -> Command:
50
+ self.commands[name or command.name] = command
51
+ return command
52
+
53
+ def command(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
54
+ """Register a command.
55
+
56
+ Usable as ``@app.cli.command``, ``@app.cli.command()`` or
57
+ ``@app.cli.command("seed")``.
58
+ """
59
+ name = kwargs.pop("name", None)
60
+ help_text = kwargs.pop("help", None)
61
+ with_appcontext = kwargs.pop("with_appcontext", True)
62
+
63
+ if kwargs:
64
+ raise TypeError(f"Unexpected keyword arguments: {', '.join(sorted(kwargs))}")
65
+
66
+ func: t.Callable[..., t.Any] | None = None
67
+
68
+ if len(args) == 1 and callable(args[0]):
69
+ func = args[0]
70
+ elif len(args) == 1 and isinstance(args[0], str):
71
+ name = args[0]
72
+ elif len(args) > 1:
73
+ raise TypeError("command() takes at most one positional argument")
74
+
75
+ def decorator(f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
76
+ command = Command(
77
+ name=name or f.__name__.replace("_", "-"),
78
+ func=f,
79
+ help=help_text or inspect.getdoc(f) or "",
80
+ with_appcontext=with_appcontext,
81
+ takes_argv=_accepts_argv(f),
82
+ )
83
+ self.add_command(command)
84
+ return f
85
+
86
+ return decorator(func) if func is not None else decorator
87
+
88
+ def group(self, *args: t.Any, **kwargs: t.Any) -> t.Any:
89
+ """Register a command that is conceptually a subgroup.
90
+
91
+ Nested groups are not supported; the command is registered flat under
92
+ its own name so the call sites stay familiar.
93
+ """
94
+ kwargs.setdefault("with_appcontext", True)
95
+ decorator = self.command(*args, **kwargs)
96
+ return decorator
pboot/cli/testing.py ADDED
@@ -0,0 +1,122 @@
1
+ """A CLI test runner, so testing pboot commands needs no extra package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import io
7
+ import os
8
+ import shlex
9
+ import sys
10
+ import typing as t
11
+
12
+ __all__ = ["CliResult", "CliRunner"]
13
+
14
+
15
+ class CliResult:
16
+ """The outcome of :meth:`CliRunner.invoke`."""
17
+
18
+ def __init__(
19
+ self,
20
+ exit_code: int,
21
+ output: str,
22
+ exception: BaseException | None = None,
23
+ return_value: t.Any = None,
24
+ ) -> None:
25
+ self.exit_code = exit_code
26
+ self.output = output
27
+ self.stdout = output
28
+ self.exception = exception
29
+ self.return_value = return_value
30
+
31
+ @property
32
+ def exc_info(self) -> tuple[type[BaseException], BaseException, t.Any] | None:
33
+ if self.exception is None:
34
+ return None
35
+ return type(self.exception), self.exception, self.exception.__traceback__
36
+
37
+ def __repr__(self) -> str: # pragma: no cover
38
+ return f"<CliResult exit_code={self.exit_code} output={self.output!r}>"
39
+
40
+
41
+ class CliRunner:
42
+ """Runs a CLI entry point in-process and captures what it printed."""
43
+
44
+ def __init__(
45
+ self,
46
+ charset: str = "utf-8",
47
+ env: dict[str, str | None] | None = None,
48
+ echo_stdin: bool = False,
49
+ catch_exceptions: bool = True,
50
+ ) -> None:
51
+ self.charset = charset
52
+ self.env = env or {}
53
+ self.echo_stdin = echo_stdin
54
+ self.catch_exceptions = catch_exceptions
55
+
56
+ def invoke(
57
+ self,
58
+ cli: t.Callable[..., t.Any],
59
+ args: str | t.Sequence[str] | None = None,
60
+ **kwargs: t.Any,
61
+ ) -> CliResult:
62
+ """Run ``cli`` with ``args`` and return its result."""
63
+ argv = shlex.split(args) if isinstance(args, str) else list(args or [])
64
+
65
+ saved_env = {key: os.environ.get(key) for key in self.env}
66
+
67
+ for key, value in self.env.items():
68
+ if value is None:
69
+ os.environ.pop(key, None)
70
+ else:
71
+ os.environ[key] = value
72
+
73
+ stream = io.StringIO()
74
+ exit_code = 0
75
+ exception: BaseException | None = None
76
+ return_value: t.Any = None
77
+
78
+ try:
79
+ with contextlib.redirect_stdout(stream), contextlib.redirect_stderr(stream):
80
+ try:
81
+ return_value = cli(argv)
82
+ exit_code = int(return_value) if isinstance(return_value, int) else 0
83
+ except SystemExit as e:
84
+ code = e.code
85
+ exit_code = int(code) if isinstance(code, int) else (0 if code is None else 1)
86
+ except BaseException as e: # noqa: BLE001
87
+ if not self.catch_exceptions:
88
+ raise
89
+ exception = e
90
+ exit_code = 1
91
+ finally:
92
+ for key, value in saved_env.items():
93
+ if value is not None:
94
+ os.environ[key] = value
95
+
96
+ return CliResult(exit_code, stream.getvalue(), exception, return_value)
97
+
98
+ def isolated_filesystem(self, temp_dir: str | None = None) -> t.ContextManager[str]: # pragma: no cover
99
+ """A convenience wrapper kept for symmetry with other runners."""
100
+ return _IsolatedFilesystem(temp_dir)
101
+
102
+
103
+ class _IsolatedFilesystem: # pragma: no cover
104
+ def __init__(self, temp_dir: str | None = None) -> None:
105
+ import tempfile
106
+
107
+ self._temp_dir = temp_dir
108
+ self._previous: str | None = None
109
+
110
+ def __enter__(self) -> str:
111
+ import tempfile
112
+
113
+ self._previous = os.getcwd()
114
+ self._path = self._temp_dir or tempfile.mkdtemp()
115
+ os.chdir(self._path)
116
+ with contextlib.suppress(KeyError):
117
+ sys.path.remove(self._previous)
118
+ return self._path
119
+
120
+ def __exit__(self, *args: t.Any) -> None:
121
+ if self._previous is not None:
122
+ os.chdir(self._previous)
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: pboot-cli
3
+ Version: 1.0.0
4
+ Summary: The pboot command line interface, built on argparse.
5
+ Project-URL: Source, https://gitee.com/pboot-org/pboot-cli
6
+ Project-URL: Homepage, https://gitee.com/pboot-org/pboot
7
+ Maintainer: pboot-org
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE.md
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Software Development :: User Interfaces
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+
21
+ # pboot-cli
22
+
23
+ The `pboot` command line interface, built on `argparse`.
24
+
25
+ This distribution is what `pboot` installs so the `pboot` command exists. It
26
+ has no runtime dependencies of its own: `argparse`, `importlib` and `inspect`
27
+ from the standard library are all it uses to parse arguments, find the
28
+ application and dispatch a command.
29
+
30
+ ## Commands
31
+
32
+ ```
33
+ pboot [--app MODULE:ATTR] [--debug] COMMAND
34
+ ```
35
+
36
+ - `run` — serve the application with uvicorn (`--host`, `--port`, `--reload`,
37
+ `--workers`, `--root-path`).
38
+ - `routes` — print the routing table (`--sort endpoint|methods|rule`,
39
+ `--all-methods`).
40
+ - `shell` — an interactive shell with the application context pushed.
41
+
42
+ The application is taken from `--app`, then `PBOOT_APP`, then `app` in the
43
+ current directory.
44
+
45
+ ## Application commands
46
+
47
+ Commands registered on an application are added as subcommands:
48
+
49
+ ```python
50
+ @app.cli.command()
51
+ def seed():
52
+ """Fill the database."""
53
+
54
+
55
+ @app.cli.command("echo")
56
+ def echo(argv):
57
+ """Receives the arguments argparse did not consume."""
58
+ print(" ".join(argv))
59
+ ```
60
+
61
+ A command whose signature has `argv` (or `*args`) receives the leftover
62
+ arguments and parses them with `argparse` itself; every other command takes no
63
+ arguments. Commands run inside the application context by default.
64
+
65
+ ## Testing
66
+
67
+ `pboot.cli.testing.CliRunner` runs a command in-process and captures its
68
+ output, so no third-party test runner is needed:
69
+
70
+ ```python
71
+ from pboot.cli import main
72
+ from pboot.cli.testing import CliRunner
73
+
74
+ result = CliRunner().invoke(main, ["--app", "myapp:app", "routes"])
75
+ assert result.exit_code == 0
76
+ ```
@@ -0,0 +1,9 @@
1
+ pboot/cli/__init__.py,sha256=far6fkBMjmCVMY8ILQX88STM5MaIpO71qO4MhSyHAnY,10323
2
+ pboot/cli/_app.py,sha256=wNbjBeS2z9jHDCz92Oyd-Rm7AgF_OzP5ykU6I2tMZZ8,5691
3
+ pboot/cli/_commands.py,sha256=C-UwRepSGCFz5xcMVF2V1uUbvOGG2r1XuvBY0fJdmg0,3108
4
+ pboot/cli/_group.py,sha256=JJln0ZnnSazb4GULDWg6M99TxY5fb7WRcJjdvazQYWY,3088
5
+ pboot/cli/testing.py,sha256=V_SXnK-uyPRcCaeBYJb0Wo-TenkG0DqbsynmRrnPwcY,3872
6
+ pboot_cli-1.0.0.dist-info/METADATA,sha256=uzlALrQkkmBAKt6amwcslbpqiUn8mGVns1sQbgAIoxc,2322
7
+ pboot_cli-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ pboot_cli-1.0.0.dist-info/licenses/LICENSE.md,sha256=3LlWd6AiQCQxh-lk-UGEfRmxeCHPmeWvrmhPqzKMGb8,1518
9
+ pboot_cli-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,27 @@
1
+ Copyright © 2018, [Encode OSS Ltd](https://www.encode.io/).
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.