rn-forge-tooling 0.3.3__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.3
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>
@@ -15,7 +15,7 @@ Classifier: Programming Language :: Python :: 3.14
15
15
  Classifier: Typing :: Typed
16
16
  Requires-Dist: rn-forge-commons>=0.8.0,<0.11
17
17
  Requires-Dist: rn-forge-cli>=0.1.1,<0.3
18
- Requires-Dist: assertpy>=2.35 ; extra == 'testing'
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/
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rn-forge-tooling"
3
- version = "0.3.3"
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"
@@ -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.3"
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" }]
@@ -20,7 +20,7 @@ requires-python = ">=3.14"
20
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
  ]
@@ -15,6 +15,7 @@ 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
 
@@ -175,6 +176,20 @@ def _emit(record: DataclassMixin, text: str) -> None:
175
176
  console.success("{}", text)
176
177
 
177
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
+
178
193
  def _add_install(app: typer.Typer, product: ToolProduct) -> None:
179
194
  @app.command("install")
180
195
  def install(
@@ -210,7 +225,7 @@ def _add_install(app: typer.Typer, product: ToolProduct) -> None:
210
225
  result = lifecycle.install(
211
226
  product, version=version, source=source, force=force, ref=ref
212
227
  )
213
- _emit(result, _install_text(result))
228
+ _emit_install(result, product)
214
229
 
215
230
 
216
231
  def _add_upgrade(app: typer.Typer, product: ToolProduct) -> None:
@@ -218,7 +233,7 @@ def _add_upgrade(app: typer.Typer, product: ToolProduct) -> None:
218
233
  def upgrade() -> None:
219
234
  """Install the latest release, or the recorded ref's current commit, over the current install."""
220
235
  result = lifecycle.upgrade(product)
221
- _emit(result, _install_text(result))
236
+ _emit_install(result, product)
222
237
 
223
238
 
224
239
  def _add_uninstall(app: typer.Typer, product: ToolProduct) -> None:
@@ -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,
@@ -25,6 +32,7 @@ from rn_forge.tooling.install.release import (
25
32
  __all__ = [
26
33
  "Check",
27
34
  "CleanupResult",
35
+ "EnvWrite",
28
36
  "GitHubReleases",
29
37
  "InstallResult",
30
38
  "InstallStatus",
@@ -36,6 +44,8 @@ __all__ = [
36
44
  "ToolProduct",
37
45
  "cleanup",
38
46
  "doctor",
47
+ "env_hint",
48
+ "env_schema",
39
49
  "extract_archive",
40
50
  "fetch_release",
41
51
  "install",
@@ -43,4 +53,5 @@ __all__ = [
43
53
  "status",
44
54
  "uninstall",
45
55
  "upgrade",
56
+ "write_env",
46
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``."""
@@ -19,7 +19,14 @@ from rn_forge.commons.fs.paths import PathUtils
19
19
  from rn_forge.commons.lang.dataclasses import DataclassMixin
20
20
  from rn_forge.commons.logging import AppLogger
21
21
  from rn_forge.tooling.install.archive import extract_archive
22
- from rn_forge.tooling.install.home import ToolHome
22
+ from rn_forge.tooling.install.home import (
23
+ ENV_SCHEMA,
24
+ EnvWrite,
25
+ ToolHome,
26
+ env_hint,
27
+ env_schema,
28
+ write_env,
29
+ )
23
30
  from rn_forge.tooling.install.product import Link, ToolProduct
24
31
  from rn_forge.tooling.install.release import (
25
32
  GitHubReleases,
@@ -52,12 +59,18 @@ class InstallResult(DataclassMixin):
52
59
  ``not-installed``.
53
60
  version: The version now active, when there is one.
54
61
  previous: The version that was active before, when there was one.
62
+ env: What the install did to ``env.sh`` (an :class:`EnvWrite` value),
63
+ or ``None`` when nothing was installed.
64
+ hint: How to source ``env.sh``, when ``bin/`` is not on ``PATH`` after
65
+ an install; ``None`` otherwise.
55
66
  """
56
67
 
57
68
  product: str
58
69
  outcome: str
59
70
  version: str | None = None
60
71
  previous: str | None = None
72
+ env: str | None = None
73
+ hint: str | None = None
61
74
 
62
75
 
63
76
  @dataclass(frozen=True, slots=True)
@@ -154,10 +167,23 @@ def install(
154
167
  with home.lock():
155
168
  previous = home.current_version()
156
169
  if previous == target and not force:
157
- return InstallResult(product.name, "already-current", target, previous)
158
- _install(product, home, source, target, previous, ref, sha)
170
+ return InstallResult(
171
+ product.name,
172
+ "already-current",
173
+ target,
174
+ previous,
175
+ hint=env_hint(home.root),
176
+ )
177
+ env = _install(product, home, source, target, previous, ref, sha)
159
178
  _LOGGER.verbose("install: {} {} active (was {})", product.name, target, previous)
160
- return InstallResult(product.name, "installed", target, previous)
179
+ return InstallResult(
180
+ product.name,
181
+ "installed",
182
+ target,
183
+ previous,
184
+ env=env.value,
185
+ hint=env_hint(home.root),
186
+ )
161
187
 
162
188
 
163
189
  def upgrade(
@@ -266,14 +292,16 @@ def doctor(product: ToolProduct, *, home: ToolHome | None = None) -> list[Findin
266
292
 
267
293
  A product that is not installed is a **warning**, not an error: the same
268
294
  command runs from a development checkout, where there is nothing under
269
- ``$RNF_HOME`` and nothing wrong. The product's checks run either way.
295
+ ``$RNF_HOME`` and nothing wrong. The ``home.*`` rows are warnings for the
296
+ same reason: a development checkout has no hooked-up home. Both they and
297
+ the product's checks run either way.
270
298
 
271
299
  Returns:
272
300
  Every finding, product checks last. Only an ``error`` should fail the
273
301
  command.
274
302
  """
275
303
  home = home or ToolHome(product.name)
276
- findings = _install_findings(product, home)
304
+ findings = _install_findings(product, home) + _home_findings(home)
277
305
  for check in product.checks():
278
306
  findings.extend(check(home))
279
307
  return findings
@@ -298,16 +326,18 @@ def _install(
298
326
  previous: str | None,
299
327
  ref: str | None,
300
328
  sha: str | None,
301
- ) -> None:
329
+ ) -> EnvWrite:
302
330
  """Prepare and activate a release or commit. The caller holds the lock."""
303
331
  prepared = _prepare(product, home, source, target, sha)
304
332
  undo: list[tuple[str, Callable[[], object]]] = []
305
333
  retained = False
306
334
  try:
307
- _activate(product, home, source, prepared, target, previous, ref, sha, undo)
335
+ return _activate(
336
+ product, home, source, prepared, target, previous, ref, sha, undo
337
+ )
308
338
  except BaseException as exc:
309
339
  failures = _recover(undo)
310
- retained = (prepared.work / "displaced").exists()
340
+ retained = prepared.work.joinpath("displaced").exists()
311
341
  _failure(product, target, exc, failures, prepared.work, retained)
312
342
  raise
313
343
  finally:
@@ -352,8 +382,12 @@ def _activate(
352
382
  ref: str | None,
353
383
  sha: str | None,
354
384
  undo: list[tuple[str, Callable[[], object]]],
355
- ) -> None:
356
- """Build and activate a release, appending recovery steps to *undo*."""
385
+ ) -> EnvWrite:
386
+ """Build and activate a release, appending recovery steps to *undo*.
387
+
388
+ Returns:
389
+ What was done to ``env.sh``.
390
+ """
357
391
  version_dir = home.version_dir(target)
358
392
  displaced = prepared.work / "displaced"
359
393
  if version_dir.exists():
@@ -374,6 +408,9 @@ def _activate(
374
408
  for link in product.artifacts():
375
409
  undo.append((f"restore link {link.path}", _place_link(home, link)))
376
410
 
411
+ undo.append(("restore env.sh", _restore_file(home.env_path)))
412
+ env = write_env(home.root)
413
+
377
414
  undo.append(("restore state.json", _restore_file(home.state_path)))
378
415
  if previous is not None and previous != target:
379
416
  product.migrate(previous, target)
@@ -393,6 +430,7 @@ def _activate(
393
430
 
394
431
  undo.append(("restore current", _restore_current(home)))
395
432
  home.activate(target)
433
+ return env
396
434
 
397
435
 
398
436
  def _text(recorded: dict[str, Any], key: str) -> str | None:
@@ -551,6 +589,44 @@ def _restore_current(home: ToolHome) -> Callable[[], None]:
551
589
  # -- doctor -------------------------------------------------------------------
552
590
 
553
591
 
592
+ def _home_findings(home: ToolHome) -> list[Finding]:
593
+ """What is true of the shell's hookup to the home: ``env.sh`` and ``PATH``."""
594
+ findings: list[Finding] = []
595
+ if not home.env_path.is_file():
596
+ findings.append(
597
+ Finding(
598
+ "home.env-missing",
599
+ Severity.WARNING,
600
+ f"{home.env_path} does not exist; any install writes it",
601
+ path=str(home.env_path),
602
+ )
603
+ )
604
+ else:
605
+ recorded = env_schema(home.root)
606
+ if recorded is not None and recorded < ENV_SCHEMA:
607
+ findings.append(
608
+ Finding(
609
+ "home.env-stale",
610
+ Severity.WARNING,
611
+ f"{home.env_path} is at schema {recorded}, this version "
612
+ f"writes {ENV_SCHEMA}; any install rewrites it",
613
+ path=str(home.env_path),
614
+ details={"recorded": recorded, "expected": ENV_SCHEMA},
615
+ )
616
+ )
617
+ hint = env_hint(home.root)
618
+ if hint is not None:
619
+ findings.append(
620
+ Finding(
621
+ "home.not-on-path",
622
+ Severity.WARNING,
623
+ hint,
624
+ path=str(home.root / "bin"),
625
+ )
626
+ )
627
+ return findings
628
+
629
+
554
630
  def _install_findings(product: ToolProduct, home: ToolHome) -> list[Finding]:
555
631
  """What is true of the install itself, before any product check."""
556
632
  current = home.current_version()
@@ -0,0 +1,110 @@
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 re
7
+ import shutil
8
+ from collections.abc import Sequence
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from rn_forge.commons.exceptions import AppException
13
+ from rn_forge.commons.fs.paths import PathUtils
14
+ from rn_forge.commons.runtime.subprocess import Process
15
+ from rn_forge.tooling.install.product import Link, ToolProduct
16
+
17
+ __all__ = ["PythonTool"]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class PythonTool(ToolProduct):
22
+ """A Python tool installed with ``uv tool install``.
23
+
24
+ The package must declare a console script named :attr:`name`, and that
25
+ script must be a Typer (or Click) command: the build asks it for its zsh
26
+ completion script. ``uv`` must be on ``PATH``; it is a program, not a
27
+ dependency.
28
+ """
29
+
30
+ def artifacts(self) -> Sequence[Link]:
31
+ """The links ``bin/<name>`` to the console script and ``completions/_<name>``."""
32
+ return (
33
+ Link(f"bin/{self.name}", f"bin/{self.name}"),
34
+ Link(f"completions/_{self.name}", f"completions/_{self.name}"),
35
+ )
36
+
37
+ def preflight(self) -> None:
38
+ """Refuse the install when ``uv`` is not on ``PATH``.
39
+
40
+ Raises:
41
+ AppException: ``uv`` was not found.
42
+ """
43
+ if shutil.which("uv") is None:
44
+ raise AppException(
45
+ "{} needs uv on PATH to install; install uv first", self.name
46
+ )
47
+
48
+ def build(self, release_root: Path, version_dir: Path) -> None:
49
+ """Install the package at *release_root* into *version_dir*.
50
+
51
+ The console script ends up at ``<version_dir>/bin/<name>`` and its zsh
52
+ completion script at ``<version_dir>/completions/_<name>``.
53
+
54
+ Raises:
55
+ AppException: ``uv tool install`` failed, or the command did not
56
+ answer the completion variable with a zsh completion script.
57
+ """
58
+ # uv creates version_dir itself; the environment is built in place
59
+ # because its scripts hold absolute paths.
60
+ env = {
61
+ **os.environ,
62
+ "UV_TOOL_DIR": str(version_dir / "tool"),
63
+ "UV_TOOL_BIN_DIR": str(version_dir / "bin"),
64
+ }
65
+ Process.execute(
66
+ "uv tool install", "uv", "tool", "install", str(release_root), env=env
67
+ )
68
+ self._write_completion(version_dir)
69
+
70
+ def _write_completion(self, version_dir: Path) -> None:
71
+ """Write the command's zsh completion script under *version_dir*.
72
+
73
+ Raises:
74
+ AppException: The command failed, or its output is not a zsh
75
+ completion script that registers a function with ``compdef``.
76
+ """
77
+ var = f"_{self.name.upper().replace('-', '_')}_COMPLETE"
78
+ result = Process.execute(
79
+ "completion script",
80
+ str(version_dir / "bin" / self.name),
81
+ env={**os.environ, var: "source_zsh"},
82
+ )
83
+ # compinit reads only a file's first line for #compdef, and Typer's
84
+ # output starts with a blank line.
85
+ script = (result.stdout or "").lstrip("\n")
86
+ lines = script.splitlines()
87
+ if not lines or lines[0] != f"#compdef {self.name}":
88
+ raise AppException(
89
+ "{} did not print a zsh completion script for {}; "
90
+ "it must be a Typer or Click command",
91
+ self.name,
92
+ var,
93
+ )
94
+ match = re.search(
95
+ rf"^compdef (\S+) {re.escape(self.name)}$", script, re.MULTILINE
96
+ )
97
+ if match is None:
98
+ raise AppException(
99
+ "{} printed a zsh completion script for {} without a compdef line",
100
+ self.name,
101
+ var,
102
+ )
103
+ # Autoloaded, the script only defines the function and registers it, so
104
+ # the first <TAB> completes nothing unless the function runs once.
105
+ directory = version_dir / "completions"
106
+ directory.mkdir(parents=True, exist_ok=True)
107
+ PathUtils.atomic_write(
108
+ script.rstrip("\n") + f'\n{match.group(1)} "$@"\n',
109
+ directory / f"_{self.name}",
110
+ )
@@ -1,58 +0,0 @@
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
- )