rn-forge-cli 0.1.3__tar.gz → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rn-forge-cli
3
- Version: 0.1.3
3
+ Version: 0.2.1
4
4
  Summary: The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes
5
5
  Author: Rohit Narayanan
6
6
  Author-email: Rohit Narayanan <rohit.nn@gmail.com>
@@ -13,10 +13,10 @@ Classifier: Programming Language :: Python :: 3
13
13
  Classifier: Programming Language :: Python :: 3 :: Only
14
14
  Classifier: Programming Language :: Python :: 3.14
15
15
  Classifier: Typing :: Typed
16
- Requires-Dist: rn-forge-commons>=0.8.0,<0.10
16
+ Requires-Dist: rn-forge-commons>=0.8.0,<0.11
17
17
  Requires-Dist: rich>=15.0.0
18
18
  Requires-Dist: typer>=0.26.8
19
- Requires-Dist: assertpy>=2.35 ; extra == 'testing'
19
+ Requires-Dist: assertpy>=2.36.0 ; extra == 'testing'
20
20
  Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
21
21
  Requires-Python: >=3.14
22
22
  Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/
@@ -72,6 +72,9 @@ Require the package by version range:
72
72
  dependencies = ["rn-forge-cli>=0.1,<0.2"]
73
73
  ```
74
74
 
75
+ No extra is needed to run a command line. The `testing` extra installs
76
+ `assertpy` and `pytest`.
77
+
75
78
  ## Usage
76
79
 
77
80
  ```python
@@ -100,3 +103,9 @@ Or declare the commands in a `[cli]` table and build the app from it:
100
103
  ```python
101
104
  app = CliApp.from_config("cli.toml")
102
105
  ```
106
+
107
+ ## Errors
108
+
109
+ An `AppException` exits 1 as one line; a bad command line exits 2; `Ctrl-C`
110
+ exits 130; any other exception exits 1 with its traceback logged. A command that
111
+ raises `typer.Exit(n)` exits `n`.
@@ -44,6 +44,9 @@ Require the package by version range:
44
44
  dependencies = ["rn-forge-cli>=0.1,<0.2"]
45
45
  ```
46
46
 
47
+ No extra is needed to run a command line. The `testing` extra installs
48
+ `assertpy` and `pytest`.
49
+
47
50
  ## Usage
48
51
 
49
52
  ```python
@@ -72,3 +75,9 @@ Or declare the commands in a `[cli]` table and build the app from it:
72
75
  ```python
73
76
  app = CliApp.from_config("cli.toml")
74
77
  ```
78
+
79
+ ## Errors
80
+
81
+ An `AppException` exits 1 as one line; a bad command line exits 2; `Ctrl-C`
82
+ exits 130; any other exception exits 1 with its traceback logged. A command that
83
+ raises `typer.Exit(n)` exits `n`.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-cli"
3
- version = "0.1.3"
3
+ version = "0.2.1"
4
4
  description = "The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  requires-python = ">=3.14"
18
18
  dependencies = [
19
- "rn-forge-commons>=0.8.0,<0.10",
19
+ "rn-forge-commons>=0.8.0,<0.11",
20
20
  "rich>=15.0.0",
21
21
  "typer>=0.26.8",
22
22
  ]
@@ -27,7 +27,7 @@ email = "rohit.nn@gmail.com"
27
27
 
28
28
  [project.optional-dependencies]
29
29
  testing = [
30
- "assertpy>=2.35",
30
+ "assertpy>=2.36.0",
31
31
  "pytest>=9.1.1",
32
32
  ]
33
33
 
