rn-forge-tooling 0.3.1__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.
@@ -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
+ }
@@ -0,0 +1,44 @@
1
+ """Release sources, workstation installation, and lifecycle operations."""
2
+
3
+ from rn_forge.tooling.install.archive import extract_archive
4
+ from rn_forge.tooling.install.home import ToolHome, rnf_home
5
+ from rn_forge.tooling.install.lifecycle import (
6
+ CleanupResult,
7
+ InstallResult,
8
+ InstallStatus,
9
+ cleanup,
10
+ doctor,
11
+ install,
12
+ status,
13
+ uninstall,
14
+ upgrade,
15
+ )
16
+ from rn_forge.tooling.install.product import Check, Link, ToolProduct
17
+ from rn_forge.tooling.install.release import (
18
+ GitHubReleases,
19
+ LocalArchive,
20
+ ReleaseSource,
21
+ fetch_release,
22
+ )
23
+
24
+ __all__ = [
25
+ "Check",
26
+ "CleanupResult",
27
+ "GitHubReleases",
28
+ "InstallResult",
29
+ "InstallStatus",
30
+ "Link",
31
+ "LocalArchive",
32
+ "ReleaseSource",
33
+ "ToolHome",
34
+ "ToolProduct",
35
+ "cleanup",
36
+ "doctor",
37
+ "extract_archive",
38
+ "fetch_release",
39
+ "install",
40
+ "rnf_home",
41
+ "status",
42
+ "uninstall",
43
+ "upgrade",
44
+ ]
@@ -0,0 +1,55 @@
1
+ """Safe extraction of single-root tar and zip release bundles."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tarfile
6
+ import zipfile
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from rn_forge.commons.exceptions import AppException
11
+
12
+ __all__ = ["extract_archive"]
13
+
14
+
15
+ def extract_archive(
16
+ archive: str | Path,
17
+ destination: str | Path,
18
+ *,
19
+ filter: Literal["data", "tar", "fully_trusted"] = "data",
20
+ ) -> Path:
21
+ """Extract a ``.tar``/``.zip`` *archive* into *destination*, returning its root dir.
22
+
23
+ Args:
24
+ archive: The archive file. Tar formats (``.tar``, ``.tar.gz``,
25
+ ``.tar.bz2``, ...) are detected by content; anything else is
26
+ treated as a zip.
27
+ destination: Directory the archive's contents are extracted into.
28
+ Created if absent.
29
+ filter: The :func:`tarfile.TarFile.extractall` extraction filter
30
+ for tar archives. Zip extraction has no equivalent parameter.
31
+
32
+ Returns:
33
+ The single top-level directory the archive extracted into.
34
+
35
+ Raises:
36
+ AppException: The archive's root does not contain exactly one
37
+ directory.
38
+ """
39
+ archive = Path(archive)
40
+ dest = Path(destination)
41
+ dest.mkdir(parents=True, exist_ok=True)
42
+ if tarfile.is_tarfile(archive):
43
+ with tarfile.open(archive) as tar:
44
+ tar.extractall(dest, filter=filter) # noqa: S202 # tar filter passed by the caller
45
+ else:
46
+ with zipfile.ZipFile(archive) as zip_file:
47
+ zip_file.extractall(dest) # noqa: S202 # zipfile drops absolute and `..` member paths
48
+ entries = [item for item in dest.iterdir() if item.is_dir()]
49
+ if len(entries) != 1:
50
+ raise AppException(
51
+ "Expected exactly one root directory in archive {}, found {}",
52
+ archive,
53
+ len(entries),
54
+ )
55
+ return entries[0]
@@ -0,0 +1,117 @@
1
+ """Filesystem layout and activation for installed tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ from rn_forge.commons.exceptions import AppException
10
+ from rn_forge.commons.fs.locks import DirectoryLock, atomic_symlink
11
+
12
+ __all__ = ["DEFAULT_RNF_HOME", "RNF_HOME_ENV", "ToolHome", "rnf_home"]
13
+
14
+ RNF_HOME_ENV = "RNF_HOME"
15
+ """The environment variable that relocates every installed tool."""
16
+
17
+ DEFAULT_RNF_HOME = "~/.rn-forge"
18
+ """The home used when :data:`RNF_HOME_ENV` is unset or empty."""
19
+
20
+ _SEGMENT = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$")
21
+ """A product name or version: one path segment that cannot climb out of its parent."""
22
+
23
+
24
+ def rnf_home() -> Path:
25
+ """Return ``$RNF_HOME``, or ``~/.rn-forge`` when it is unset or empty."""
26
+ return Path(os.environ.get(RNF_HOME_ENV) or DEFAULT_RNF_HOME).expanduser()
27
+
28
+
29
+ def _segment(value: str, what: str) -> str:
30
+ """Return *value* unchanged, or raise if it is not a single safe path segment."""
31
+ if not _SEGMENT.match(value):
32
+ raise AppException(
33
+ "Invalid {} {!r}: must be a single path segment", what, value
34
+ )
35
+ return value
36
+
37
+
38
+ class ToolHome:
39
+ """The on-disk layout of one product under ``$RNF_HOME``."""
40
+
41
+ def __init__(self, name: str, root: str | Path | None = None) -> None:
42
+ """Initialize :class:`ToolHome`.
43
+
44
+ Args:
45
+ name: The product name; its directory under *root*.
46
+ root: The home directory. Defaults to :func:`rnf_home`, resolved
47
+ now rather than per access, so one instance never straddles a
48
+ change to the environment.
49
+
50
+ Raises:
51
+ AppException: *name* is not a single path segment.
52
+ """
53
+ self.name = _segment(name, "product name")
54
+ self.root = Path(root).expanduser() if root is not None else rnf_home()
55
+
56
+ @property
57
+ def product_dir(self) -> Path:
58
+ """``<home>/<product>/``."""
59
+ return self.root / self.name
60
+
61
+ @property
62
+ def versions_dir(self) -> Path:
63
+ """``<home>/<product>/versions/``."""
64
+ return self.product_dir / "versions"
65
+
66
+ @property
67
+ def current(self) -> Path:
68
+ """The ``current`` symlink. May not exist."""
69
+ return self.product_dir / "current"
70
+
71
+ @property
72
+ def state_path(self) -> Path:
73
+ """``<home>/<product>/state.json``."""
74
+ return self.product_dir / "state.json"
75
+
76
+ @property
77
+ def work_dir(self) -> Path:
78
+ """Scratch space for a transaction in flight; removed when it finishes."""
79
+ return self.product_dir / ".work"
80
+
81
+ def version_dir(self, version: str) -> Path:
82
+ """``<home>/<product>/versions/<version>/``.
83
+
84
+ Raises:
85
+ AppException: *version* is not a single path segment — a release
86
+ source is remote input, and ``../..`` is a version string too.
87
+ """
88
+ return self.versions_dir / _segment(version, "version")
89
+
90
+ def current_version(self) -> str | None:
91
+ """The version ``current`` points at, or ``None`` when there is no link."""
92
+ if not self.current.is_symlink():
93
+ return None
94
+ return Path(os.readlink(self.current)).name
95
+
96
+ def installed_versions(self) -> list[str]:
97
+ """Every version directory present, in name order."""
98
+ if not self.versions_dir.is_dir():
99
+ return []
100
+ return sorted(
101
+ entry.name
102
+ for entry in self.versions_dir.iterdir()
103
+ if entry.is_dir() and not entry.name.startswith(".")
104
+ )
105
+
106
+ def lock(self, *, timeout: float = 30.0) -> DirectoryLock:
107
+ """The lock every lifecycle verb that writes holds for its whole duration."""
108
+ return DirectoryLock(self.product_dir / ".lock", timeout=timeout)
109
+
110
+ def activate(self, version: str) -> None:
111
+ """Point ``current`` at *version*, atomically.
112
+
113
+ The link is relative (``versions/<version>``), so moving the whole home
114
+ does not break it.
115
+ """
116
+ self.product_dir.mkdir(parents=True, exist_ok=True)
117
+ atomic_symlink(self.current, Path("versions") / _segment(version, "version"))