rn-forge-tooling 0.3.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.
@@ -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,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: rn-forge-tooling
3
+ Version: 0.3.1
4
+ Summary: Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs
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: rn-forge-cli>=0.1.1,<0.2
18
+ Requires-Dist: assertpy>=1.1 ; extra == 'testing'
19
+ Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
20
+ Requires-Python: >=3.14
21
+ Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/
22
+ Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling
23
+ Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/CHANGELOG.md
24
+ Project-URL: Issues, https://github.com/rn-forge/pykit/issues
25
+ Provides-Extra: testing
26
+ Description-Content-Type: text/markdown
27
+
28
+ # rn-forge-tooling
29
+
30
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/)
31
+ ·
32
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/CHANGELOG.md)
33
+ ·
34
+ [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling)
35
+ · [All pykit packages](https://rn-forge.github.io/pykit/)
36
+
37
+ The lifecycle and install layer of the developer-tooling stack: for command-line
38
+ tools that install themselves and manage their own versions. File generation,
39
+ local state and templates live in `rn-forge-commons`.
40
+
41
+ Where
42
+ [`rn-forge-commons`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons)
43
+ is runtime-neutral — safe in a web server, a worker or a container — and
44
+ [`rn-forge-cli`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli)
45
+ is the command-line shape every application wants, this package is deliberately
46
+ workstation-shaped: it assumes a developer's filesystem and a tool that owns
47
+ files in it. It owns:
48
+
49
+ - `install` — the tool lifecycle: `$RNF_HOME` layout (`ToolHome`), release
50
+ sources and verification, archive extraction, the `ToolProduct` seam, and
51
+ the transactional
52
+ `install`/`upgrade`/`uninstall`/`cleanup`/`status`/`doctor` verbs.
53
+ - `cli` — `build_tool_app`, which builds an `rn-forge-cli` application from a
54
+ `[cli]` table and adds the lifecycle verbs declared in a `[lifecycle]`
55
+ table.
56
+
57
+ A repository that only needs a command line takes `rn-forge-cli` and stops
58
+ there. A package that ships into a deployed runtime (`rn-forge-django`,
59
+ `rn-forge-fastapi`) must never depend on this package outside a `codegen` extra.
60
+ Tooling may import cli and commons; neither may import tooling, and
61
+ `uv run lint-imports` proves it.
62
+
63
+ ## Install
64
+
65
+ Require the package by version range:
66
+
67
+ ```toml
68
+ [project]
69
+ dependencies = ["rn-forge-tooling>=0.3,<0.4"]
70
+ ```
71
+
72
+ `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges.
73
+
74
+ ## Docs
75
+
76
+ Full API reference and guides are built with mkdocs:
77
+
78
+ ```bash
79
+ uv run --group docs mkdocs serve # or `mkdocs build`
80
+ ```
81
+
82
+ Source lives in
83
+ [`docs/`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling/docs),
84
+ configured via
85
+ [`mkdocs.yml`](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/mkdocs.yml).
86
+
87
+ ## Development
88
+
89
+ From the repo root or this directory:
90
+
91
+ ```bash
92
+ uv run pytest packages/rn-forge-tooling
93
+ uv run ruff check packages/rn-forge-tooling
94
+ uv run pyright
95
+ ```
@@ -0,0 +1,68 @@
1
+ # rn-forge-tooling
2
+
3
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/)
4
+ ·
5
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/CHANGELOG.md)
6
+ ·
7
+ [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling)
8
+ · [All pykit packages](https://rn-forge.github.io/pykit/)
9
+
10
+ The lifecycle and install layer of the developer-tooling stack: for command-line
11
+ tools that install themselves and manage their own versions. File generation,
12
+ local state and templates live in `rn-forge-commons`.
13
+
14
+ Where
15
+ [`rn-forge-commons`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-commons)
16
+ is runtime-neutral — safe in a web server, a worker or a container — and
17
+ [`rn-forge-cli`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-cli)
18
+ is the command-line shape every application wants, this package is deliberately
19
+ workstation-shaped: it assumes a developer's filesystem and a tool that owns
20
+ files in it. It owns:
21
+
22
+ - `install` — the tool lifecycle: `$RNF_HOME` layout (`ToolHome`), release
23
+ sources and verification, archive extraction, the `ToolProduct` seam, and
24
+ the transactional
25
+ `install`/`upgrade`/`uninstall`/`cleanup`/`status`/`doctor` verbs.
26
+ - `cli` — `build_tool_app`, which builds an `rn-forge-cli` application from a
27
+ `[cli]` table and adds the lifecycle verbs declared in a `[lifecycle]`
28
+ table.
29
+
30
+ A repository that only needs a command line takes `rn-forge-cli` and stops
31
+ there. A package that ships into a deployed runtime (`rn-forge-django`,
32
+ `rn-forge-fastapi`) must never depend on this package outside a `codegen` extra.
33
+ Tooling may import cli and commons; neither may import tooling, and
34
+ `uv run lint-imports` proves it.
35
+
36
+ ## Install
37
+
38
+ Require the package by version range:
39
+
40
+ ```toml
41
+ [project]
42
+ dependencies = ["rn-forge-tooling>=0.3,<0.4"]
43
+ ```
44
+
45
+ `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges.
46
+
47
+ ## Docs
48
+
49
+ Full API reference and guides are built with mkdocs:
50
+
51
+ ```bash
52
+ uv run --group docs mkdocs serve # or `mkdocs build`
53
+ ```
54
+
55
+ Source lives in
56
+ [`docs/`](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling/docs),
57
+ configured via
58
+ [`mkdocs.yml`](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/mkdocs.yml).
59
+
60
+ ## Development
61
+
62
+ From the repo root or this directory:
63
+
64
+ ```bash
65
+ uv run pytest packages/rn-forge-tooling
66
+ uv run ruff check packages/rn-forge-tooling
67
+ uv run pyright
68
+ ```
@@ -0,0 +1,74 @@
1
+ [project]
2
+ name = "rn-forge-tooling"
3
+ version = "0.3.1"
4
+ description = "Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs"
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
+ "rn-forge-cli>=0.1.1,<0.2",
21
+ ]
22
+
23
+ [[project.authors]]
24
+ name = "Rohit Narayanan"
25
+ email = "rohit.nn@gmail.com"
26
+
27
+ [project.optional-dependencies]
28
+ testing = [
29
+ "assertpy>=1.1",
30
+ "pytest>=9.1.1",
31
+ ]
32
+
33
+ [project.urls]
34
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/"
35
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling"
36
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/CHANGELOG.md"
37
+ Issues = "https://github.com/rn-forge/pykit/issues"
38
+
39
+ [build-system]
40
+ requires = ["uv_build>=0.11.28,<0.12.0"]
41
+ build-backend = "uv_build"
42
+
43
+ [tool.uv.build-backend]
44
+ module-name = "rn_forge.tooling"
45
+
46
+ [tool.uv.sources.rn-forge-commons]
47
+ workspace = true
48
+
49
+ [tool.uv.sources.rn-forge-cli]
50
+ workspace = true
51
+
52
+ [tool.uv.sources.rn-forge-tooling]
53
+ workspace = true
54
+
55
+ [tool.pytest.ini_options]
56
+ addopts = "-ra --import-mode=importlib -m 'not scaffold'"
57
+ markers = ["scaffold: installs built wheels into a scaffolded application (slow)"]
58
+
59
+ [dependency-groups]
60
+ dev = [
61
+ "assertpy>=1.1",
62
+ "pyright>=1.1.411",
63
+ "pytest>=9.1.1",
64
+ "pytest-cov>=7.1.0",
65
+ "pytest-randomly>=4.1.0",
66
+ "rn-forge-tooling",
67
+ "ruff>=0.15.21",
68
+ ]
69
+ docs = [
70
+ "mkdocs>=1.6.1",
71
+ "mkdocs-material>=9.7.6",
72
+ "mkdocstrings[python]>=1.0.6",
73
+ "rn-forge-tooling",
74
+ ]
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "rn-forge-tooling"
3
+ version = "0.3.1"
4
+ description = "Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs"
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
+ "rn-forge-cli>=0.1.1,<0.2",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ testing = ["assertpy>=1.1", "pytest>=9.1.1"]
27
+
28
+ [project.urls]
29
+ Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/"
30
+ Source = "https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-tooling"
31
+ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooling/CHANGELOG.md"
32
+ Issues = "https://github.com/rn-forge/pykit/issues"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.11.28,<0.12.0"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.uv.build-backend]
39
+ module-name = "rn_forge.tooling"
40
+
41
+ [tool.uv.sources]
42
+ rn-forge-commons = { workspace = true }
43
+ rn-forge-cli = { workspace = true }
44
+ rn-forge-tooling = { 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-tooling",
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-tooling",
65
+ ]
@@ -0,0 +1,37 @@
1
+ """Public lifecycle and installation APIs for developer tools."""
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ if TYPE_CHECKING:
6
+ from rn_forge.tooling.install import ToolHome, ToolProduct, extract_archive
7
+
8
+ __all__ = [
9
+ "ToolHome",
10
+ "ToolProduct",
11
+ "extract_archive",
12
+ ]
13
+
14
+ _INSTALL = "rn_forge.tooling.install"
15
+
16
+ _MODULES = {
17
+ "ToolHome": _INSTALL,
18
+ "ToolProduct": _INSTALL,
19
+ "extract_archive": _INSTALL,
20
+ }
21
+
22
+
23
+ def __getattr__(name: str) -> Any:
24
+ """Import and return a public symbol on first access."""
25
+ module_name = _MODULES.get(name)
26
+ if module_name is None:
27
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
28
+ import importlib
29
+
30
+ value = getattr(importlib.import_module(module_name), name)
31
+ globals()[name] = value
32
+ return value
33
+
34
+
35
+ def __dir__() -> list[str]:
36
+ """Include the lazily-imported names in ``dir()``."""
37
+ return sorted([*globals(), *__all__])
@@ -0,0 +1 @@
1
+ """Command surfaces shipped by ``rn-forge-tooling``."""
@@ -0,0 +1,310 @@
1
+ """Typer commands for a declared tool lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable, Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Annotated, Any, Self
9
+
10
+ import typer
11
+ from rn_forge.cli import CliApp, CliOptions, CliSurface, YesOption
12
+ from rn_forge.commons.exceptions import AppException
13
+ from rn_forge.commons.fs.documents import DocumentUtils
14
+ from rn_forge.commons.lang.dataclasses import DataclassMixin
15
+ from rn_forge.commons.lang.utils import AppUtils
16
+ from rn_forge.commons.runtime.console import OutputMode, console
17
+ from rn_forge.tooling.install import lifecycle
18
+ from rn_forge.tooling.install.product import ToolProduct
19
+ from rn_forge.tooling.install.release import LocalArchive
20
+
21
+ __all__ = ["VERBS", "LifecycleSurface", "build_tool_app", "lifecycle_commands"]
22
+
23
+ VERBS = ("install", "upgrade", "uninstall", "cleanup", "status", "doctor")
24
+ """Every verb this module can mount, in ``--help`` order."""
25
+
26
+ LIFECYCLE_KEY = "lifecycle"
27
+ """The table :meth:`LifecycleSurface.load` reads by default."""
28
+
29
+
30
+ def lifecycle_commands(
31
+ product: ToolProduct, verbs: Sequence[str] = VERBS
32
+ ) -> typer.Typer:
33
+ """Return a Typer app holding *verbs* as commands over *product*.
34
+
35
+ Args:
36
+ product: The product the commands act on.
37
+ verbs: Which of :data:`VERBS` to include.
38
+
39
+ Raises:
40
+ AppException: *product* is not a :class:`ToolProduct`, or a verb is
41
+ not one of :data:`VERBS`.
42
+ """
43
+ if not isinstance(product, ToolProduct): # pyright: ignore[reportUnnecessaryIsInstance] - named by a config string
44
+ raise AppException("{!r} is not a ToolProduct", product)
45
+ unknown = sorted(set(verbs) - set(VERBS))
46
+ if unknown:
47
+ raise AppException("Unknown lifecycle verb(s): {}", ", ".join(unknown))
48
+
49
+ app = typer.Typer()
50
+ for verb in VERBS:
51
+ if verb in verbs:
52
+ _COMMANDS[verb](app, product)
53
+ return app
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class LifecycleSurface(DataclassMixin):
58
+ """A declared ``[lifecycle]`` table: which verbs a tool exposes, and where.
59
+
60
+ Args:
61
+ product: Import path of the :class:`ToolProduct` the verbs act on.
62
+ verbs: Which of :data:`VERBS` to expose. Default: all six.
63
+ namespace: Sub-command group the verbs are mounted under, e.g.
64
+ ``"self"`` for ``<tool> self status``. Default: mounted at the
65
+ root of the application.
66
+ """
67
+
68
+ product: str
69
+ verbs: tuple[str, ...] = VERBS
70
+ namespace: str | None = None
71
+
72
+ def __post_init__(self) -> None:
73
+ unknown = [verb for verb in self.verbs if verb not in VERBS]
74
+ if unknown:
75
+ raise AppException(
76
+ "Unknown lifecycle verb(s): {} (expected any of {})",
77
+ ", ".join(unknown),
78
+ ", ".join(VERBS),
79
+ )
80
+ duplicates = _duplicates(self.verbs)
81
+ if duplicates:
82
+ raise AppException("Duplicate lifecycle verb(s): {}", ", ".join(duplicates))
83
+ if self.namespace is not None and (
84
+ not self.namespace.strip() or any(char.isspace() for char in self.namespace)
85
+ ):
86
+ raise AppException("Invalid lifecycle namespace: {!r}", self.namespace)
87
+
88
+ @classmethod
89
+ def load(
90
+ cls, source: str | Path | Mapping[str, Any], *, key: str = LIFECYCLE_KEY
91
+ ) -> Self:
92
+ """Read a lifecycle surface from a config document or an in-memory mapping.
93
+
94
+ Args:
95
+ source: A path to a TOML/YAML/JSON document, or an already-parsed
96
+ mapping. Either may be the whole document (with the table
97
+ under *key*) or the table itself.
98
+ key: The table the surface lives under. Ignored when *source* is
99
+ already the table.
100
+
101
+ Raises:
102
+ AppException: The document has no *key* table, or a declared
103
+ value does not match its field's type.
104
+ """
105
+ data = (
106
+ dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
107
+ )
108
+ if key in data:
109
+ data = data[key]
110
+ elif "product" not in data:
111
+ raise AppException("No [{}] table to build lifecycle verbs from", key)
112
+ return cls.from_dict(dict(data))
113
+
114
+
115
+ def build_tool_app(
116
+ source: str | Path | Mapping[str, Any],
117
+ *,
118
+ cli_key: str = "cli",
119
+ lifecycle_key: str = LIFECYCLE_KEY,
120
+ **typer_kwargs: Any,
121
+ ) -> CliApp:
122
+ """Build the application a repository's ``[cli]`` and ``[lifecycle]`` tables describe.
123
+
124
+ This is the entry point for an installable tool. It builds the generic
125
+ application `rn-forge-cli` describes from ``[cli]``, then — when the
126
+ document also has a *lifecycle_key* table — mounts this module's verbs on
127
+ top of it, at the root or under `LifecycleSurface.namespace`.
128
+
129
+ Args:
130
+ source: A path to the configuration document, or an already-parsed
131
+ mapping. See :meth:`~rn_forge.cli.CliSurface.load`.
132
+ cli_key: The table the generic surface lives under.
133
+ lifecycle_key: The table the lifecycle verbs live under. A document
134
+ without this table builds a plain application.
135
+ **typer_kwargs: Forwarded to the :class:`~rn_forge.cli.CliApp`
136
+ constructor.
137
+
138
+ Raises:
139
+ AppException: Either table is malformed, the namespace or a verb
140
+ collides with a declared command name, or the product cannot be
141
+ imported.
142
+ """
143
+ document = (
144
+ dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
145
+ )
146
+ surface = CliSurface.load(document, key=cli_key)
147
+ app = CliApp.from_surface(surface, **typer_kwargs)
148
+ if lifecycle_key not in document:
149
+ return app
150
+
151
+ declared = LifecycleSurface.load(document, key=lifecycle_key)
152
+ occupied = (
153
+ {declared.namespace} if declared.namespace is not None else set(declared.verbs)
154
+ )
155
+ collisions = occupied & {command.name for command in surface.commands}
156
+ if collisions:
157
+ raise AppException(
158
+ "Duplicate command name(s): {}", ", ".join(sorted(collisions))
159
+ )
160
+
161
+ try:
162
+ product = AppUtils.import_string(declared.product)
163
+ except Exception as error:
164
+ raise AppException(
165
+ "Cannot import lifecycle product {!r}: {}", declared.product, error
166
+ ) from error
167
+ commands = lifecycle_commands(product, declared.verbs)
168
+ if declared.namespace is not None:
169
+ app.add_typer(
170
+ commands,
171
+ name=declared.namespace,
172
+ help="Install, upgrade and check this tool itself.",
173
+ )
174
+ else:
175
+ app.add_typer(commands)
176
+ return app
177
+
178
+
179
+ def _duplicates(names: Iterable[str]) -> list[str]:
180
+ """Names appearing more than once, in first-seen order."""
181
+ seen: set[str] = set()
182
+ repeated: list[str] = []
183
+ for name in names:
184
+ if name in seen and name not in repeated:
185
+ repeated.append(name)
186
+ seen.add(name)
187
+ return repeated
188
+
189
+
190
+ def _emit(record: DataclassMixin, text: str) -> None:
191
+ """Print *record* as JSON in ``--json`` mode, *text* otherwise."""
192
+ if console.mode is OutputMode.JSON:
193
+ console.emit(record.as_dict())
194
+ else:
195
+ console.success("{}", text)
196
+
197
+
198
+ def _add_install(app: typer.Typer, product: ToolProduct) -> None:
199
+ @app.command("install")
200
+ def install(
201
+ version: Annotated[
202
+ str | None,
203
+ typer.Option("--version", help="Version to install. Default: latest."),
204
+ ] = None,
205
+ archive: Annotated[
206
+ Path | None,
207
+ typer.Option("--archive", help="Install from a local archive instead."),
208
+ ] = None,
209
+ force: Annotated[
210
+ bool, typer.Option("--force", help="Reinstall the active version.")
211
+ ] = False,
212
+ ) -> None:
213
+ """Install a release and make it the active version."""
214
+ source = None
215
+ if archive is not None:
216
+ if version is None:
217
+ raise typer.BadParameter("--archive needs --version")
218
+ source = LocalArchive(archive, version)
219
+ result = lifecycle.install(product, version=version, source=source, force=force)
220
+ _emit(result, _install_text(result))
221
+
222
+
223
+ def _add_upgrade(app: typer.Typer, product: ToolProduct) -> None:
224
+ @app.command("upgrade")
225
+ def upgrade() -> None:
226
+ """Install the latest release over the current install."""
227
+ result = lifecycle.upgrade(product)
228
+ _emit(result, _install_text(result))
229
+
230
+
231
+ def _add_uninstall(app: typer.Typer, product: ToolProduct) -> None:
232
+ @app.command("uninstall")
233
+ def uninstall(ctx: typer.Context, yes: YesOption = False) -> None:
234
+ """Remove every installed version and everything the install put in place."""
235
+ if not CliOptions.from_context(ctx, yes=yes).yes and not console.confirm(
236
+ f"Remove {product.name} and every installed version?"
237
+ ):
238
+ raise typer.Abort()
239
+ result = lifecycle.uninstall(product)
240
+ _emit(
241
+ result,
242
+ f"{product.name} removed"
243
+ if result.outcome == "removed"
244
+ else f"{product.name} is not installed",
245
+ )
246
+
247
+
248
+ def _add_cleanup(app: typer.Typer, product: ToolProduct) -> None:
249
+ @app.command("cleanup")
250
+ def cleanup(ctx: typer.Context, yes: YesOption = False) -> None:
251
+ """Remove every installed version except the active one."""
252
+ planned = lifecycle.cleanup(product, dry_run=True)
253
+ if planned.removed and not (
254
+ CliOptions.from_context(ctx, yes=yes).yes
255
+ or console.confirm(
256
+ f"Remove {', '.join(planned.removed)} (keeping {planned.kept})?"
257
+ )
258
+ ):
259
+ raise typer.Abort()
260
+ result = lifecycle.cleanup(product)
261
+ _emit(
262
+ result,
263
+ f"removed {len(result.removed)} version(s), kept {result.kept}",
264
+ )
265
+
266
+
267
+ def _add_status(app: typer.Typer, product: ToolProduct) -> None:
268
+ @app.command("status")
269
+ def status() -> None:
270
+ """Show the running version and what is installed."""
271
+ result = lifecycle.status(product)
272
+ _emit(
273
+ result,
274
+ f"{result.product} {result.version} — installed: "
275
+ f"{result.installed or 'none'} ({result.home})",
276
+ )
277
+
278
+
279
+ def _add_doctor(app: typer.Typer, product: ToolProduct) -> None:
280
+ @app.command("doctor")
281
+ def doctor() -> None:
282
+ """Check the install and the product's own health."""
283
+ findings = lifecycle.doctor(product)
284
+ if console.mode is OutputMode.JSON:
285
+ console.emit({"findings": [finding.as_dict() for finding in findings]})
286
+ else:
287
+ for finding in findings:
288
+ # `markup=False`: a finding's `[code]` is not Rich markup, and
289
+ # the code is the part a reader searches for.
290
+ console.print(f"{finding.severity}: {finding}", markup=False)
291
+ if any(finding.is_error for finding in findings):
292
+ raise typer.Exit(1)
293
+
294
+
295
+ def _install_text(result: lifecycle.InstallResult) -> str:
296
+ if result.outcome == "already-current":
297
+ return f"{result.product} {result.version} is already active"
298
+ return (
299
+ f"{result.product} {result.version} installed (was {result.previous or 'none'})"
300
+ )
301
+
302
+
303
+ _COMMANDS = {
304
+ "install": _add_install,
305
+ "upgrade": _add_upgrade,
306
+ "uninstall": _add_uninstall,
307
+ "cleanup": _add_cleanup,
308
+ "status": _add_status,
309
+ "doctor": _add_doctor,
310
+ }