@@ -64,17 +64,17 @@ markers = ["scaffold: installs built wheels into a scaffolded application (slow)
64
64
 
65
65
  [dependency-groups]
66
66
  dev = [
67
- "assertpy>=2.35",
67
+ "assertpy>=2.36.0",
68
68
  "pyright>=1.1.411",
69
- "pytest>=9.1.1",
69
+ "pytest>=9.2.0",
70
70
  "pytest-cov>=7.1.0",
71
71
  "pytest-randomly>=4.1.0",
72
72
  "rn-forge-cli",
73
- "ruff>=0.15.21",
73
+ "ruff>=0.17.4",
74
74
  ]
75
75
  docs = [
76
76
  "mkdocs>=1.6.1",
77
- "mkdocs-material>=9.7.6",
78
- "mkdocstrings[python]>=1.0.6",
77
+ "mkdocs-material>=9.8.1",
78
+ "mkdocstrings[python]>=1.0.8",
79
79
  "rn-forge-cli",
80
80
  ]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-cli"
3
- version = "0.1.3"
3
+ version = "0.2.1"
4
4
  description = "The shared command-line layer for rn-forge applications: Typer app factory, standard options, console and exit codes"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
@@ -18,13 +18,13 @@ classifiers = [
18
18
  requires-python = ">=3.14"
19
19
  # Internal requirements are version ranges (ADR-0004).
20
20
  dependencies = [
21
- "rn-forge-commons>=0.8.0,<0.10",
21
+ "rn-forge-commons>=0.8.0,<0.11",
22
22
  "rich>=15.0.0",
23
23
  "typer>=0.26.8",
24
24
  ]
25
25
 
26
26
  [project.optional-dependencies]
27
- testing = ["assertpy>=2.35", "pytest>=9.1.1"]
27
+ testing = ["assertpy>=2.36.0", "pytest>=9.1.1"]
28
28
 
29
29
  [project.urls]
30
30
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-cli/latest/"
@@ -59,17 +59,17 @@ markers = [
59
59
 
60
60
  [dependency-groups]
61
61
  dev = [
62
- "assertpy>=2.35",
62
+ "assertpy>=2.36.0",
63
63
  "pyright>=1.1.411",
64
- "pytest>=9.1.1",
64
+ "pytest>=9.2.0",
65
65
  "pytest-cov>=7.1.0",
66
66
  "pytest-randomly>=4.1.0",
67
67
  "rn-forge-cli",
68
- "ruff>=0.15.21",
68
+ "ruff>=0.17.4",
69
69
  ]
70
70
  docs = [
71
71
  "mkdocs>=1.6.1",
72
- "mkdocs-material>=9.7.6",
73
- "mkdocstrings[python]>=1.0.6",
72
+ "mkdocs-material>=9.8.1",
73
+ "mkdocstrings[python]>=1.0.8",
74
74
  "rn-forge-cli",
75
75
  ]
@@ -2,12 +2,16 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import inspect
6
+ import re
5
7
  from collections.abc import Mapping, Sequence
6
8
  from enum import IntEnum
7
9
  from pathlib import Path
8
10
  from typing import Any, Self
9
11
 
10
12
  import typer
13
+ from rich.errors import StyleSyntaxError
14
+ from rich.style import Style
11
15
  from rn_forge.cli.options import (
12
16
  CliOptions,
13
17
  JsonOption,
@@ -21,6 +25,7 @@ from rn_forge.commons.exceptions import AppException
21
25
  from rn_forge.commons.lang.utils import AppUtils
22
26
  from rn_forge.commons.logging import AppLogger
23
27
  from rn_forge.commons.runtime.console import console
28
+ from typer._click.core import ParameterSource
24
29
 
25
30
  # Typer 0.26 vendors Click, so `click.UsageError` and Typer's own are different
26
31
  # classes and an `except click.UsageError` never fires. These are the ones a
@@ -32,6 +37,42 @@ __all__ = ["CliApp", "ExitCode", "run"]
32
37
 
33
38
  _LOGGER = AppLogger.get_logger(__name__)
34
39
 
40
+ _BRACKET_GROUP = re.compile(r"\[([^\[\]]*)\]")
41
+
42
+
43
+ def _escape_markup(text: str) -> str:
44
+ """Escape each ``[...]`` group in *text* that is not Rich markup.
45
+
46
+ A group stays markup when it is a closing tag or parses as a Rich style.
47
+ """
48
+
49
+ def escape(match: re.Match[str]) -> str:
50
+ content = match.group(1)
51
+ if not content or content.startswith("/"):
52
+ return match.group(0)
53
+ try:
54
+ Style.parse(content)
55
+ except StyleSyntaxError:
56
+ return "\\" + match.group(0)
57
+ return match.group(0)
58
+
59
+ return _BRACKET_GROUP.sub(escape, text)
60
+
61
+
62
+ _SECTION_HEADER = re.compile(
63
+ r"^(?:Args|Arguments|Returns|Raises|Yields|Examples|Note):$", re.MULTILINE
64
+ )
65
+
66
+
67
+ def _strip_sections(doc: str) -> str:
68
+ """Return *doc* up to its first Google-style section header.
69
+
70
+ A header is a line that is, in full, ``Args:``, ``Arguments:``,
71
+ ``Returns:``, ``Raises:``, ``Yields:``, ``Examples:`` or ``Note:``.
72
+ """
73
+ header = _SECTION_HEADER.search(doc)
74
+ return (doc[: header.start()] if header else doc).rstrip()
75
+
35
76
 
36
77
  class ExitCode(IntEnum):
37
78
  """Exit codes returned by an ``rn-forge`` CLI."""
@@ -70,6 +111,7 @@ def run(app: typer.Typer, args: Sequence[str] | None = None, **kwargs: Any) -> i
70
111
 
71
112
  Diagnosed :class:`~rn_forge.commons.exceptions.AppException` instances are
72
113
  reported without a traceback; unexpected exceptions are logged in full.
114
+ The console mode on return is the mode on entry.
73
115
 
74
116
  Args:
75
117
  app: The Typer application to run.
@@ -79,8 +121,9 @@ def run(app: typer.Typer, args: Sequence[str] | None = None, **kwargs: Any) -> i
79
121
  Returns:
80
122
  The exit code to hand to :func:`sys.exit`.
81
123
  """
82
- command = typer.main.get_command(app)
124
+ prior = console.mode
83
125
  try:
126
+ command = typer.main.get_command(app)
84
127
  # `standalone_mode=False` stops Click from printing and exiting on its
85
128
  # own, so the codes below are the only ones this process can produce.
86
129
  # In that mode Click *returns* the code an explicit exit asked for.
@@ -105,6 +148,8 @@ def run(app: typer.Typer, args: Sequence[str] | None = None, **kwargs: Any) -> i
105
148
  console.error("Unexpected error: {}", unexpected)
106
149
  _LOGGER.exception("Unhandled exception escaped the command")
107
150
  return ExitCode.FAILURE
151
+ finally:
152
+ console.set_mode(prior)
108
153
 
109
154
 
110
155
  class CliApp(typer.Typer):
@@ -163,10 +208,15 @@ class CliApp(typer.Typer):
163
208
  # whatever the level is and wherever on the command line it was
164
209
  # given.
165
210
  CliOptions(quiet=quiet, json_output=json_output).apply(ctx)
211
+ explicit = any(
212
+ ctx.get_parameter_source(name) is not ParameterSource.DEFAULT
213
+ for name in ("log_level", "log_file")
214
+ )
166
215
  AppLogger.initialize(
167
216
  root_logger_name=self._logger_name,
168
217
  level=log_level.to_int(),
169
218
  file=str(log_file) if log_file else None,
219
+ force_reconfigure=explicit,
170
220
  )
171
221
 
172
222
  @classmethod
@@ -196,7 +246,7 @@ class CliApp(typer.Typer):
196
246
  """Build the application an already-parsed *surface* describes."""
197
247
  app = cls(
198
248
  surface.name,
199
- surface.help,
249
+ _escape_markup(surface.help) if surface.help else surface.help,
200
250
  default_log_level=surface.default_log_level,
201
251
  **typer_kwargs,
202
252
  )
@@ -225,8 +275,15 @@ class CliApp(typer.Typer):
225
275
  command.target,
226
276
  error,
227
277
  ) from error
278
+ text = command.help
279
+ if text is None:
280
+ if isinstance(target, typer.Typer):
281
+ text = target.info.help if isinstance(target.info.help, str) else None
282
+ elif callable(target):
283
+ text = _strip_sections(inspect.getdoc(target) or "")
284
+ help_text = _escape_markup(text) if text else None
228
285
  if isinstance(target, typer.Typer):
229
- self.add_typer(target, name=command.name, help=command.help)
286
+ self.add_typer(target, name=command.name, help=help_text)
230
287
  return
231
288
  if not callable(target):
232
289
  raise AppException(
@@ -234,7 +291,7 @@ class CliApp(typer.Typer):
234
291
  command.name,
235
292
  command.target,
236
293
  )
237
- self.command(name=command.name, help=command.help)(target)
294
+ self.command(name=command.name, help=help_text)(target)
238
295
 
239
296
  def run(self, args: Sequence[str] | None = None, **kwargs: Any) -> int:
240
297
  """Invoke this application and return its exit code. See :func:`run`."""
@@ -10,7 +10,7 @@ from typing import Any, Self
10
10
  from rn_forge.cli.options import LogLevel
11
11
  from rn_forge.commons.exceptions import AppException
12
12
  from rn_forge.commons.fs.documents import DocumentUtils
13
- from rn_forge.commons.lang.dataclasses import DataclassMixin
13
+ from rn_forge.commons.lang.dataclasses import StrictDataclassMixin
14
14
 
15
15
  __all__ = [
16
16
  "SURFACE_KEY",
@@ -23,7 +23,7 @@ SURFACE_KEY = "cli"
23
23
 
24
24
 
25
25
  @dataclass(frozen=True, slots=True)
26
- class CommandSurface(DataclassMixin):
26
+ class CommandSurface(StrictDataclassMixin):
27
27
  """One command or command namespace of a declared CLI.
28
28
 
29
29
  Args:
@@ -31,8 +31,8 @@ class CommandSurface(DataclassMixin):
31
31
  target: Import path of the implementation, as ``module:attribute`` or
32
32
  a dotted path. A :class:`typer.Typer` becomes a namespace; a
33
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.
34
+ help: Help text, used as written. Defaults to the target's
35
+ docstring up to its first section (``Args:``, ``Raises:``, ...).
36
36
  """
37
37
 
38
38
  name: str
@@ -41,7 +41,7 @@ class CommandSurface(DataclassMixin):
41
41
 
42
42
 
43
43
  @dataclass(frozen=True, slots=True)
44
- class CliSurface(DataclassMixin):
44
+ class CliSurface(StrictDataclassMixin):
45
45
  """A whole declared command line.
46
46
 
47
47
  Args:
@@ -82,8 +82,10 @@ class CliSurface(DataclassMixin):
82
82
  The parsed, validated surface.
83
83
 
84
84
  Raises:
85
- AppException: The document has no *key* table, or a declared value
86
- does not match its field's type.
85
+ AppException: The document has no *key* table, ``commands`` is not
86
+ an array of tables, an entry in ``commands`` is not a table,
87
+ a declared value does not match its field's type, or a key names no
88
+ field.
87
89
  """
88
90
  data = (
89
91
  dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
@@ -92,9 +94,31 @@ class CliSurface(DataclassMixin):
92
94
  data = data[key]
93
95
  elif "name" not in data:
94
96
  raise AppException("No [{}] table to build a CLI from", key)
97
+ _validate_commands(data, key)
95
98
  return cls.from_dict(dict(data))
96
99
 
97
100
 
101
+ def _validate_commands(data: Mapping[str, Any], key: str) -> None:
102
+ if "commands" not in data:
103
+ return
104
+ commands = data["commands"]
105
+ entries: Iterable[object] = commands
106
+ if not isinstance(commands, list | tuple):
107
+ raise AppException(
108
+ "[{}] commands must be an array of tables, not {}",
109
+ key,
110
+ type(commands).__name__,
111
+ )
112
+ for index, entry in enumerate(entries):
113
+ if not isinstance(entry, Mapping):
114
+ raise AppException(
115
+ "[{}] commands[{}] must be a table, not {}",
116
+ key,
117
+ index,
118
+ type(entry).__name__,
119
+ )
120
+
121
+
98
122
  def _duplicates(names: Iterable[str]) -> list[str]:
99
123
  """Names appearing more than once, in first-seen order."""
100
124
  seen: set[str] = set()
File without changes