rn-forge-tooling 0.3.1__tar.gz → 0.3.3__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-tooling
3
- Version: 0.3.1
3
+ Version: 0.3.3
4
4
  Summary: Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs
5
5
  Author: Rohit Narayanan
6
6
  Author-email: Rohit Narayanan <rohit.nn@gmail.com>
@@ -13,9 +13,9 @@ 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.9
17
- Requires-Dist: rn-forge-cli>=0.1.1,<0.2
18
- Requires-Dist: assertpy>=1.1 ; extra == 'testing'
16
+ Requires-Dist: rn-forge-commons>=0.8.0,<0.11
17
+ Requires-Dist: rn-forge-cli>=0.1.1,<0.3
18
+ Requires-Dist: assertpy>=2.35 ; extra == 'testing'
19
19
  Requires-Dist: pytest>=9.1.1 ; extra == 'testing'
20
20
  Requires-Python: >=3.14
21
21
  Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/
@@ -57,8 +57,8 @@ files in it. It owns:
57
57
  A repository that only needs a command line takes `rn-forge-cli` and stops
58
58
  there. A package that ships into a deployed runtime (`rn-forge-django`,
59
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.
60
+ Tooling may import cli and commons; neither may import tooling, and `task lint`
61
+ proves it.
62
62
 
63
63
  ## Install
64
64
 
@@ -69,27 +69,34 @@ Require the package by version range:
69
69
  dependencies = ["rn-forge-tooling>=0.3,<0.4"]
70
70
  ```
71
71
 
72
- `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges.
72
+ `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges. The
73
+ `testing` extra installs `assertpy` and `pytest`.
73
74
 
74
- ## Docs
75
+ ## Minimum example
75
76
 
76
- Full API reference and guides are built with mkdocs:
77
+ ```toml
78
+ # cli.toml
79
+ [cli]
80
+ name = "golden-tool"
81
+ help = "A tool that manages its own install."
77
82
 
78
- ```bash
79
- uv run --group docs mkdocs serve # or `mkdocs build`
83
+ [lifecycle]
84
+ product = "golden_tool.product:PRODUCT"
80
85
  ```
81
86
 
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
87
+ ```python
88
+ from pathlib import Path
88
89
 
89
- From the repo root or this directory:
90
+ from rn_forge.tooling.cli.lifecycle import build_tool_app
90
91
 
91
- ```bash
92
- uv run pytest packages/rn-forge-tooling
93
- uv run ruff check packages/rn-forge-tooling
94
- uv run pyright
92
+ app = build_tool_app(Path(__file__).parent / "cli.toml")
95
93
  ```
94
+
95
+ ## Errors
96
+
97
+ `install` and `upgrade` roll back on failure and re-raise as an `AppException`
98
+ whose message says "rolled back" only when every undo step succeeded; otherwise
99
+ it names each failed step. An interruption is re-raised as is after recovery.
100
+
101
+ Maintainer commands are in the
102
+ [development guide](https://rn-forge.github.io/pykit/guides/development/).
@@ -30,8 +30,8 @@ files in it. It owns:
30
30
  A repository that only needs a command line takes `rn-forge-cli` and stops
31
31
  there. A package that ships into a deployed runtime (`rn-forge-django`,
32
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.
33
+ Tooling may import cli and commons; neither may import tooling, and `task lint`
34
+ proves it.
35
35
 
36
36
  ## Install
37
37
 
@@ -42,27 +42,34 @@ Require the package by version range:
42
42
  dependencies = ["rn-forge-tooling>=0.3,<0.4"]
43
43
  ```
44
44
 
45
- `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges.
45
+ `rn-forge-cli` and `rn-forge-commons` come with it, as version ranges. The
46
+ `testing` extra installs `assertpy` and `pytest`.
46
47
 
47
- ## Docs
48
+ ## Minimum example
48
49
 
49
- Full API reference and guides are built with mkdocs:
50
+ ```toml
51
+ # cli.toml
52
+ [cli]
53
+ name = "golden-tool"
54
+ help = "A tool that manages its own install."
50
55
 
51
- ```bash
52
- uv run --group docs mkdocs serve # or `mkdocs build`
56
+ [lifecycle]
57
+ product = "golden_tool.product:PRODUCT"
53
58
  ```
54
59
 
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
60
+ ```python
61
+ from pathlib import Path
61
62
 
62
- From the repo root or this directory:
63
+ from rn_forge.tooling.cli.lifecycle import build_tool_app
63
64
 
64
- ```bash
65
- uv run pytest packages/rn-forge-tooling
66
- uv run ruff check packages/rn-forge-tooling
67
- uv run pyright
65
+ app = build_tool_app(Path(__file__).parent / "cli.toml")
68
66
  ```
67
+
68
+ ## Errors
69
+
70
+ `install` and `upgrade` roll back on failure and re-raise as an `AppException`
71
+ whose message says "rolled back" only when every undo step succeeded; otherwise
72
+ it names each failed step. An interruption is re-raised as is after recovery.
73
+
74
+ Maintainer commands are in the
75
+ [development guide](https://rn-forge.github.io/pykit/guides/development/).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-tooling"
3
- version = "0.3.1"
3
+ version = "0.3.3"
4
4
  description = "Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -16,8 +16,8 @@ classifiers = [
16
16
  ]
17
17
  requires-python = ">=3.14"
18
18
  dependencies = [
19
- "rn-forge-commons>=0.8.0,<0.9",
20
- "rn-forge-cli>=0.1.1,<0.2",
19
+ "rn-forge-commons>=0.8.0,<0.11",
20
+ "rn-forge-cli>=0.1.1,<0.3",
21
21
  ]
22
22
 
23
23
  [[project.authors]]
@@ -26,7 +26,7 @@ email = "rohit.nn@gmail.com"
26
26
 
27
27
  [project.optional-dependencies]
28
28
  testing = [
29
- "assertpy>=1.1",
29
+ "assertpy>=2.35",
30
30
  "pytest>=9.1.1",
31
31
  ]
32
32
 
@@ -37,11 +37,19 @@ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooli
37
37
  Issues = "https://github.com/rn-forge/pykit/issues"
38
38
 
39
39
  [build-system]
40
- requires = ["uv_build>=0.11.28,<0.12.0"]
40
+ requires = ["uv_build>=0.13.7,<0.14.0"]
41
41
  build-backend = "uv_build"
42
42
 
43
+ [tool.pyright]
44
+ typeCheckingMode = "strict"
45
+ reportMissingTypeStubs = false
46
+ reportUnnecessaryTypeIgnoreComment = "error"
47
+ venv = ".venv"
48
+ venvPath = "../.."
49
+
43
50
  [tool.uv.build-backend]
44
51
  module-name = "rn_forge.tooling"
52
+ source-exclude = ["**/.DS_Store"]
45
53
 
46
54
  [tool.uv.sources.rn-forge-commons]
47
55
  workspace = true
@@ -58,7 +66,7 @@ markers = ["scaffold: installs built wheels into a scaffolded application (slow)
58
66
 
59
67
  [dependency-groups]
60
68
  dev = [
61
- "assertpy>=1.1",
69
+ "assertpy>=2.35",
62
70
  "pyright>=1.1.411",
63
71
  "pytest>=9.1.1",
64
72
  "pytest-cov>=7.1.0",
@@ -1,29 +1,26 @@
1
1
  [project]
2
2
  name = "rn-forge-tooling"
3
- version = "0.3.1"
3
+ version = "0.3.3"
4
4
  description = "Developer-tool lifecycle verbs and install mechanics for the rn-forge-* CLIs"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Rohit Narayanan", email = "rohit.nn@gmail.com" }]
7
7
  license = "MIT"
8
8
  license-files = ["LICENSE"]
9
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",
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
17
  ]
18
18
  requires-python = ">=3.14"
19
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
- ]
20
+ dependencies = ["rn-forge-commons>=0.8.0,<0.11", "rn-forge-cli>=0.1.1,<0.3"]
24
21
 
25
22
  [project.optional-dependencies]
26
- testing = ["assertpy>=1.1", "pytest>=9.1.1"]
23
+ testing = ["assertpy>=2.35", "pytest>=9.1.1"]
27
24
 
28
25
  [project.urls]
29
26
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/"
@@ -32,11 +29,19 @@ Changelog = "https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-tooli
32
29
  Issues = "https://github.com/rn-forge/pykit/issues"
33
30
 
34
31
  [build-system]
35
- requires = ["uv_build>=0.11.28,<0.12.0"]
32
+ requires = ["uv_build>=0.13.7,<0.14.0"]
36
33
  build-backend = "uv_build"
37
34
 
35
+ [tool.pyright]
36
+ typeCheckingMode = "strict"
37
+ reportMissingTypeStubs = false
38
+ reportUnnecessaryTypeIgnoreComment = "error"
39
+ venv = ".venv"
40
+ venvPath = "../.."
41
+
38
42
  [tool.uv.build-backend]
39
43
  module-name = "rn_forge.tooling"
44
+ source-exclude = ["**/.DS_Store"]
40
45
 
41
46
  [tool.uv.sources]
42
47
  rn-forge-commons = { workspace = true }
@@ -45,21 +50,23 @@ rn-forge-tooling = { workspace = true }
45
50
 
46
51
  [tool.pytest.ini_options]
47
52
  addopts = "-ra --import-mode=importlib -m 'not scaffold'"
48
- markers = ["scaffold: installs built wheels into a scaffolded application (slow)"]
53
+ markers = [
54
+ "scaffold: installs built wheels into a scaffolded application (slow)",
55
+ ]
49
56
 
50
57
  [dependency-groups]
51
58
  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
+ "assertpy>=2.35",
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-tooling",
65
+ "ruff>=0.15.21",
59
66
  ]
60
67
  docs = [
61
- "mkdocs>=1.6.1",
62
- "mkdocs-material>=9.7.6",
63
- "mkdocstrings[python]>=1.0.6",
64
- "rn-forge-tooling",
68
+ "mkdocs>=1.6.1",
69
+ "mkdocs-material>=9.7.6",
70
+ "mkdocstrings[python]>=1.0.6",
71
+ "rn-forge-tooling",
65
72
  ]
@@ -3,9 +3,9 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from collections.abc import Iterable, Mapping, Sequence
6
- from dataclasses import dataclass
6
+ from dataclasses import dataclass, field
7
7
  from pathlib import Path
8
- from typing import Annotated, Any, Self
8
+ from typing import Annotated, Any, Self, cast
9
9
 
10
10
  import typer
11
11
  from rn_forge.cli import CliApp, CliOptions, CliSurface, YesOption
@@ -20,39 +20,10 @@ from rn_forge.tooling.install.release import LocalArchive
20
20
 
21
21
  __all__ = ["VERBS", "LifecycleSurface", "build_tool_app", "lifecycle_commands"]
22
22
 
23
- VERBS = ("install", "upgrade", "uninstall", "cleanup", "status", "doctor")
24
- """Every verb this module can mount, in ``--help`` order."""
25
-
26
23
  LIFECYCLE_KEY = "lifecycle"
27
24
  """The table :meth:`LifecycleSurface.load` reads by default."""
28
25
 
29
26
 
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
27
  @dataclass(frozen=True, slots=True)
57
28
  class LifecycleSurface(DataclassMixin):
58
29
  """A declared ``[lifecycle]`` table: which verbs a tool exposes, and where.
@@ -66,7 +37,7 @@ class LifecycleSurface(DataclassMixin):
66
37
  """
67
38
 
68
39
  product: str
69
- verbs: tuple[str, ...] = VERBS
40
+ verbs: tuple[str, ...] = field(default_factory=lambda: VERBS)
70
41
  namespace: str | None = None
71
42
 
72
43
  def __post_init__(self) -> None:
@@ -106,9 +77,18 @@ class LifecycleSurface(DataclassMixin):
106
77
  dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
107
78
  )
108
79
  if key in data:
109
- data = data[key]
80
+ table = data[key]
81
+ if not isinstance(table, Mapping):
82
+ raise AppException("[{}] must be a table", key)
83
+ data = dict(cast(Mapping[str, Any], table))
110
84
  elif "product" not in data:
111
85
  raise AppException("No [{}] table to build lifecycle verbs from", key)
86
+ if "verbs" in data:
87
+ verbs = data["verbs"]
88
+ if not isinstance(verbs, list) or not all(
89
+ isinstance(verb, str) for verb in cast(list[object], verbs)
90
+ ):
91
+ raise AppException("Lifecycle verbs must be a list of strings")
112
92
  return cls.from_dict(dict(data))
113
93
 
114
94
 
@@ -209,21 +189,34 @@ def _add_install(app: typer.Typer, product: ToolProduct) -> None:
209
189
  force: Annotated[
210
190
  bool, typer.Option("--force", help="Reinstall the active version.")
211
191
  ] = False,
192
+ ref: Annotated[
193
+ str | None,
194
+ typer.Option(
195
+ "--ref",
196
+ help="Install a branch, tag or commit of the product's GitHub repository.",
197
+ ),
198
+ ] = None,
212
199
  ) -> None:
213
200
  """Install a release and make it the active version."""
201
+ if ref is not None and (version is not None or archive is not None):
202
+ raise typer.BadParameter(
203
+ "--ref cannot be combined with --version or --archive"
204
+ )
214
205
  source = None
215
206
  if archive is not None:
216
207
  if version is None:
217
208
  raise typer.BadParameter("--archive needs --version")
218
209
  source = LocalArchive(archive, version)
219
- result = lifecycle.install(product, version=version, source=source, force=force)
210
+ result = lifecycle.install(
211
+ product, version=version, source=source, force=force, ref=ref
212
+ )
220
213
  _emit(result, _install_text(result))
221
214
 
222
215
 
223
216
  def _add_upgrade(app: typer.Typer, product: ToolProduct) -> None:
224
217
  @app.command("upgrade")
225
218
  def upgrade() -> None:
226
- """Install the latest release over the current install."""
219
+ """Install the latest release, or the recorded ref's current commit, over the current install."""
227
220
  result = lifecycle.upgrade(product)
228
221
  _emit(result, _install_text(result))
229
222
 
@@ -269,10 +262,16 @@ def _add_status(app: typer.Typer, product: ToolProduct) -> None:
269
262
  def status() -> None:
270
263
  """Show the running version and what is installed."""
271
264
  result = lifecycle.status(product)
265
+ installed = result.installed or "none"
266
+ if result.commit is not None:
267
+ installed = (
268
+ f"{result.package_version or installed} "
269
+ f"({result.ref} @ {result.commit[:12]})"
270
+ )
272
271
  _emit(
273
272
  result,
274
273
  f"{result.product} {result.version} — installed: "
275
- f"{result.installed or 'none'} ({result.home})",
274
+ f"{installed} ({result.home})",
276
275
  )
277
276
 
278
277
 
@@ -308,3 +307,33 @@ _COMMANDS = {
308
307
  "status": _add_status,
309
308
  "doctor": _add_doctor,
310
309
  }
310
+ """Command adders in ``--help`` order."""
311
+
312
+ VERBS = tuple(_COMMANDS)
313
+ """Every verb this module can mount, in ``--help`` order."""
314
+
315
+
316
+ def lifecycle_commands(
317
+ product: ToolProduct, verbs: Sequence[str] = VERBS
318
+ ) -> typer.Typer:
319
+ """Return a Typer app holding *verbs* as commands over *product*.
320
+
321
+ Args:
322
+ product: The product the commands act on.
323
+ verbs: Which of :data:`VERBS` to include.
324
+
325
+ Raises:
326
+ AppException: *product* is not a :class:`ToolProduct`, or a verb is
327
+ not one of :data:`VERBS`.
328
+ """
329
+ if not isinstance(product, ToolProduct): # pyright: ignore[reportUnnecessaryIsInstance] - named by a config string
330
+ raise AppException("{!r} is not a ToolProduct", product)
331
+ unknown = sorted(set(verbs) - set(VERBS))
332
+ if unknown:
333
+ raise AppException("Unknown lifecycle verb(s): {}", ", ".join(unknown))
334
+
335
+ app = typer.Typer()
336
+ for verb, add_command in _COMMANDS.items():
337
+ if verb in verbs:
338
+ add_command(app, product)
339
+ return app
@@ -14,6 +14,7 @@ from rn_forge.tooling.install.lifecycle import (
14
14
  upgrade,
15
15
  )
16
16
  from rn_forge.tooling.install.product import Check, Link, ToolProduct
17
+ from rn_forge.tooling.install.python import PythonTool
17
18
  from rn_forge.tooling.install.release import (
18
19
  GitHubReleases,
19
20
  LocalArchive,
@@ -29,6 +30,7 @@ __all__ = [
29
30
  "InstallStatus",
30
31
  "Link",
31
32
  "LocalArchive",
33
+ "PythonTool",
32
34
  "ReleaseSource",
33
35
  "ToolHome",
34
36
  "ToolProduct",
@@ -75,7 +75,10 @@ class ToolHome:
75
75
 
76
76
  @property
77
77
  def work_dir(self) -> Path:
78
- """Scratch space for a transaction in flight; removed when it finishes."""
78
+ """Scratch space holding unique transaction directories.
79
+
80
+ A failed restoration retains its displaced version here; cleanup keeps it.
81
+ """
79
82
  return self.product_dir / ".work"
80
83
 
81
84
  def version_dir(self, version: str) -> Path:
@@ -5,9 +5,12 @@ from __future__ import annotations
5
5
  import json
6
6
  import os
7
7
  import shutil
8
+ import tempfile
9
+ import tomllib
8
10
  from collections.abc import Callable
9
11
  from dataclasses import dataclass, field
10
12
  from pathlib import Path
13
+ from typing import Any, cast
11
14
 
12
15
  from rn_forge.commons.exceptions import AppException
13
16
  from rn_forge.commons.findings import Finding, Severity
@@ -15,9 +18,14 @@ from rn_forge.commons.fs.locks import atomic_symlink
15
18
  from rn_forge.commons.fs.paths import PathUtils
16
19
  from rn_forge.commons.lang.dataclasses import DataclassMixin
17
20
  from rn_forge.commons.logging import AppLogger
21
+ from rn_forge.tooling.install.archive import extract_archive
18
22
  from rn_forge.tooling.install.home import ToolHome
19
23
  from rn_forge.tooling.install.product import Link, ToolProduct
20
- from rn_forge.tooling.install.release import ReleaseSource, fetch_release
24
+ from rn_forge.tooling.install.release import (
25
+ GitHubReleases,
26
+ ReleaseSource,
27
+ fetch_release,
28
+ )
21
29
 
22
30
  __all__ = [
23
31
  "CleanupResult",
@@ -79,6 +87,10 @@ class InstallStatus(DataclassMixin):
79
87
  home: The product's directory.
80
88
  installed: The version ``current`` points at, or ``None``.
81
89
  versions: Every version directory present.
90
+ ref: What the install was asked for: a branch, tag or commit SHA, or
91
+ the release tag. ``None`` when nothing is recorded.
92
+ commit: The installed commit's SHA for a ref install, else ``None``.
93
+ package_version: The package version recorded at install, or ``None``.
82
94
  """
83
95
 
84
96
  product: str
@@ -86,6 +98,9 @@ class InstallStatus(DataclassMixin):
86
98
  home: str
87
99
  installed: str | None = None
88
100
  versions: list[str] = field(default_factory=list[str])
101
+ ref: str | None = None
102
+ commit: str | None = None
103
+ package_version: str | None = None
89
104
 
90
105
 
91
106
  def install(
@@ -95,29 +110,52 @@ def install(
95
110
  source: ReleaseSource | None = None,
96
111
  home: ToolHome | None = None,
97
112
  force: bool = False,
113
+ ref: str | None = None,
98
114
  ) -> InstallResult:
99
- """Install *version* of *product* and make it the active one.
115
+ """Install *version* of *product*, or the commit *ref* names, and make it active.
100
116
 
101
117
  Args:
102
118
  product: The product to install.
103
119
  version: The version to install. Defaults to the source's latest.
120
+ Not combined with *ref*.
104
121
  source: Where to fetch from. Defaults to ``product.source``.
105
122
  home: The home to install into. Defaults to the product's.
106
123
  force: Reinstall even when *version* is already active.
124
+ ref: A branch, tag or commit SHA of the source's GitHub repository.
125
+ The install is recorded under the first 12 characters of the
126
+ commit.
107
127
 
108
128
  Raises:
109
- AppException: Any step failed; everything it did has been undone.
110
- BaseException: An interruption, re-raised once everything is undone.
129
+ AppException: Both *version* and *ref* were given, *ref* was given
130
+ for a source that is not a :class:`GitHubReleases`, the product's
131
+ ``preflight`` refused, or a step failed; all undo steps were
132
+ attempted, with any recovery failures and retained displaced
133
+ version's path reported.
134
+ BaseException: An interruption, re-raised after recovery with any
135
+ recovery failures and retained path logged at error level.
111
136
  """
112
137
  home = home or ToolHome(product.name)
138
+ product.preflight()
113
139
  source = source or product.source
114
- target = version or source.latest()
140
+ sha: str | None = None
141
+ if ref is not None:
142
+ if version is not None:
143
+ raise AppException("A version and a ref cannot be combined")
144
+ if not isinstance(source, GitHubReleases):
145
+ raise AppException(
146
+ "{} cannot install a ref: its source is not a GitHub repository",
147
+ product.name,
148
+ )
149
+ sha = source.resolve(ref)
150
+ target = sha[:12]
151
+ else:
152
+ target = version or source.latest()
115
153
  home.version_dir(target) # validates the version before anything is written
116
154
  with home.lock():
117
155
  previous = home.current_version()
118
156
  if previous == target and not force:
119
157
  return InstallResult(product.name, "already-current", target, previous)
120
- _install(product, home, source, target, previous)
158
+ _install(product, home, source, target, previous, ref, sha)
121
159
  _LOGGER.verbose("install: {} {} active (was {})", product.name, target, previous)
122
160
  return InstallResult(product.name, "installed", target, previous)
123
161
 
@@ -128,7 +166,11 @@ def upgrade(
128
166
  source: ReleaseSource | None = None,
129
167
  home: ToolHome | None = None,
130
168
  ) -> InstallResult:
131
- """Install the latest version over an existing install.
169
+ """Move an existing install forward.
170
+
171
+ A ref install re-resolves its recorded ref and installs that commit, or
172
+ returns ``already-current`` when it has not moved. Any other install moves
173
+ to the source's latest version.
132
174
 
133
175
  Raises:
134
176
  AppException: The product is not installed, or the install failed.
@@ -140,6 +182,10 @@ def upgrade(
140
182
  product.name,
141
183
  home.product_dir,
142
184
  )
185
+ recorded = _recorded(product, home)
186
+ ref, commit = recorded.get("ref"), recorded.get("commit")
187
+ if isinstance(ref, str) and ref and isinstance(commit, str) and commit:
188
+ return install(product, source=source, home=home, ref=ref)
143
189
  return install(product, source=source, home=home)
144
190
 
145
191
 
@@ -186,19 +232,32 @@ def cleanup(
186
232
  stale = [v for v in home.installed_versions() if v != current]
187
233
  for stale_version in stale:
188
234
  shutil.rmtree(home.version_dir(stale_version))
189
- shutil.rmtree(home.work_dir, ignore_errors=True)
235
+ if home.work_dir.is_dir():
236
+ for entry in home.work_dir.iterdir():
237
+ if entry.is_dir() and (entry / "displaced").exists():
238
+ _LOGGER.warning( # noqa: PLE1205 # brace-style log format
239
+ "Keeping retained transaction directory {}", entry
240
+ )
241
+ elif entry.is_dir() and not entry.is_symlink():
242
+ shutil.rmtree(entry, ignore_errors=True)
243
+ else:
244
+ entry.unlink(missing_ok=True)
190
245
  return CleanupResult(product.name, current, stale)
191
246
 
192
247
 
193
248
  def status(product: ToolProduct, *, home: ToolHome | None = None) -> InstallStatus:
194
249
  """Report the running version and what is installed. Writes nothing."""
195
250
  home = home or ToolHome(product.name)
251
+ recorded = _recorded(product, home)
196
252
  return InstallStatus(
197
253
  product=product.name,
198
254
  version=product.version,
199
255
  home=str(home.product_dir),
200
256
  installed=home.current_version(),
201
257
  versions=home.installed_versions(),
258
+ ref=_text(recorded, "ref"),
259
+ commit=_text(recorded, "commit"),
260
+ package_version=_text(recorded, "version"),
202
261
  )
203
262
 
204
263
 
@@ -223,61 +282,214 @@ def doctor(product: ToolProduct, *, home: ToolHome | None = None) -> list[Findin
223
282
  # -- install transaction ----------------------------------------------------
224
283
 
225
284
 
285
+ @dataclass(frozen=True, slots=True)
286
+ class _Prepared:
287
+ """A transaction's work directory and verified, extracted release root."""
288
+
289
+ work: Path
290
+ release_root: Path
291
+
292
+
226
293
  def _install(
227
294
  product: ToolProduct,
228
295
  home: ToolHome,
229
296
  source: ReleaseSource,
230
297
  target: str,
231
298
  previous: str | None,
299
+ ref: str | None,
300
+ sha: str | None,
232
301
  ) -> None:
233
- """The install transaction proper. The caller holds the lock."""
234
- undo: list[Callable[[], object]] = []
235
- work = home.work_dir / f"{target}-{os.getpid()}"
236
- shutil.rmtree(work, ignore_errors=True)
237
- version_dir = home.version_dir(target)
238
- displaced = work / "displaced"
302
+ """Prepare and activate a release or commit. The caller holds the lock."""
303
+ prepared = _prepare(product, home, source, target, sha)
304
+ undo: list[tuple[str, Callable[[], object]]] = []
305
+ retained = False
239
306
  try:
240
- release_root = fetch_release(source, target, work / "release")
307
+ _activate(product, home, source, prepared, target, previous, ref, sha, undo)
308
+ except BaseException as exc:
309
+ failures = _recover(undo)
310
+ retained = (prepared.work / "displaced").exists()
311
+ _failure(product, target, exc, failures, prepared.work, retained)
312
+ raise
313
+ finally:
314
+ if not retained:
315
+ shutil.rmtree(prepared.work, ignore_errors=True)
241
316
 
242
- if version_dir.exists():
243
- # A reinstall: set the existing directory aside rather than
244
- # deleting it, so a failed rebuild can put it back.
245
- version_dir.rename(displaced)
246
- undo.append(lambda: displaced.rename(version_dir))
247
- version_dir.parent.mkdir(parents=True, exist_ok=True)
248
- undo.append(lambda: shutil.rmtree(version_dir, ignore_errors=True))
249
- product.build(release_root, version_dir)
250
317
 
251
- for link in product.artifacts():
252
- undo.append(_place_link(home, link))
253
-
254
- undo.append(_restore_file(home.state_path))
255
- if previous is not None and previous != target:
256
- product.migrate(previous, target)
257
- PathUtils.atomic_write(
258
- json.dumps(
259
- {"version": target, "schema_version": product.state_schema_version},
260
- indent=2,
261
- )
262
- + "\n",
263
- home.state_path,
318
+ def _prepare(
319
+ product: ToolProduct,
320
+ home: ToolHome,
321
+ source: ReleaseSource,
322
+ target: str,
323
+ sha: str | None,
324
+ ) -> _Prepared:
325
+ """Download, verify and extract a release or commit; remove its work directory on failure."""
326
+ work: Path | None = None
327
+ try:
328
+ home.work_dir.mkdir(parents=True, exist_ok=True)
329
+ work = Path(tempfile.mkdtemp(prefix=f"{target}-", dir=home.work_dir))
330
+ if sha is None:
331
+ root = fetch_release(source, target, work / "release")
332
+ else:
333
+ assert isinstance(source, GitHubReleases) # noqa: S101 # checked by install
334
+ (work / "release").mkdir()
335
+ archive = source.download_commit(sha, work / "release")
336
+ root = extract_archive(archive, work / "release" / "extracted")
337
+ return _Prepared(work, root)
338
+ except BaseException as exc:
339
+ if work is not None:
340
+ shutil.rmtree(work, ignore_errors=True)
341
+ _failure(product, target, exc, [], work, False)
342
+ raise
343
+
344
+
345
+ def _activate(
346
+ product: ToolProduct,
347
+ home: ToolHome,
348
+ source: ReleaseSource,
349
+ prepared: _Prepared,
350
+ target: str,
351
+ previous: str | None,
352
+ ref: str | None,
353
+ sha: str | None,
354
+ undo: list[tuple[str, Callable[[], object]]],
355
+ ) -> None:
356
+ """Build and activate a release, appending recovery steps to *undo*."""
357
+ version_dir = home.version_dir(target)
358
+ displaced = prepared.work / "displaced"
359
+ if version_dir.exists():
360
+ # A failed reinstall must be able to put the existing directory back.
361
+ version_dir.rename(displaced)
362
+ undo.append(
363
+ ("restore displaced version", lambda: displaced.rename(version_dir))
264
364
  )
365
+ version_dir.parent.mkdir(parents=True, exist_ok=True)
366
+ undo.append(
367
+ (
368
+ f"remove versions/{target}",
369
+ lambda: shutil.rmtree(version_dir, ignore_errors=True),
370
+ )
371
+ )
372
+ product.build(prepared.release_root, version_dir)
265
373
 
266
- undo.append(_restore_current(home))
267
- home.activate(target)
268
- except BaseException as exc:
269
- for step in reversed(undo):
374
+ for link in product.artifacts():
375
+ undo.append((f"restore link {link.path}", _place_link(home, link)))
376
+
377
+ undo.append(("restore state.json", _restore_file(home.state_path)))
378
+ if previous is not None and previous != target:
379
+ product.migrate(previous, target)
380
+ PathUtils.atomic_write(
381
+ json.dumps(
382
+ {
383
+ "version": target if sha is None else _source_version(prepared, target),
384
+ "ref": ref if ref is not None else _tag(source, target),
385
+ "commit": sha,
386
+ "schema_version": product.state_schema_version,
387
+ },
388
+ indent=2,
389
+ )
390
+ + "\n",
391
+ home.state_path,
392
+ )
393
+
394
+ undo.append(("restore current", _restore_current(home)))
395
+ home.activate(target)
396
+
397
+
398
+ def _text(recorded: dict[str, Any], key: str) -> str | None:
399
+ """*key*'s value when it is a non-empty string."""
400
+ value = recorded.get(key)
401
+ return value if isinstance(value, str) and value else None
402
+
403
+
404
+ def _recorded(product: ToolProduct, home: ToolHome) -> dict[str, Any]:
405
+ """``state.json``'s object, or ``{}`` when it cannot be read.
406
+
407
+ A state with no ``ref`` was recorded as a release install: its ``ref`` is
408
+ the release tag and its ``commit`` is ``None``.
409
+ """
410
+ try:
411
+ state = json.loads(home.state_path.read_text(encoding="utf-8"))
412
+ except OSError, ValueError:
413
+ return {}
414
+ if not isinstance(state, dict):
415
+ return {}
416
+ recorded = cast(dict[str, Any], state)
417
+ if "ref" not in recorded:
418
+ version = _text(recorded, "version") or home.current_version()
419
+ if version is not None:
420
+ try:
421
+ source: ReleaseSource | None = product.source
422
+ except AppException:
423
+ source = None
424
+ recorded["ref"] = version if source is None else _tag(source, version)
425
+ recorded["commit"] = None
426
+ return recorded
427
+
428
+
429
+ def _tag(source: ReleaseSource, target: str) -> str:
430
+ """The tag a release install came from."""
431
+ if isinstance(source, GitHubReleases):
432
+ return source.tag_prefix + target
433
+ return target
434
+
435
+
436
+ def _source_version(prepared: _Prepared, default: str) -> str:
437
+ """``[project] version`` of the extracted tree, or *default* when absent."""
438
+ try:
439
+ with (prepared.release_root / "pyproject.toml").open("rb") as stream:
440
+ return str(tomllib.load(stream)["project"]["version"])
441
+ except OSError, KeyError, TypeError, ValueError:
442
+ return default
443
+
444
+
445
+ def _recover(
446
+ undo: list[tuple[str, Callable[[], object]]],
447
+ ) -> list[tuple[str, Exception]]:
448
+ """Attempt every undo step in reverse order and return recovery failures."""
449
+ failures: list[tuple[str, Exception]] = []
450
+ for label, step in reversed(undo):
451
+ try:
270
452
  step()
453
+ except Exception as error: # noqa: BLE001 - attempt every undo step
454
+ failures.append((label, error))
455
+ return failures
456
+
457
+
458
+ def _failure(
459
+ product: ToolProduct,
460
+ target: str,
461
+ exc: BaseException,
462
+ failures: list[tuple[str, Exception]],
463
+ work: Path | None,
464
+ retained: bool,
465
+ ) -> None:
466
+ """Raise an install error, or log incomplete recovery for an interruption."""
467
+ if failures:
468
+ details = "; ".join(f"{label}: {error}" for label, error in failures)
469
+ if retained:
470
+ details += f"; the previous version is kept at {work}"
271
471
  if isinstance(exc, Exception):
272
472
  raise AppException(
273
- "Install of {} {} failed and was rolled back: {}",
473
+ "Install of {} {} failed: {}; recovery is incomplete: {}",
274
474
  product.name,
275
475
  target,
276
476
  exc,
477
+ details,
277
478
  ) from exc
278
- raise
279
- finally:
280
- shutil.rmtree(work, ignore_errors=True)
479
+ _LOGGER.error( # noqa: PLE1205 # brace-style log format
480
+ "Install of {} {} failed: {}; recovery is incomplete: {}",
481
+ product.name,
482
+ target,
483
+ exc,
484
+ details,
485
+ )
486
+ if isinstance(exc, Exception):
487
+ raise AppException(
488
+ "Install of {} {} failed and was rolled back: {}",
489
+ product.name,
490
+ target,
491
+ exc,
492
+ ) from exc
281
493
 
282
494
 
283
495
  def _link_target(home: ToolHome, link: Link) -> str:
@@ -362,13 +574,14 @@ def _install_findings(product: ToolProduct, home: ToolHome) -> list[Finding]:
362
574
  path=str(home.current),
363
575
  )
364
576
  )
365
- if current != product.version:
577
+ installed = _text(_recorded(product, home), "version") or current
578
+ if installed != product.version:
366
579
  findings.append(
367
580
  Finding(
368
581
  "install.version-mismatch",
369
582
  Severity.WARNING,
370
- f"running {product.version}, but {current} is installed",
371
- details={"running": product.version, "installed": current},
583
+ f"running {product.version}, but {installed} is installed",
584
+ details={"running": product.version, "installed": installed},
372
585
  )
373
586
  )
374
587
  findings.extend(_state_findings(product, home))
@@ -93,6 +93,13 @@ class ToolProduct:
93
93
  """Product-specific ``doctor`` checks. Default: none."""
94
94
  return ()
95
95
 
96
+ def preflight(self) -> None:
97
+ """Called by ``install`` before anything is written. Default: nothing.
98
+
99
+ Raises:
100
+ AppException: To refuse the install.
101
+ """
102
+
96
103
  def build(self, release_root: Path, version_dir: Path) -> None:
97
104
  """Turn an extracted release into an installed version directory.
98
105
 
@@ -0,0 +1,58 @@
1
+ """A product whose release is a Python package with a console script."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from rn_forge.commons.exceptions import AppException
12
+ from rn_forge.commons.runtime.subprocess import Process
13
+ from rn_forge.tooling.install.product import Link, ToolProduct
14
+
15
+ __all__ = ["PythonTool"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class PythonTool(ToolProduct):
20
+ """A Python tool installed with ``uv tool install``.
21
+
22
+ The package must declare a console script named :attr:`name`. ``uv`` must
23
+ be on ``PATH``; it is a program, not a dependency.
24
+ """
25
+
26
+ def artifacts(self) -> Sequence[Link]:
27
+ """The link ``bin/<name>`` to the console script."""
28
+ return (Link(f"bin/{self.name}", f"bin/{self.name}"),)
29
+
30
+ def preflight(self) -> None:
31
+ """Refuse the install when ``uv`` is not on ``PATH``.
32
+
33
+ Raises:
34
+ AppException: ``uv`` was not found.
35
+ """
36
+ if shutil.which("uv") is None:
37
+ raise AppException(
38
+ "{} needs uv on PATH to install; install uv first", self.name
39
+ )
40
+
41
+ def build(self, release_root: Path, version_dir: Path) -> None:
42
+ """Install the package at *release_root* into *version_dir*.
43
+
44
+ The console script ends up at ``<version_dir>/bin/<name>``.
45
+
46
+ Raises:
47
+ AppException: ``uv tool install`` failed.
48
+ """
49
+ # uv creates version_dir itself; the environment is built in place
50
+ # because its scripts hold absolute paths.
51
+ env = {
52
+ **os.environ,
53
+ "UV_TOOL_DIR": str(version_dir / "tool"),
54
+ "UV_TOOL_BIN_DIR": str(version_dir / "bin"),
55
+ }
56
+ Process.execute(
57
+ "uv tool install", "uv", "tool", "install", str(release_root), env=env
58
+ )
@@ -3,8 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import re
6
7
  import shutil
7
8
  import urllib.error
9
+ import urllib.parse
8
10
  import urllib.request
9
11
  from dataclasses import dataclass
10
12
  from pathlib import Path
@@ -19,6 +21,8 @@ __all__ = ["GitHubReleases", "LocalArchive", "ReleaseSource", "fetch_release"]
19
21
 
20
22
  _LOGGER = AppLogger.get_logger(__name__)
21
23
 
24
+ _SHA = re.compile(r"[0-9a-f]{40}")
25
+
22
26
  _TIMEOUT = 60.0
23
27
  """Seconds before a network request to a release host is abandoned."""
24
28
 
@@ -97,8 +101,47 @@ class GitHubReleases:
97
101
  AppException: The download failed.
98
102
  """
99
103
  tag = f"{self.tag_prefix}{version}"
100
- url = f"{self.web_url}/{self.repo}/archive/refs/tags/{tag}.tar.gz"
101
- archive = destination / f"{tag}.tar.gz"
104
+ return self._fetch(
105
+ f"{self.web_url}/{self.repo}/archive/refs/tags/{tag}.tar.gz",
106
+ destination / f"{tag}.tar.gz",
107
+ )
108
+
109
+ def resolve(self, ref: str) -> str:
110
+ """Return the 40-character commit SHA that a branch, tag or SHA names.
111
+
112
+ Raises:
113
+ AppException: The request failed, the ref does not exist, or the
114
+ response carries no valid SHA.
115
+ """
116
+ url = f"{self.api_url}/repos/{self.repo}/commits/{urllib.parse.quote(ref, safe='')}"
117
+ try:
118
+ with urllib.request.urlopen(url, timeout=_TIMEOUT) as response: # noqa: S310 # URL built from the configured GitHub host
119
+ sha = str(json.load(response).get("sha") or "")
120
+ except (urllib.error.URLError, ValueError, AttributeError) as error:
121
+ raise AppException(
122
+ "Cannot resolve ref {!r} of {}: {}", ref, self.repo, error
123
+ ) from error
124
+ if not _SHA.fullmatch(sha):
125
+ raise AppException(
126
+ "Cannot resolve ref {!r} of {}: malformed sha {!r}",
127
+ ref,
128
+ self.repo,
129
+ sha,
130
+ )
131
+ return sha
132
+
133
+ def download_commit(self, sha: str, destination: Path) -> Path:
134
+ """Download the source tarball of commit *sha* into *destination*.
135
+
136
+ Raises:
137
+ AppException: The download failed.
138
+ """
139
+ return self._fetch(
140
+ f"{self.web_url}/{self.repo}/archive/{sha}.tar.gz",
141
+ destination / f"{sha}.tar.gz",
142
+ )
143
+
144
+ def _fetch(self, url: str, archive: Path) -> Path:
102
145
  try:
103
146
  with (
104
147
  urllib.request.urlopen(url, timeout=_TIMEOUT) as response, # noqa: S310 # URL built from the configured GitHub host