rn-forge-tooling 0.3.2__tar.gz → 0.4.0__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.2
3
+ Version: 0.4.0
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.10
17
- Requires-Dist: rn-forge-cli>=0.1.1,<0.2
18
- Requires-Dist: assertpy>=2.35 ; 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.36.0 ; 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.2"
3
+ version = "0.4.0"
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.10",
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>=2.35",
29
+ "assertpy>=2.36.0",
30
30
  "pytest>=9.1.1",
31
31
  ]
32
32
 
@@ -66,17 +66,17 @@ markers = ["scaffold: installs built wheels into a scaffolded application (slow)
66
66
 
67
67
  [dependency-groups]
68
68
  dev = [
69
- "assertpy>=2.35",
69
+ "assertpy>=2.36.0",
70
70
  "pyright>=1.1.411",
71
- "pytest>=9.1.1",
71
+ "pytest>=9.2.0",
72
72
  "pytest-cov>=7.1.0",
73
73
  "pytest-randomly>=4.1.0",
74
74
  "rn-forge-tooling",
75
- "ruff>=0.15.21",
75
+ "ruff>=0.17.4",
76
76
  ]
77
77
  docs = [
78
78
  "mkdocs>=1.6.1",
79
- "mkdocs-material>=9.7.6",
80
- "mkdocstrings[python]>=1.0.6",
79
+ "mkdocs-material>=9.8.1",
80
+ "mkdocstrings[python]>=1.0.8",
81
81
  "rn-forge-tooling",
82
82
  ]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-tooling"
3
- version = "0.3.2"
3
+ version = "0.4.0"
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" }]
@@ -17,10 +17,10 @@ classifiers = [
17
17
  ]
18
18
  requires-python = ">=3.14"
19
19
  # Internal requirements are version ranges (ADR-0004).
20
- dependencies = ["rn-forge-commons>=0.8.0,<0.10", "rn-forge-cli>=0.1.1,<0.2"]
20
+ dependencies = ["rn-forge-commons>=0.8.0,<0.11", "rn-forge-cli>=0.1.1,<0.3"]
21
21
 
22
22
  [project.optional-dependencies]
23
- testing = ["assertpy>=2.35", "pytest>=9.1.1"]
23
+ testing = ["assertpy>=2.36.0", "pytest>=9.1.1"]
24
24
 
25
25
  [project.urls]
26
26
  Documentation = "https://rn-forge.github.io/pykit/packages/rn-forge-tooling/latest/"
@@ -56,17 +56,17 @@ markers = [
56
56
 
57
57
  [dependency-groups]
58
58
  dev = [
59
- "assertpy>=2.35",
59
+ "assertpy>=2.36.0",
60
60
  "pyright>=1.1.411",
61
- "pytest>=9.1.1",
61
+ "pytest>=9.2.0",
62
62
  "pytest-cov>=7.1.0",
63
63
  "pytest-randomly>=4.1.0",
64
64
  "rn-forge-tooling",
65
- "ruff>=0.15.21",
65
+ "ruff>=0.17.4",
66
66
  ]
67
67
  docs = [
68
68
  "mkdocs>=1.6.1",
69
- "mkdocs-material>=9.7.6",
70
- "mkdocstrings[python]>=1.0.6",
69
+ "mkdocs-material>=9.8.1",
70
+ "mkdocstrings[python]>=1.0.8",
71
71
  "rn-forge-tooling",
72
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
@@ -15,44 +15,16 @@ from rn_forge.commons.lang.dataclasses import DataclassMixin
15
15
  from rn_forge.commons.lang.utils import AppUtils
16
16
  from rn_forge.commons.runtime.console import OutputMode, console
17
17
  from rn_forge.tooling.install import lifecycle
18
+ from rn_forge.tooling.install.home import ToolHome
18
19
  from rn_forge.tooling.install.product import ToolProduct
19
20
  from rn_forge.tooling.install.release import LocalArchive
20
21
 
21
22
  __all__ = ["VERBS", "LifecycleSurface", "build_tool_app", "lifecycle_commands"]
22
23
 
23
- VERBS = ("install", "upgrade", "uninstall", "cleanup", "status", "doctor")
24
- """Every verb this module can mount, in ``--help`` order."""
25
-
26
24
  LIFECYCLE_KEY = "lifecycle"
27
25
  """The table :meth:`LifecycleSurface.load` reads by default."""
28
26
 
29
27
 
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
28
  @dataclass(frozen=True, slots=True)
57
29
  class LifecycleSurface(DataclassMixin):
58
30
  """A declared ``[lifecycle]`` table: which verbs a tool exposes, and where.
@@ -66,7 +38,7 @@ class LifecycleSurface(DataclassMixin):
66
38
  """
67
39
 
68
40
  product: str
69
- verbs: tuple[str, ...] = VERBS
41
+ verbs: tuple[str, ...] = field(default_factory=lambda: VERBS)
70
42
  namespace: str | None = None
71
43
 
72
44
  def __post_init__(self) -> None:
@@ -106,9 +78,18 @@ class LifecycleSurface(DataclassMixin):
106
78
  dict(source) if isinstance(source, Mapping) else DocumentUtils.read(source)
107
79
  )
108
80
  if key in data:
109
- data = data[key]
81
+ table = data[key]
82
+ if not isinstance(table, Mapping):
83
+ raise AppException("[{}] must be a table", key)
84
+ data = dict(cast(Mapping[str, Any], table))
110
85
  elif "product" not in data:
111
86
  raise AppException("No [{}] table to build lifecycle verbs from", key)
87
+ if "verbs" in data:
88
+ verbs = data["verbs"]
89
+ if not isinstance(verbs, list) or not all(
90
+ isinstance(verb, str) for verb in cast(list[object], verbs)
91
+ ):
92
+ raise AppException("Lifecycle verbs must be a list of strings")
112
93
  return cls.from_dict(dict(data))
113
94
 
114
95
 
@@ -195,6 +176,20 @@ def _emit(record: DataclassMixin, text: str) -> None:
195
176
  console.success("{}", text)
196
177
 
197
178
 
179
+ def _emit_install(result: lifecycle.InstallResult, product: ToolProduct) -> None:
180
+ """Emit an install's result, then any ``env.sh`` warning and the source hint."""
181
+ _emit(result, _install_text(result))
182
+ if console.mode is OutputMode.JSON:
183
+ return
184
+ if result.env == "foreign":
185
+ console.warning(
186
+ "{} has no rn-forge schema line; left it alone",
187
+ ToolHome(product.name).env_path,
188
+ )
189
+ if result.hint:
190
+ console.info("{}", result.hint)
191
+
192
+
198
193
  def _add_install(app: typer.Typer, product: ToolProduct) -> None:
199
194
  @app.command("install")
200
195
  def install(
@@ -209,23 +204,36 @@ def _add_install(app: typer.Typer, product: ToolProduct) -> None:
209
204
  force: Annotated[
210
205
  bool, typer.Option("--force", help="Reinstall the active version.")
211
206
  ] = False,
207
+ ref: Annotated[
208
+ str | None,
209
+ typer.Option(
210
+ "--ref",
211
+ help="Install a branch, tag or commit of the product's GitHub repository.",
212
+ ),
213
+ ] = None,
212
214
  ) -> None:
213
215
  """Install a release and make it the active version."""
216
+ if ref is not None and (version is not None or archive is not None):
217
+ raise typer.BadParameter(
218
+ "--ref cannot be combined with --version or --archive"
219
+ )
214
220
  source = None
215
221
  if archive is not None:
216
222
  if version is None:
217
223
  raise typer.BadParameter("--archive needs --version")
218
224
  source = LocalArchive(archive, version)
219
- result = lifecycle.install(product, version=version, source=source, force=force)
220
- _emit(result, _install_text(result))
225
+ result = lifecycle.install(
226
+ product, version=version, source=source, force=force, ref=ref
227
+ )
228
+ _emit_install(result, product)
221
229
 
222
230
 
223
231
  def _add_upgrade(app: typer.Typer, product: ToolProduct) -> None:
224
232
  @app.command("upgrade")
225
233
  def upgrade() -> None:
226
- """Install the latest release over the current install."""
234
+ """Install the latest release, or the recorded ref's current commit, over the current install."""
227
235
  result = lifecycle.upgrade(product)
228
- _emit(result, _install_text(result))
236
+ _emit_install(result, product)
229
237
 
230
238
 
231
239
  def _add_uninstall(app: typer.Typer, product: ToolProduct) -> None:
@@ -269,10 +277,16 @@ def _add_status(app: typer.Typer, product: ToolProduct) -> None:
269
277
  def status() -> None:
270
278
  """Show the running version and what is installed."""
271
279
  result = lifecycle.status(product)
280
+ installed = result.installed or "none"
281
+ if result.commit is not None:
282
+ installed = (
283
+ f"{result.package_version or installed} "
284
+ f"({result.ref} @ {result.commit[:12]})"
285
+ )
272
286
  _emit(
273
287
  result,
274
288
  f"{result.product} {result.version} — installed: "
275
- f"{result.installed or 'none'} ({result.home})",
289
+ f"{installed} ({result.home})",
276
290
  )
277
291
 
278
292
 
@@ -308,3 +322,33 @@ _COMMANDS = {
308
322
  "status": _add_status,
309
323
  "doctor": _add_doctor,
310
324
  }
325
+ """Command adders in ``--help`` order."""
326
+
327
+ VERBS = tuple(_COMMANDS)
328
+ """Every verb this module can mount, in ``--help`` order."""
329
+
330
+
331
+ def lifecycle_commands(
332
+ product: ToolProduct, verbs: Sequence[str] = VERBS
333
+ ) -> typer.Typer:
334
+ """Return a Typer app holding *verbs* as commands over *product*.
335
+
336
+ Args:
337
+ product: The product the commands act on.
338
+ verbs: Which of :data:`VERBS` to include.
339
+
340
+ Raises:
341
+ AppException: *product* is not a :class:`ToolProduct`, or a verb is
342
+ not one of :data:`VERBS`.
343
+ """
344
+ if not isinstance(product, ToolProduct): # pyright: ignore[reportUnnecessaryIsInstance] - named by a config string
345
+ raise AppException("{!r} is not a ToolProduct", product)
346
+ unknown = sorted(set(verbs) - set(VERBS))
347
+ if unknown:
348
+ raise AppException("Unknown lifecycle verb(s): {}", ", ".join(unknown))
349
+
350
+ app = typer.Typer()
351
+ for verb, add_command in _COMMANDS.items():
352
+ if verb in verbs:
353
+ add_command(app, product)
354
+ return app
@@ -1,7 +1,14 @@
1
1
  """Release sources, workstation installation, and lifecycle operations."""
2
2
 
3
3
  from rn_forge.tooling.install.archive import extract_archive
4
- from rn_forge.tooling.install.home import ToolHome, rnf_home
4
+ from rn_forge.tooling.install.home import (
5
+ EnvWrite,
6
+ ToolHome,
7
+ env_hint,
8
+ env_schema,
9
+ rnf_home,
10
+ write_env,
11
+ )
5
12
  from rn_forge.tooling.install.lifecycle import (
6
13
  CleanupResult,
7
14
  InstallResult,
@@ -14,6 +21,7 @@ from rn_forge.tooling.install.lifecycle import (
14
21
  upgrade,
15
22
  )
16
23
  from rn_forge.tooling.install.product import Check, Link, ToolProduct
24
+ from rn_forge.tooling.install.python import PythonTool
17
25
  from rn_forge.tooling.install.release import (
18
26
  GitHubReleases,
19
27
  LocalArchive,
@@ -24,16 +32,20 @@ from rn_forge.tooling.install.release import (
24
32
  __all__ = [
25
33
  "Check",
26
34
  "CleanupResult",
35
+ "EnvWrite",
27
36
  "GitHubReleases",
28
37
  "InstallResult",
29
38
  "InstallStatus",
30
39
  "Link",
31
40
  "LocalArchive",
41
+ "PythonTool",
32
42
  "ReleaseSource",
33
43
  "ToolHome",
34
44
  "ToolProduct",
35
45
  "cleanup",
36
46
  "doctor",
47
+ "env_hint",
48
+ "env_schema",
37
49
  "extract_archive",
38
50
  "fetch_release",
39
51
  "install",
@@ -41,4 +53,5 @@ __all__ = [
41
53
  "status",
42
54
  "uninstall",
43
55
  "upgrade",
56
+ "write_env",
44
57
  ]
@@ -4,12 +4,26 @@ from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import re
7
+ from enum import StrEnum
7
8
  from pathlib import Path
8
9
 
9
10
  from rn_forge.commons.exceptions import AppException
10
11
  from rn_forge.commons.fs.locks import DirectoryLock, atomic_symlink
11
-
12
- __all__ = ["DEFAULT_RNF_HOME", "RNF_HOME_ENV", "ToolHome", "rnf_home"]
12
+ from rn_forge.commons.fs.paths import PathUtils
13
+
14
+ __all__ = [
15
+ "DEFAULT_RNF_HOME",
16
+ "ENV_SCHEMA",
17
+ "ENV_TEMPLATE",
18
+ "RNF_HOME_ENV",
19
+ "EnvWrite",
20
+ "ToolHome",
21
+ "env_hint",
22
+ "env_schema",
23
+ "render_env",
24
+ "rnf_home",
25
+ "write_env",
26
+ ]
13
27
 
14
28
  RNF_HOME_ENV = "RNF_HOME"
15
29
  """The environment variable that relocates every installed tool."""
@@ -17,6 +31,25 @@ RNF_HOME_ENV = "RNF_HOME"
17
31
  DEFAULT_RNF_HOME = "~/.rn-forge"
18
32
  """The home used when :data:`RNF_HOME_ENV` is unset or empty."""
19
33
 
34
+ ENV_SCHEMA = 1
35
+ """The schema number of the ``env.sh`` this package writes."""
36
+
37
+ ENV_TEMPLATE = """\
38
+ # rn-forge home environment, schema 1. Written by rn-forge installers; do not edit.
39
+ # Source it from your shell's rc file, before compinit: source "<home>/env.sh"
40
+ export RNF_HOME="<home>"
41
+ case ":${PATH}:" in
42
+ *":${RNF_HOME}/bin:"*) ;;
43
+ *) export PATH="${RNF_HOME}/bin:${PATH}" ;;
44
+ esac
45
+ if [ -n "${ZSH_VERSION:-}" ]; then
46
+ fpath=("${RNF_HOME}/completions" "${fpath[@]}")
47
+ fi
48
+ """
49
+ """The ``env.sh`` text, with ``<home>`` standing for the home's absolute path."""
50
+
51
+ _SCHEMA_LINE = re.compile(r"^# rn-forge home environment, schema (\d+)\.")
52
+
20
53
  _SEGMENT = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$")
21
54
  """A product name or version: one path segment that cannot climb out of its parent."""
22
55
 
@@ -26,6 +59,75 @@ def rnf_home() -> Path:
26
59
  return Path(os.environ.get(RNF_HOME_ENV) or DEFAULT_RNF_HOME).expanduser()
27
60
 
28
61
 
62
+ class EnvWrite(StrEnum):
63
+ """What :func:`write_env` did."""
64
+
65
+ WRITTEN = "written"
66
+ """The file was missing or older, and was written."""
67
+
68
+ CURRENT = "current"
69
+ """The file has the same or a newer schema, and was left alone."""
70
+
71
+ FOREIGN = "foreign"
72
+ """The file has no schema line, so it is not ours, and was left alone."""
73
+
74
+
75
+ def render_env(root: Path) -> str:
76
+ """Return :data:`ENV_TEMPLATE` for the home at *root*, as an absolute path."""
77
+ return ENV_TEMPLATE.replace("<home>", str(Path(root).expanduser().absolute()))
78
+
79
+
80
+ def env_schema(root: Path) -> int | None:
81
+ """Return the schema number on the first line of ``<root>/env.sh``.
82
+
83
+ Returns:
84
+ The number, or ``None`` when the file is missing or empty, or its first
85
+ line is not the schema line, so the file is not ours.
86
+ """
87
+ path = Path(root) / "env.sh"
88
+ if not path.is_file():
89
+ return None
90
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
91
+ found = _SCHEMA_LINE.match(lines[0]) if lines else None
92
+ return int(found.group(1)) if found else None
93
+
94
+
95
+ def write_env(root: Path) -> EnvWrite:
96
+ """Write ``<root>/env.sh`` when it is missing or names a lower schema.
97
+
98
+ Args:
99
+ root: The home directory; created when absent.
100
+
101
+ Returns:
102
+ Which case applied. A file with the same or a higher schema, or with no
103
+ schema line, is left unchanged.
104
+ """
105
+ path = Path(root) / "env.sh"
106
+ if path.is_file():
107
+ recorded = env_schema(root)
108
+ if recorded is None:
109
+ return EnvWrite.FOREIGN
110
+ if recorded >= ENV_SCHEMA:
111
+ return EnvWrite.CURRENT
112
+ path.parent.mkdir(parents=True, exist_ok=True)
113
+ PathUtils.atomic_write(render_env(root), path)
114
+ return EnvWrite.WRITTEN
115
+
116
+
117
+ def env_hint(root: Path) -> str | None:
118
+ """Return how to source ``env.sh``, or ``None`` when ``<root>/bin`` is on ``PATH``."""
119
+ bin_dir = os.path.abspath(Path(root) / "bin")
120
+ entries = os.environ.get("PATH", "").split(os.pathsep)
121
+ if any(os.path.abspath(entry) == bin_dir for entry in entries):
122
+ return None
123
+ home = Path(root).expanduser().absolute()
124
+ return (
125
+ f"{home}/bin is not on PATH. To use it in this shell, run:\n"
126
+ f' source "{home}/env.sh"\n'
127
+ "and add that line to your shell's rc file, before compinit."
128
+ )
129
+
130
+
29
131
  def _segment(value: str, what: str) -> str:
30
132
  """Return *value* unchanged, or raise if it is not a single safe path segment."""
31
133
  if not _SEGMENT.match(value):
@@ -68,6 +170,16 @@ class ToolHome:
68
170
  """The ``current`` symlink. May not exist."""
69
171
  return self.product_dir / "current"
70
172
 
173
+ @property
174
+ def env_path(self) -> Path:
175
+ """``<home>/env.sh``, owned by the home rather than the product."""
176
+ return self.root / "env.sh"
177
+
178
+ @property
179
+ def completions_dir(self) -> Path:
180
+ """``<home>/completions/``."""
181
+ return self.root / "completions"
182
+
71
183
  @property
72
184
  def state_path(self) -> Path:
73
185
  """``<home>/<product>/state.json``."""
@@ -75,7 +187,10 @@ class ToolHome:
75
187
 
76
188
  @property
77
189
  def work_dir(self) -> Path:
78
- """Scratch space for a transaction in flight; removed when it finishes."""
190
+ """Scratch space holding unique transaction directories.
191
+
192
+ A failed restoration retains its displaced version here; cleanup keeps it.
193
+ """
79
194
  return self.product_dir / ".work"
80
195
 
81
196
  def version_dir(self, version: str) -> Path: