rn-forge-cli 0.1.2__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rohit Narayanan
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,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: rn-forge-cli
3
+ Version: 0.1.2
4
+ Summary: The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes
5
+ Author: Rohit Narayanan
6
+ Author-email: Rohit Narayanan <rohit.nn@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: rn-forge-commons>=0.8.0,<0.9
17
+ Requires-Dist: rich>=15.0.0
18
+ Requires-Dist: typer>=0.26.8
19
+ Requires-Dist: assertpy>=1.1 ; extra == 'testing'
20
+ Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
21
+ Requires-Python: >=3.14
22
+ Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/
23
+ Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli
24
+ Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-cli/CHANGELOG.md
25
+ Project-URL: Issues, https://github.com/rn-forge/pykit/issues
26
+ Provides-Extra: testing
27
+ Description-Content-Type: text/markdown
28
+
29
+ # rn-forge-cli
30
+
31
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/)
32
+ ·
33
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-cli/CHANGELOG.md)
34
+ · [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli) ·
35
+ [All pykit packages](https://rn-forge.github.io/pykit/)
36
+
37
+ The shared command-line layer for `rn-forge-*` applications: the Typer
38
+ application class, the standard option set and the error-to-exit-code mapping.
39
+
40
+ Where
41
+ [`rn-forge-commons`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons)
42
+ is runtime-neutral — safe in a web server, a worker or a container — this
43
+ package is the *command-line shape*. An ordinary batch application wants it just
44
+ as much as a developer tool does, which is why it is separate from
45
+ [`rn-forge-tooling`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling),
46
+ the package that owns files, installs and rendering. It owns:
47
+
48
+ - `app` — `CliApp`, a `typer.Typer` subclass wiring the standard options into
49
+ logging and the console; `ExitCode`; and `run`, which applies the mapping to
50
+ any Typer app. Calling a `CliApp` returns an exit code, so
51
+ `[project.scripts]` points straight at the app object.
52
+ - `options` — `--log-level`, `--log-file`, `--quiet`, `--json`, `--dry-run`,
53
+ `--yes`, `--set`, `CliOptions` and `parse_overrides`.
54
+ - `surface` — `CliSurface`/`CommandSurface`, the records behind a `[cli]` table
55
+ in a config file, from which `CliApp.from_config` builds the app. Validated
56
+ on load: a wrong type names the offending key.
57
+
58
+ Console output is **not** here — `AppConsole` lives in `rn-forge-commons`,
59
+ because it is a property of the process rather than of the command-line parser,
60
+ and `rn_forge.django` may not import this package to reach one. This package
61
+ drives it: `--quiet`/`--json` set its mode.
62
+
63
+ `rn_forge.cli` may import `rn_forge.commons`. It must never import
64
+ `rn_forge.tooling`, and `rn_forge.commons` must never import either —
65
+ `.importlinter` proves all three.
66
+
67
+ ## Installation
68
+
69
+ Require the package by version range:
70
+
71
+ ```toml
72
+ dependencies = ["rn-forge-cli>=0.1,<0.2"]
73
+ ```
74
+
75
+ ## Usage
76
+
77
+ ```python
78
+ from rn_forge.cli import CliApp
79
+ from rn_forge.commons import console
80
+
81
+ app = CliApp("golden-app", "Do the thing.")
82
+
83
+
84
+ @app.command()
85
+ def greet(name: str) -> None:
86
+ """Greet someone."""
87
+ console.success("Hello, {}", name)
88
+ ```
89
+
90
+ ```toml
91
+ [project.scripts]
92
+ golden-app = "golden_app.cli:app"
93
+ ```
94
+
95
+ There is no `main()`: a generated console script is `sys.exit(app())`, and
96
+ `CliApp.__call__` returns the mapped exit code.
97
+
98
+ Or declare the commands in a `[cli]` table and build the app from it:
99
+
100
+ ```python
101
+ app = CliApp.from_config("cli.toml")
102
+ ```
@@ -0,0 +1,74 @@
1
+ # rn-forge-cli
2
+
3
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/)
4
+ ·
5
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-cli/CHANGELOG.md)
6
+ · [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli) ·
7
+ [All pykit packages](https://rn-forge.github.io/pykit/)
8
+
9
+ The shared command-line layer for `rn-forge-*` applications: the Typer
10
+ application class, the standard option set and the error-to-exit-code mapping.
11
+
12
+ Where
13
+ [`rn-forge-commons`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons)
14
+ is runtime-neutral — safe in a web server, a worker or a container — this
15
+ package is the *command-line shape*. An ordinary batch application wants it just
16
+ as much as a developer tool does, which is why it is separate from
17
+ [`rn-forge-tooling`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling),
18
+ the package that owns files, installs and rendering. It owns:
19
+
20
+ - `app` — `CliApp`, a `typer.Typer` subclass wiring the standard options into
21
+ logging and the console; `ExitCode`; and `run`, which applies the mapping to
22
+ any Typer app. Calling a `CliApp` returns an exit code, so
23
+ `[project.scripts]` points straight at the app object.
24
+ - `options` — `--log-level`, `--log-file`, `--quiet`, `--json`, `--dry-run`,
25
+ `--yes`, `--set`, `CliOptions` and `parse_overrides`.
26
+ - `surface` — `CliSurface`/`CommandSurface`, the records behind a `[cli]` table
27
+ in a config file, from which `CliApp.from_config` builds the app. Validated
28
+ on load: a wrong type names the offending key.
29
+
30
+ Console output is **not** here — `AppConsole` lives in `rn-forge-commons`,
31
+ because it is a property of the process rather than of the command-line parser,
32
+ and `rn_forge.django` may not import this package to reach one. This package
33
+ drives it: `--quiet`/`--json` set its mode.
34
+
35
+ `rn_forge.cli` may import `rn_forge.commons`. It must never import
36
+ `rn_forge.tooling`, and `rn_forge.commons` must never import either —
37
+ `.importlinter` proves all three.
38
+
39
+ ## Installation
40
+
41
+ Require the package by version range:
42
+
43
+ ```toml
44
+ dependencies = ["rn-forge-cli>=0.1,<0.2"]
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from rn_forge.cli import CliApp
51
+ from rn_forge.commons import console
52
+
53
+ app = CliApp("golden-app", "Do the thing.")
54
+
55
+
56
+ @app.command()
57
+ def greet(name: str) -> None:
58
+ """Greet someone."""
59
+ console.success("Hello, {}", name)
60
+ ```
61
+
62
+ ```toml
63
+ [project.scripts]
64
+ golden-app = "golden_app.cli:app"
65
+ ```
66
+
67
+ There is no `main()`: a generated console script is `sys.exit(app())`, and
68
+ `CliApp.__call__` returns the mapped exit code.
69
+
70
+ Or declare the commands in a `[cli]` table and build the app from it:
71
+
72
+ ```python
73
+ app = CliApp.from_config("cli.toml")
74
+ ```
@@ -0,0 +1,72 @@
1
+ [project]
2
+ name = "rn-forge-cli"
3
+ version = "0.1.2"
4
+ description = "The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ classifiers = [
9
+ "Development Status :: 3 - Alpha",
10
+ "Intended Audience :: Developers",
11
+ "Operating System :: OS Independent",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3 :: Only",
14
+ "Programming Language :: Python :: 3.14",
15
+ "Typing :: Typed",
16
+ ]
17
+ requires-python = ">=3.14"
18
+ dependencies = [
19
+ "rn-forge-commons>=0.8.0,<0.9",
20
+ "rich>=15.0.0",
21
+ "typer>=0.26.8",
22
+ ]
23
+
24
+ [[project.authors]]
25
+ name = "Rohit Narayanan"
26
+ email = "rohit.nn@gmail.com"
27
+
28
+ [project.optional-dependencies]
29
+ testing = [
30
+ "assertpy>=1.1",
31
+ "pytest>=9.1.1",
32
+ ]
33
+
34
+ [project.urls]
35
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/"
36
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli"
37
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-cli/CHANGELOG.md"
38
+ Issues = "https://github.com/rn-forge/pykit/issues"
39
+
40
+ [build-system]
41
+ requires = ["uv_build>=0.11.28,<0.12.0"]
42
+ build-backend = "uv_build"
43
+
44
+ [tool.uv.build-backend]
45
+ module-name = "rn_forge.cli"
46
+
47
+ [tool.uv.sources.rn-forge-commons]
48
+ workspace = true
49
+
50
+ [tool.uv.sources.rn-forge-cli]
51
+ workspace = true
52
+
53
+ [tool.pytest.ini_options]
54
+ addopts = "-ra --import-mode=importlib -m 'not scaffold'"
55
+ markers = ["scaffold: installs built wheels into a scaffolded application (slow)"]
56
+
57
+ [dependency-groups]
58
+ dev = [
59
+ "assertpy>=1.1",
60
+ "pyright>=1.1.411",
61
+ "pytest>=9.1.1",
62
+ "pytest-cov>=7.1.0",
63
+ "pytest-randomly>=4.1.0",
64
+ "rn-forge-cli",
65
+ "ruff>=0.15.21",
66
+ ]
67
+ docs = [
68
+ "mkdocs>=1.6.1",
69
+ "mkdocs-material>=9.7.6",
70
+ "mkdocstrings[python]>=1.0.6",
71
+ "rn-forge-cli",
72
+ ]
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "rn-forge-cli"
3
+ version = "0.1.2"
4
+ description = "The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes"
5
+ readme = "README.md"
6
+ authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "Operating System :: OS Independent",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3 :: Only",
15
+ "Programming Language :: Python :: 3.14",
16
+ "Typing :: Typed",
17
+ ]
18
+ requires-python = ">=3.14"
19
+ # Internal requirements are version ranges (ADR-0004).
20
+ dependencies = [
21
+ "rn-forge-commons>=0.8.0,<0.9",
22
+ "rich>=15.0.0",
23
+ "typer>=0.26.8",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ testing = ["assertpy>=1.1", "pytest>=9.1.1"]
28
+
29
+ [project.urls]
30
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/"
31
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli"
32
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-cli/CHANGELOG.md"
33
+ Issues = "https://github.com/rn-forge/pykit/issues"
34
+
35
+ [build-system]
36
+ requires = ["uv_build>=0.11.28,<0.12.0"]
37
+ build-backend = "uv_build"
38
+
39
+ [tool.uv.build-backend]
40
+ module-name = "rn_forge.cli"
41
+
42
+ [tool.uv.sources]
43
+ rn-forge-commons = { workspace = true }
44
+ rn-forge-cli = { workspace = true }
45
+
46
+ [tool.pytest.ini_options]
47
+ addopts = "-ra --import-mode=importlib -m 'not scaffold'"
48
+ markers = ["scaffold: installs built wheels into a scaffolded application (slow)"]
49
+
50
+ [dependency-groups]
51
+ dev = [
52
+ "assertpy>=1.1",
53
+ "pyright>=1.1.411",
54
+ "pytest>=9.1.1",
55
+ "pytest-cov>=7.1.0",
56
+ "pytest-randomly>=4.1.0",
57
+ "rn-forge-cli",
58
+ "ruff>=0.15.21",
59
+ ]
60
+ docs = [
61
+ "mkdocs>=1.6.1",
62
+ "mkdocs-material>=9.7.6",
63
+ "mkdocstrings[python]>=1.0.6",
64
+ "rn-forge-cli",
65
+ ]
@@ -0,0 +1,34 @@
1
+ """Public command-line application, option, and surface APIs."""
2
+
3
+ from rn_forge.cli.app import CliApp, ExitCode, run
4
+ from rn_forge.cli.options import (
5
+ CliOptions,
6
+ DryRunOption,
7
+ JsonOption,
8
+ LogFileOption,
9
+ LogLevel,
10
+ LogLevelOption,
11
+ QuietOption,
12
+ SetOption,
13
+ YesOption,
14
+ parse_overrides,
15
+ )
16
+ from rn_forge.cli.surface import CliSurface, CommandSurface
17
+
18
+ __all__ = [
19
+ "CliApp",
20
+ "CliOptions",
21
+ "CliSurface",
22
+ "CommandSurface",
23
+ "DryRunOption",
24
+ "ExitCode",
25
+ "JsonOption",
26
+ "LogFileOption",
27
+ "LogLevel",
28
+ "LogLevelOption",
29
+ "QuietOption",
30
+ "SetOption",
31
+ "YesOption",
32
+ "parse_overrides",
33
+ "run",
34
+ ]
@@ -0,0 +1,251 @@
1
+ """Typer application setup and error-to-exit-code handling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from enum import IntEnum
7
+ from pathlib import Path
8
+ from typing import Any, Self
9
+
10
+ import typer
11
+ from rn_forge.cli.options import (
12
+ CliOptions,
13
+ JsonOption,
14
+ LogFileOption,
15
+ LogLevel,
16
+ LogLevelOption,
17
+ QuietOption,
18
+ )
19
+ from rn_forge.cli.surface import SURFACE_KEY, CliSurface, CommandSurface
20
+ from rn_forge.commons.exceptions import AppException
21
+ from rn_forge.commons.lang.utils import AppUtils
22
+ from rn_forge.commons.logging import AppLogger
23
+ from rn_forge.commons.runtime.console import console
24
+
25
+ # Typer 0.26 vendors Click, so `click.UsageError` and Typer's own are different
26
+ # classes and an `except click.UsageError` never fires. These are the ones a
27
+ # Typer command actually raises. The import is private, which is the cost of
28
+ # Typer not re-exporting them; the `typer>=0.26.8` floor is what pins it.
29
+ from typer._click.exceptions import ClickException, UsageError
30
+
31
+ __all__ = ["CliApp", "ExitCode", "run"]
32
+
33
+ _LOGGER = AppLogger.get_logger(__name__)
34
+
35
+
36
+ class ExitCode(IntEnum):
37
+ """Exit codes returned by an ``rn-forge`` CLI."""
38
+
39
+ OK = 0
40
+ """The command succeeded."""
41
+ FAILURE = 1
42
+ """The command ran and failed — the ordinary error exit."""
43
+ USAGE = 2
44
+ """The command line itself was wrong: an unknown flag, a bad value."""
45
+ INTERRUPTED = 130
46
+ """The user interrupted the command (``128 + SIGINT``)."""
47
+
48
+ @classmethod
49
+ def for_error(cls, error: BaseException) -> int:
50
+ """Return the exit code *error* maps to.
51
+
52
+ Explicit exit signals retain their supplied code, including codes not
53
+ represented by :class:`ExitCode`.
54
+ """
55
+ if isinstance(error, typer.Exit):
56
+ return error.exit_code
57
+ if isinstance(error, SystemExit):
58
+ return 0 if error.code is None else int(error.code)
59
+ if isinstance(error, UsageError):
60
+ return cls.USAGE
61
+ if isinstance(error, ClickException):
62
+ return error.exit_code
63
+ if isinstance(error, typer.Abort | KeyboardInterrupt):
64
+ return cls.INTERRUPTED
65
+ return cls.FAILURE
66
+
67
+
68
+ def run(app: typer.Typer, args: Sequence[str] | None = None, **kwargs: Any) -> int:
69
+ """Invoke *app*, reporting whatever escapes it, and return an exit code.
70
+
71
+ Diagnosed :class:`~rn_forge.commons.exceptions.AppException` instances are
72
+ reported without a traceback; unexpected exceptions are logged in full.
73
+
74
+ Args:
75
+ app: The Typer application to run.
76
+ args: The command line, defaulting to ``sys.argv[1:]``.
77
+ **kwargs: Forwarded to the underlying Click command.
78
+
79
+ Returns:
80
+ The exit code to hand to :func:`sys.exit`.
81
+ """
82
+ command = typer.main.get_command(app)
83
+ try:
84
+ # `standalone_mode=False` stops Click from printing and exiting on its
85
+ # own, so the codes below are the only ones this process can produce.
86
+ # In that mode Click *returns* the code an explicit exit asked for.
87
+ result = command(args=args, standalone_mode=False, **kwargs)
88
+ return result if isinstance(result, int) else ExitCode.OK
89
+ except (typer.Exit, SystemExit) as exit_signal:
90
+ return ExitCode.for_error(exit_signal)
91
+ except typer.Abort, KeyboardInterrupt:
92
+ console.warning("Interrupted.")
93
+ return ExitCode.INTERRUPTED
94
+ except ClickException as command_line_error:
95
+ command_line_error.show()
96
+ return ExitCode.for_error(command_line_error)
97
+ except AppException as failure:
98
+ # `.message`, not `str(failure)`: AppException's __str__ is the
99
+ # diagnostic form (`-1 | text | {}`), which is right for a log line and
100
+ # wrong for the one sentence a person reads on their terminal.
101
+ console.error("{}", failure.message)
102
+ _LOGGER.debug("Command failed", exc_info=True)
103
+ return ExitCode.FAILURE
104
+ except Exception as unexpected:
105
+ console.error("Unexpected error: {}", unexpected)
106
+ _LOGGER.exception("Unhandled exception escaped the command")
107
+ return ExitCode.FAILURE
108
+
109
+
110
+ class CliApp(typer.Typer):
111
+ """Typer application with standard logging, output, and exit handling.
112
+
113
+ Construct one directly, or build it from a repository's declared ``[cli]``
114
+ surface::
115
+
116
+ app = CliApp("golden-app", "Do the thing.") # explicit
117
+ app = CliApp.from_config(Path(__file__).parent / "config.toml")
118
+
119
+ Either way the root callback already takes ``--log-level``/``--log-file``
120
+ and ``--quiet``/``--json``, and :meth:`__call__` returns a mapped exit code
121
+ — so ``[project.scripts]`` needs nothing but ``mypkg.cli:app``, with no
122
+ ``main()``.
123
+
124
+ Typer is inherited rather than wrapped, so ``@app.command()``,
125
+ ``add_typer`` and the full constructor keyword set remain available.
126
+ """
127
+
128
+ def __init__(
129
+ self,
130
+ name: str,
131
+ help: str | None = None,
132
+ *,
133
+ default_log_level: LogLevel = LogLevel.VERBOSE,
134
+ **typer_kwargs: Any,
135
+ ) -> None:
136
+ """Initialize the application and register its root callback.
137
+
138
+ ``no_args_is_help=True`` and ``pretty_exceptions_show_locals=False``
139
+ are set by default and may be overridden through *typer_kwargs*.
140
+
141
+ Args:
142
+ name: The app name, also used (lowercased, spaces replaced with
143
+ ``_``) as the root logger name.
144
+ help: The app's ``--help`` description.
145
+ default_log_level: Default value for ``--log-level``.
146
+ **typer_kwargs: Forwarded to the :class:`typer.Typer` constructor.
147
+ """
148
+ typer_kwargs.setdefault("no_args_is_help", True)
149
+ typer_kwargs.setdefault("pretty_exceptions_show_locals", False)
150
+ super().__init__(name=name, help=help, **typer_kwargs)
151
+ self._logger_name = name.replace(" ", "_").lower()
152
+
153
+ @self.callback()
154
+ def _root(
155
+ ctx: typer.Context,
156
+ log_level: LogLevelOption = default_log_level,
157
+ log_file: LogFileOption = None,
158
+ quiet: QuietOption = False,
159
+ json_output: JsonOption = False,
160
+ ) -> None:
161
+ # `--json` needs no special handling for logging: AppLogger sends
162
+ # console records to stderr, so a stdout payload stays parseable
163
+ # whatever the level is and wherever on the command line it was
164
+ # given.
165
+ CliOptions(quiet=quiet, json_output=json_output).apply(ctx)
166
+ AppLogger.initialize(
167
+ root_logger_name=self._logger_name,
168
+ level=log_level.to_int(),
169
+ file=str(log_file) if log_file else None,
170
+ )
171
+
172
+ @classmethod
173
+ def from_config(
174
+ cls,
175
+ source: str | Path | Mapping[str, Any],
176
+ *,
177
+ key: str = SURFACE_KEY,
178
+ **typer_kwargs: Any,
179
+ ) -> Self:
180
+ """Build the application a repository's ``[cli]`` table describes.
181
+
182
+ Args:
183
+ source: A path to the configuration document, or an already-parsed
184
+ mapping. See :meth:`CliSurface.load`.
185
+ key: The table the surface lives under.
186
+ **typer_kwargs: Forwarded to the constructor.
187
+
188
+ Raises:
189
+ AppException: The document has no surface table, a declared value
190
+ has the wrong type, or a command's target cannot be imported.
191
+ """
192
+ return cls.from_surface(CliSurface.load(source, key=key), **typer_kwargs)
193
+
194
+ @classmethod
195
+ def from_surface(cls, surface: CliSurface, **typer_kwargs: Any) -> Self:
196
+ """Build the application an already-parsed *surface* describes."""
197
+ app = cls(
198
+ surface.name,
199
+ surface.help,
200
+ default_log_level=surface.default_log_level,
201
+ **typer_kwargs,
202
+ )
203
+ for command in surface.commands:
204
+ app.add_declared(command)
205
+ _LOGGER.verbose(
206
+ "CliApp: built {} with {} command(s)",
207
+ surface.name,
208
+ len(surface.commands),
209
+ )
210
+ return app
211
+
212
+ def add_declared(self, command: CommandSurface) -> None:
213
+ """Attach one declared command or namespace, importing its target by name.
214
+
215
+ Raises:
216
+ AppException: The target cannot be imported, or is neither a
217
+ :class:`typer.Typer` nor callable.
218
+ """
219
+ try:
220
+ target = AppUtils.import_string(command.target)
221
+ except Exception as error:
222
+ raise AppException(
223
+ "Cannot import command {!r} from {!r}: {}",
224
+ command.name,
225
+ command.target,
226
+ error,
227
+ ) from error
228
+ if isinstance(target, typer.Typer):
229
+ self.add_typer(target, name=command.name, help=command.help)
230
+ return
231
+ if not callable(target):
232
+ raise AppException(
233
+ "Command {!r} target {!r} is neither a Typer app nor callable",
234
+ command.name,
235
+ command.target,
236
+ )
237
+ self.command(name=command.name, help=command.help)(target)
238
+
239
+ def run(self, args: Sequence[str] | None = None, **kwargs: Any) -> int:
240
+ """Invoke this application and return its exit code. See :func:`run`."""
241
+ return run(self, args, **kwargs)
242
+
243
+ def __call__(self, *args: Any, **kwargs: Any) -> int:
244
+ """Invoke the application and return its exit code.
245
+
246
+ Unlike :meth:`typer.Typer.__call__`, which runs Click in standalone
247
+ mode and raises :exc:`SystemExit`, this returns the code — so a
248
+ generated console script (``sys.exit(app())``) gets the mapping in
249
+ :func:`run` for free.
250
+ """
251
+ return self.run(*args, **kwargs)
@@ -0,0 +1,183 @@
1
+ """Standard CLI options and value parsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import tomllib
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass, replace
9
+ from enum import StrEnum
10
+ from pathlib import Path
11
+ from typing import Annotated, Any, Self, cast
12
+
13
+ import typer
14
+ from rn_forge.commons.logging import AppLogger
15
+ from rn_forge.commons.runtime.console import OutputMode, console
16
+
17
+ __all__ = [
18
+ "CliOptions",
19
+ "DryRunOption",
20
+ "JsonOption",
21
+ "LogFileOption",
22
+ "LogLevel",
23
+ "LogLevelOption",
24
+ "QuietOption",
25
+ "SetOption",
26
+ "YesOption",
27
+ "parse_overrides",
28
+ ]
29
+
30
+
31
+ class LogLevel(StrEnum):
32
+ """CLI-facing log level names. Values are lowercase for clean ``--help`` output."""
33
+
34
+ CRITICAL = "critical"
35
+ ERROR = "error"
36
+ SUCCESS = "success"
37
+ WARNING = "warning"
38
+ NOTICE = "notice"
39
+ INFO = "info"
40
+ VERBOSE = "verbose"
41
+ DEBUG = "debug"
42
+ SPAM = "spam"
43
+ TRACE = "trace"
44
+
45
+ def to_int(self) -> int:
46
+ """Return the matching :class:`~rn_forge.commons.logging.AppLogger` level constant."""
47
+ mapping: dict[LogLevel, int] = {
48
+ LogLevel.CRITICAL: AppLogger.CRITICAL,
49
+ LogLevel.ERROR: AppLogger.ERROR,
50
+ LogLevel.SUCCESS: AppLogger.SUCCESS,
51
+ LogLevel.WARNING: AppLogger.WARNING,
52
+ LogLevel.NOTICE: AppLogger.NOTICE,
53
+ LogLevel.INFO: AppLogger.INFO,
54
+ LogLevel.VERBOSE: AppLogger.VERBOSE,
55
+ LogLevel.DEBUG: AppLogger.DEBUG,
56
+ LogLevel.SPAM: AppLogger.SPAM,
57
+ LogLevel.TRACE: AppLogger.TRACE,
58
+ }
59
+ return mapping[self]
60
+
61
+
62
+ LogLevelOption = Annotated[
63
+ LogLevel, typer.Option("--log-level", "-ll", help="Logging level.")
64
+ ]
65
+ LogFileOption = Annotated[
66
+ Path | None, typer.Option("--log-file", "-lf", help="Path to a log file.")
67
+ ]
68
+ QuietOption = Annotated[
69
+ bool, typer.Option("--quiet", "-q", help="Suppress non-essential output.")
70
+ ]
71
+ JsonOption = Annotated[
72
+ bool, typer.Option("--json", help="Emit machine-readable JSON output.")
73
+ ]
74
+ DryRunOption = Annotated[
75
+ bool,
76
+ typer.Option(
77
+ "--dry-run", help="Report what would change without writing anything."
78
+ ),
79
+ ]
80
+ YesOption = Annotated[
81
+ bool, typer.Option("--yes", "-y", help="Assume yes for every confirmation.")
82
+ ]
83
+ SetOption = Annotated[
84
+ list[str] | None,
85
+ typer.Option("--set", help="Override a config value, as dotted.key=value."),
86
+ ]
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class CliOptions:
91
+ """Resolved standard flags stored on the root ``ctx.obj``."""
92
+
93
+ quiet: bool = False
94
+ json_output: bool = False
95
+ dry_run: bool = False
96
+ yes: bool = False
97
+
98
+ @classmethod
99
+ def from_context(
100
+ cls,
101
+ ctx: typer.Context,
102
+ *,
103
+ quiet: bool = False,
104
+ json_output: bool = False,
105
+ dry_run: bool = False,
106
+ yes: bool = False,
107
+ ) -> Self:
108
+ """Return the options for this command: the root callback's, merged with these.
109
+
110
+ A flag set on either the root callback or the command is retained.
111
+
112
+ Pure — nothing is written to *ctx* and no console mode is changed.
113
+ Chain :meth:`apply` for that.
114
+ """
115
+ root_obj = ctx.find_root().obj
116
+ root = root_obj if isinstance(root_obj, cls) else cls()
117
+ return replace(
118
+ root,
119
+ quiet=root.quiet or quiet,
120
+ json_output=root.json_output or json_output,
121
+ dry_run=root.dry_run or dry_run,
122
+ yes=root.yes or yes,
123
+ )
124
+
125
+ def apply(self, ctx: typer.Context) -> Self:
126
+ """Validate this combination, set the console mode, and persist onto *ctx*.
127
+
128
+ Returns:
129
+ ``self``, so the call chains off :meth:`from_context`.
130
+
131
+ Raises:
132
+ typer.BadParameter: Both ``--quiet`` and ``--json`` are set, from
133
+ either level.
134
+ """
135
+ if self.quiet and self.json_output:
136
+ raise typer.BadParameter("--quiet and --json are mutually exclusive")
137
+ if self.json_output:
138
+ console.set_mode(OutputMode.JSON)
139
+ elif self.quiet:
140
+ console.set_mode(OutputMode.QUIET)
141
+ ctx.find_root().obj = self
142
+ return self
143
+
144
+
145
+ def parse_overrides(values: Sequence[str] | None) -> dict[str, Any]:
146
+ """Parse ``["a.b=1", "c=[1,2]"]`` into a nested mapping with typed scalars.
147
+
148
+ Values are parsed as JSON, then as TOML scalars, and otherwise retained as
149
+ strings. Dotted keys create nested mappings.
150
+
151
+ Raises:
152
+ typer.BadParameter: An entry has no ``=``, an empty key, or a dotted
153
+ path that collides with a scalar set by an earlier entry.
154
+ """
155
+ result: dict[str, Any] = {}
156
+ for expression in values or []:
157
+ if "=" not in expression:
158
+ raise typer.BadParameter(f"Override must be KEY=VALUE: {expression!r}")
159
+ key, raw = expression.split("=", 1)
160
+ parts = [part for part in key.strip().split(".") if part]
161
+ if not parts:
162
+ raise typer.BadParameter(f"Override key cannot be empty: {expression!r}")
163
+ cursor: dict[str, Any] = result
164
+ for part in parts[:-1]:
165
+ existing: Any = cursor.setdefault(part, {})
166
+ if not isinstance(existing, dict):
167
+ raise typer.BadParameter(f"Override collides with scalar key: {key!r}")
168
+ cursor = cast("dict[str, Any]", existing)
169
+ cursor[parts[-1]] = _parse_scalar(raw)
170
+ return result
171
+
172
+
173
+ def _parse_scalar(raw: str) -> Any:
174
+ """Parse *raw* as JSON, then as a TOML scalar, else return it unchanged."""
175
+ stripped = raw.strip()
176
+ try:
177
+ return json.loads(stripped)
178
+ except json.JSONDecodeError:
179
+ pass
180
+ try:
181
+ return tomllib.loads(f"value = {stripped}\n")["value"]
182
+ except tomllib.TOMLDecodeError, KeyError:
183
+ return raw
File without changes
@@ -0,0 +1,106 @@
1
+ """Models for a repository's declared ``[cli]`` surface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any, Self
9
+
10
+ from rn_forge.cli.options import LogLevel
11
+ from rn_forge.commons.exceptions import AppException
12
+ from rn_forge.commons.fs.documents import DocumentUtils
13
+ from rn_forge.commons.lang.dataclasses import DataclassMixin
14
+
15
+ __all__ = [
16
+ "SURFACE_KEY",
17
+ "CliSurface",
18
+ "CommandSurface",
19
+ ]
20
+
21
+ SURFACE_KEY = "cli"
22
+ """The table a declared surface is read from."""
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class CommandSurface(DataclassMixin):
27
+ """One command or command namespace of a declared CLI.
28
+
29
+ Args:
30
+ name: The name the command is invoked by.
31
+ target: Import path of the implementation, as ``module:attribute`` or
32
+ a dotted path. A :class:`typer.Typer` becomes a namespace; a
33
+ callable becomes a single command.
34
+ help: Help text. Defaults to the target's own docstring, which is
35
+ where it belongs when there is one.
36
+ """
37
+
38
+ name: str
39
+ target: str
40
+ help: str | None = None
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class CliSurface(DataclassMixin):
45
+ """A whole declared command line.
46
+
47
+ Args:
48
+ name: The application name, also used as the root logger name.
49
+ help: The application's ``--help`` description.
50
+ default_log_level: The default value of ``--log-level``.
51
+ commands: The commands and namespaces the app exposes.
52
+ """
53
+
54
+ name: str
55
+ help: str | None = None
56
+ default_log_level: LogLevel = LogLevel.VERBOSE
57
+ commands: tuple[CommandSurface, ...] = field(
58
+ default_factory=tuple[CommandSurface, ...]
59
+ )
60
+
61
+ def __post_init__(self) -> None:
62
+ if not self.name.strip():
63
+ raise AppException("A declared CLI needs a name")
64
+ duplicates = _duplicates(command.name for command in self.commands)
65
+ if duplicates:
66
+ raise AppException("Duplicate command name(s): {}", ", ".join(duplicates))
67
+
68
+ @classmethod
69
+ def load(
70
+ cls, source: str | Path | Mapping[str, Any], *, key: str = SURFACE_KEY
71
+ ) -> Self:
72
+ """Read a surface from a config document or an in-memory mapping.
73
+
74
+ Args:
75
+ source: A path to a TOML/YAML/JSON document, or an already-parsed
76
+ mapping. Either may be the whole document (with the surface
77
+ under *key*) or the surface table itself.
78
+ key: The table the surface lives under. Ignored when *source* is
79
+ already the surface table.
80
+
81
+ Returns:
82
+ The parsed, validated surface.
83
+
84
+ Raises:
85
+ AppException: The document has no *key* table, or a declared value
86
+ does not match its field's type.
87
+ """
88
+ data = (
89
+ dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
90
+ )
91
+ if key in data:
92
+ data = data[key]
93
+ elif "name" not in data:
94
+ raise AppException("No [{}] table to build a CLI from", key)
95
+ return cls.from_dict(dict(data))
96
+
97
+
98
+ def _duplicates(names: Iterable[str]) -> list[str]:
99
+ """Names appearing more than once, in first-seen order."""
100
+ seen: set[str] = set()
101
+ repeated: list[str] = []
102
+ for name in names:
103
+ if name in seen and name not in repeated:
104
+ repeated.append(name)
105
+ seen.add(name)
106
+ return repeated