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,435 @@
1
+ """Transactional install, upgrade, removal, status, and diagnostic operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ from rn_forge.commons.exceptions import AppException
13
+ from rn_forge.commons.findings import Finding, Severity
14
+ from rn_forge.commons.fs.locks import atomic_symlink
15
+ from rn_forge.commons.fs.paths import PathUtils
16
+ from rn_forge.commons.lang.dataclasses import DataclassMixin
17
+ from rn_forge.commons.logging import AppLogger
18
+ from rn_forge.tooling.install.home import ToolHome
19
+ from rn_forge.tooling.install.product import Link, ToolProduct
20
+ from rn_forge.tooling.install.release import ReleaseSource, fetch_release
21
+
22
+ __all__ = [
23
+ "CleanupResult",
24
+ "InstallResult",
25
+ "InstallStatus",
26
+ "cleanup",
27
+ "doctor",
28
+ "install",
29
+ "status",
30
+ "uninstall",
31
+ "upgrade",
32
+ ]
33
+
34
+ _LOGGER = AppLogger.get_logger(__name__)
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class InstallResult(DataclassMixin):
39
+ """What ``install``, ``upgrade`` or ``uninstall`` did.
40
+
41
+ Args:
42
+ product: The product name.
43
+ outcome: ``installed``, ``already-current``, ``removed`` or
44
+ ``not-installed``.
45
+ version: The version now active, when there is one.
46
+ previous: The version that was active before, when there was one.
47
+ """
48
+
49
+ product: str
50
+ outcome: str
51
+ version: str | None = None
52
+ previous: str | None = None
53
+
54
+
55
+ @dataclass(frozen=True, slots=True)
56
+ class CleanupResult(DataclassMixin):
57
+ """What ``cleanup`` removed, or would remove.
58
+
59
+ Args:
60
+ product: The product name.
61
+ kept: The active version.
62
+ removed: The versions removed — or, on a dry run, to be removed.
63
+ dry_run: Whether anything was actually removed.
64
+ """
65
+
66
+ product: str
67
+ kept: str
68
+ removed: list[str] = field(default_factory=list[str])
69
+ dry_run: bool = False
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class InstallStatus(DataclassMixin):
74
+ """Where a product is installed, and at what version.
75
+
76
+ Args:
77
+ product: The product name.
78
+ version: The version of the running code.
79
+ home: The product's directory.
80
+ installed: The version ``current`` points at, or ``None``.
81
+ versions: Every version directory present.
82
+ """
83
+
84
+ product: str
85
+ version: str
86
+ home: str
87
+ installed: str | None = None
88
+ versions: list[str] = field(default_factory=list[str])
89
+
90
+
91
+ def install(
92
+ product: ToolProduct,
93
+ *,
94
+ version: str | None = None,
95
+ source: ReleaseSource | None = None,
96
+ home: ToolHome | None = None,
97
+ force: bool = False,
98
+ ) -> InstallResult:
99
+ """Install *version* of *product* and make it the active one.
100
+
101
+ Args:
102
+ product: The product to install.
103
+ version: The version to install. Defaults to the source's latest.
104
+ source: Where to fetch from. Defaults to ``product.source``.
105
+ home: The home to install into. Defaults to the product's.
106
+ force: Reinstall even when *version* is already active.
107
+
108
+ Raises:
109
+ AppException: Any step failed; everything it did has been undone.
110
+ BaseException: An interruption, re-raised once everything is undone.
111
+ """
112
+ home = home or ToolHome(product.name)
113
+ source = source or product.source
114
+ target = version or source.latest()
115
+ home.version_dir(target) # validates the version before anything is written
116
+ with home.lock():
117
+ previous = home.current_version()
118
+ if previous == target and not force:
119
+ return InstallResult(product.name, "already-current", target, previous)
120
+ _install(product, home, source, target, previous)
121
+ _LOGGER.verbose("install: {} {} active (was {})", product.name, target, previous)
122
+ return InstallResult(product.name, "installed", target, previous)
123
+
124
+
125
+ def upgrade(
126
+ product: ToolProduct,
127
+ *,
128
+ source: ReleaseSource | None = None,
129
+ home: ToolHome | None = None,
130
+ ) -> InstallResult:
131
+ """Install the latest version over an existing install.
132
+
133
+ Raises:
134
+ AppException: The product is not installed, or the install failed.
135
+ """
136
+ home = home or ToolHome(product.name)
137
+ if home.current_version() is None:
138
+ raise AppException(
139
+ "{} is not installed under {}; install it first",
140
+ product.name,
141
+ home.product_dir,
142
+ )
143
+ return install(product, source=source, home=home)
144
+
145
+
146
+ def uninstall(product: ToolProduct, *, home: ToolHome | None = None) -> InstallResult:
147
+ """Remove the product's links and its whole directory under the home.
148
+
149
+ Works over an install that never completed: nothing here assumes
150
+ ``current`` or ``state.json`` exists. A link is removed only when it still
151
+ points where this product put it — a path someone has since replaced with
152
+ their own file or link is left alone.
153
+ """
154
+ home = home or ToolHome(product.name)
155
+ if not home.product_dir.exists():
156
+ return InstallResult(product.name, "not-installed")
157
+ previous = home.current_version()
158
+ with home.lock():
159
+ for link in product.artifacts():
160
+ path = home.root / link.path
161
+ if path.is_symlink() and os.readlink(path) == _link_target(home, link):
162
+ path.unlink()
163
+ # The lock directory lives inside; releasing it afterwards tolerates
164
+ # its absence.
165
+ shutil.rmtree(home.product_dir)
166
+ return InstallResult(product.name, "removed", previous=previous)
167
+
168
+
169
+ def cleanup(
170
+ product: ToolProduct, *, home: ToolHome | None = None, dry_run: bool = False
171
+ ) -> CleanupResult:
172
+ """Remove every installed version except the active one, and leftover scratch space.
173
+
174
+ Raises:
175
+ AppException: There is no active version to keep.
176
+ """
177
+ home = home or ToolHome(product.name)
178
+ current = home.current_version()
179
+ if current is None:
180
+ raise AppException("{} has no active version to keep", product.name)
181
+ if dry_run:
182
+ stale = [v for v in home.installed_versions() if v != current]
183
+ return CleanupResult(product.name, current, stale, dry_run=True)
184
+ with home.lock():
185
+ current = home.current_version() or current
186
+ stale = [v for v in home.installed_versions() if v != current]
187
+ for stale_version in stale:
188
+ shutil.rmtree(home.version_dir(stale_version))
189
+ shutil.rmtree(home.work_dir, ignore_errors=True)
190
+ return CleanupResult(product.name, current, stale)
191
+
192
+
193
+ def status(product: ToolProduct, *, home: ToolHome | None = None) -> InstallStatus:
194
+ """Report the running version and what is installed. Writes nothing."""
195
+ home = home or ToolHome(product.name)
196
+ return InstallStatus(
197
+ product=product.name,
198
+ version=product.version,
199
+ home=str(home.product_dir),
200
+ installed=home.current_version(),
201
+ versions=home.installed_versions(),
202
+ )
203
+
204
+
205
+ def doctor(product: ToolProduct, *, home: ToolHome | None = None) -> list[Finding]:
206
+ """Inspect the install, then run the product's own checks.
207
+
208
+ A product that is not installed is a **warning**, not an error: the same
209
+ command runs from a development checkout, where there is nothing under
210
+ ``$RNF_HOME`` and nothing wrong. The product's checks run either way.
211
+
212
+ Returns:
213
+ Every finding, product checks last. Only an ``error`` should fail the
214
+ command.
215
+ """
216
+ home = home or ToolHome(product.name)
217
+ findings = _install_findings(product, home)
218
+ for check in product.checks():
219
+ findings.extend(check(home))
220
+ return findings
221
+
222
+
223
+ # -- install transaction ----------------------------------------------------
224
+
225
+
226
+ def _install(
227
+ product: ToolProduct,
228
+ home: ToolHome,
229
+ source: ReleaseSource,
230
+ target: str,
231
+ previous: str | None,
232
+ ) -> 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"
239
+ try:
240
+ release_root = fetch_release(source, target, work / "release")
241
+
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
+
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,
264
+ )
265
+
266
+ undo.append(_restore_current(home))
267
+ home.activate(target)
268
+ except BaseException as exc:
269
+ for step in reversed(undo):
270
+ step()
271
+ if isinstance(exc, Exception):
272
+ raise AppException(
273
+ "Install of {} {} failed and was rolled back: {}",
274
+ product.name,
275
+ target,
276
+ exc,
277
+ ) from exc
278
+ raise
279
+ finally:
280
+ shutil.rmtree(work, ignore_errors=True)
281
+
282
+
283
+ def _link_target(home: ToolHome, link: Link) -> str:
284
+ """What *link*'s symlink contains: a relative path through ``current``."""
285
+ path = home.root / link.path
286
+ return os.path.relpath(home.current / link.target, path.parent)
287
+
288
+
289
+ def _place_link(home: ToolHome, link: Link) -> Callable[[], None]:
290
+ """Put *link* in place and return how to undo it.
291
+
292
+ Raises:
293
+ AppException: Something other than a symlink is already at the path —
294
+ a file a person put there is not ours to replace.
295
+ """
296
+ path = home.root / link.path
297
+ path.parent.mkdir(parents=True, exist_ok=True)
298
+ PathUtils.assert_within(home.root, path.parent)
299
+ if path.exists() and not path.is_symlink():
300
+ raise AppException("{} exists and is not a link; not replacing it", path)
301
+ before = os.readlink(path) if path.is_symlink() else None
302
+ atomic_symlink(path, _link_target(home, link))
303
+
304
+ def restore() -> None:
305
+ if before is None:
306
+ path.unlink(missing_ok=True)
307
+ else:
308
+ atomic_symlink(path, before)
309
+
310
+ return restore
311
+
312
+
313
+ def _restore_file(path: Path) -> Callable[[], None]:
314
+ """Snapshot *path*'s bytes now and return how to put them back."""
315
+ before = path.read_bytes() if path.is_file() else None
316
+
317
+ def restore() -> None:
318
+ if before is None:
319
+ path.unlink(missing_ok=True)
320
+ else:
321
+ PathUtils.atomic_write(before, path)
322
+
323
+ return restore
324
+
325
+
326
+ def _restore_current(home: ToolHome) -> Callable[[], None]:
327
+ """Snapshot where ``current`` points now and return how to point it back."""
328
+ before = os.readlink(home.current) if home.current.is_symlink() else None
329
+
330
+ def restore() -> None:
331
+ if before is None:
332
+ home.current.unlink(missing_ok=True)
333
+ else:
334
+ atomic_symlink(home.current, before)
335
+
336
+ return restore
337
+
338
+
339
+ # -- doctor -------------------------------------------------------------------
340
+
341
+
342
+ def _install_findings(product: ToolProduct, home: ToolHome) -> list[Finding]:
343
+ """What is true of the install itself, before any product check."""
344
+ current = home.current_version()
345
+ if current is None:
346
+ return [
347
+ Finding(
348
+ "install.not-installed",
349
+ Severity.WARNING,
350
+ f"{product.name} is not installed under {home.product_dir}",
351
+ path=str(home.product_dir),
352
+ )
353
+ ]
354
+
355
+ findings: list[Finding] = []
356
+ if not home.current.resolve().is_dir():
357
+ findings.append(
358
+ Finding(
359
+ "install.current-broken",
360
+ Severity.ERROR,
361
+ f"current points at {current}, which is not installed",
362
+ path=str(home.current),
363
+ )
364
+ )
365
+ if current != product.version:
366
+ findings.append(
367
+ Finding(
368
+ "install.version-mismatch",
369
+ Severity.WARNING,
370
+ f"running {product.version}, but {current} is installed",
371
+ details={"running": product.version, "installed": current},
372
+ )
373
+ )
374
+ findings.extend(_state_findings(product, home))
375
+ for link in product.artifacts():
376
+ path = home.root / link.path
377
+ if not path.is_symlink() or os.readlink(path) != _link_target(home, link):
378
+ findings.append(
379
+ Finding(
380
+ "install.link-missing",
381
+ Severity.ERROR,
382
+ f"{link.path} does not link to {link.target}",
383
+ path=str(path),
384
+ )
385
+ )
386
+ elif not path.exists():
387
+ findings.append(
388
+ Finding(
389
+ "install.link-broken",
390
+ Severity.ERROR,
391
+ f"{link.path} links to {link.target}, which does not exist",
392
+ path=str(path),
393
+ )
394
+ )
395
+ if not findings:
396
+ findings.append(
397
+ Finding(
398
+ "install.ok",
399
+ Severity.INFO,
400
+ f"{product.name} {current} is installed",
401
+ path=str(home.product_dir),
402
+ )
403
+ )
404
+ return findings
405
+
406
+
407
+ def _state_findings(product: ToolProduct, home: ToolHome) -> list[Finding]:
408
+ """Whether ``state.json`` is readable and at the product's schema version."""
409
+ try:
410
+ recorded = json.loads(home.state_path.read_text(encoding="utf-8"))
411
+ schema = int(recorded["schema_version"])
412
+ except (OSError, ValueError, KeyError, TypeError) as error:
413
+ return [
414
+ Finding(
415
+ "install.state-unreadable",
416
+ Severity.WARNING,
417
+ f"cannot read the install state: {error}",
418
+ path=str(home.state_path),
419
+ )
420
+ ]
421
+ if schema != product.state_schema_version:
422
+ return [
423
+ Finding(
424
+ "install.state-schema",
425
+ Severity.ERROR,
426
+ f"state is at schema {schema}, this version expects "
427
+ f"{product.state_schema_version}; reinstall to migrate it",
428
+ path=str(home.state_path),
429
+ details={
430
+ "recorded": schema,
431
+ "expected": product.state_schema_version,
432
+ },
433
+ )
434
+ ]
435
+ return []
@@ -0,0 +1,113 @@
1
+ """Product description consumed by tool lifecycle operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from collections.abc import Callable, Iterable, Sequence
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from rn_forge.commons.exceptions import AppException
11
+ from rn_forge.commons.findings import Finding
12
+ from rn_forge.commons.fs.paths import PathUtils
13
+ from rn_forge.tooling.install.home import ToolHome
14
+ from rn_forge.tooling.install.release import GitHubReleases, ReleaseSource
15
+
16
+ __all__ = ["Check", "Link", "ToolProduct"]
17
+
18
+ Check = Callable[[ToolHome], Iterable[Finding]]
19
+ """A product-specific doctor check: inspect the install, report what is true of it.
20
+
21
+ Report a passing check as an ``info`` finding rather than nothing, so ``doctor``
22
+ shows that it ran.
23
+ """
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Link:
28
+ """A symlink an install puts in place outside the version directory.
29
+
30
+ The link points through ``current``, never at a version directory, so an
31
+ upgrade swaps what it resolves to without touching the link.
32
+
33
+ Args:
34
+ path: Where the link goes, relative to ``$RNF_HOME`` — ``bin/golden-tool``.
35
+ target: What it points at, relative to the installed version's root.
36
+ """
37
+
38
+ path: str
39
+ target: str
40
+
41
+ def __post_init__(self) -> None:
42
+ # Normalised here rather than at use: a link outside the home, or
43
+ # through `..` out of the version, is wrong however it is used.
44
+ object.__setattr__(self, "path", PathUtils.normalize_relative(self.path))
45
+ object.__setattr__(self, "target", PathUtils.normalize_relative(self.target))
46
+ if self.path == ".":
47
+ raise AppException("A link cannot replace the home directory itself")
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ToolProduct:
52
+ """An installable tool, as the lifecycle verbs see it.
53
+
54
+ Args:
55
+ name: The product's name, and its directory under ``$RNF_HOME``.
56
+ version: The version of the running code — normally the package's
57
+ ``__version__``.
58
+ repo: ``owner/name`` of the GitHub repository releases are tagged in.
59
+ Used only when *release_source* is not given.
60
+ release_source: Where releases come from. Defaults to
61
+ :class:`GitHubReleases` of *repo*.
62
+ state_schema_version: The version of whatever state the product keeps
63
+ under its home. ``doctor`` reports an install recorded at another
64
+ one; :meth:`migrate` is what moves it.
65
+ """
66
+
67
+ name: str
68
+ version: str
69
+ repo: str | None = None
70
+ release_source: ReleaseSource | None = None
71
+ state_schema_version: int = 1
72
+
73
+ @property
74
+ def source(self) -> ReleaseSource:
75
+ """The release source to fetch from.
76
+
77
+ Raises:
78
+ AppException: Neither *release_source* nor *repo* was given.
79
+ """
80
+ if self.release_source is not None:
81
+ return self.release_source
82
+ if self.repo is None:
83
+ raise AppException(
84
+ "{} declares neither a release source nor a repository", self.name
85
+ )
86
+ return GitHubReleases(self.repo)
87
+
88
+ def artifacts(self) -> Sequence[Link]:
89
+ """What an install puts in place beside the version directory. Default: nothing."""
90
+ return ()
91
+
92
+ def checks(self) -> Sequence[Check]:
93
+ """Product-specific ``doctor`` checks. Default: none."""
94
+ return ()
95
+
96
+ def build(self, release_root: Path, version_dir: Path) -> None:
97
+ """Turn an extracted release into an installed version directory.
98
+
99
+ The default copies the release tree. Implementations that create
100
+ path-dependent artifacts must build them directly in *version_dir*.
101
+
102
+ Args:
103
+ release_root: The extracted release's root directory.
104
+ version_dir: The directory to populate. Does not exist yet.
105
+ """
106
+ shutil.copytree(release_root, version_dir, symlinks=True)
107
+
108
+ def migrate(self, frm: str, to: str) -> None:
109
+ """Move the product's state from version *frm* to version *to*. Default: nothing.
110
+
111
+ Runs after the new version is built and before it is activated. Raise
112
+ to abandon the install; the previous version stays active.
113
+ """