phlo-transform 0.2.0__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,343 @@
1
+ """Locate, install, and invoke the Phlo Transform CLI binary.
2
+
3
+ The Python provider is a thin adapter over the Rust engine: every semantic
4
+ answer comes from the binary's JSON reports rather than a reimplementation.
5
+ The binary is looked up in ``PHLO_TRANSFORM_BIN``, then ``.phlo/bin``, then
6
+ ``PATH``; ``phlo transform install`` downloads the pinned portable release
7
+ into ``.phlo/bin`` so a project can carry its engine version with it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import platform
16
+ import shutil
17
+ import subprocess
18
+ import tarfile
19
+ import tempfile
20
+ from collections.abc import Mapping
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from urllib.request import urlopen
24
+
25
+ from phlo.exceptions import PhloCapabilitySetupError
26
+ from phlo.logging import get_logger
27
+
28
+ from phlo_transform.settings import TransformSettings
29
+
30
+ logger = get_logger(__name__)
31
+
32
+ RELEASE_BASE_URL = "https://github.com/phlohouse/phlo-transform/releases/download"
33
+ BINARY_NAME = "phlo-transform"
34
+
35
+ _TARGETS = {
36
+ ("linux", "x86_64"): "x86_64-unknown-linux-gnu",
37
+ ("linux", "amd64"): "x86_64-unknown-linux-gnu",
38
+ ("linux", "aarch64"): "aarch64-unknown-linux-gnu",
39
+ ("linux", "arm64"): "aarch64-unknown-linux-gnu",
40
+ ("darwin", "x86_64"): "x86_64-apple-darwin",
41
+ ("darwin", "arm64"): "aarch64-apple-darwin",
42
+ ("windows", "amd64"): "x86_64-pc-windows-msvc",
43
+ ("windows", "x86_64"): "x86_64-pc-windows-msvc",
44
+ }
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class Invocation:
49
+ """Captured result of one CLI invocation."""
50
+
51
+ command: tuple[str, ...]
52
+ returncode: int
53
+ stdout: str
54
+ stderr: str
55
+
56
+ @property
57
+ def ok(self) -> bool:
58
+ """Return True when the process exited successfully."""
59
+
60
+ return self.returncode == 0
61
+
62
+ def json(self) -> dict | None:
63
+ """Parse the JSON report emitted on stdout, if any."""
64
+
65
+ text = self.stdout.strip()
66
+ if not text:
67
+ return None
68
+ try:
69
+ payload = json.loads(text)
70
+ except ValueError:
71
+ return None
72
+ return payload if isinstance(payload, dict) else None
73
+
74
+
75
+ def binary_name() -> str:
76
+ """Return the executable name for the current platform."""
77
+
78
+ return f"{BINARY_NAME}.exe" if platform.system().lower() == "windows" else BINARY_NAME
79
+
80
+
81
+ def release_target() -> str:
82
+ """Return the release target triple for the current platform."""
83
+
84
+ system = platform.system().lower()
85
+ machine = platform.machine().lower()
86
+ target = _TARGETS.get((system, machine))
87
+ if target is None:
88
+ raise PhloCapabilitySetupError(
89
+ capability="transform",
90
+ required=True,
91
+ message=f"phlo-transform has no portable release for {system}/{machine}",
92
+ suggestions=[
93
+ "Build the engine from source: cargo install --path crates/phlo-transform-cli",
94
+ "Point PHLO_TRANSFORM_BIN at an existing phlo-transform executable",
95
+ ],
96
+ )
97
+ return target
98
+
99
+
100
+ def find_binary(project_root: Path, settings: TransformSettings) -> Path | None:
101
+ """Return the first usable binary path, or None when none is installed."""
102
+
103
+ candidates: list[Path] = []
104
+ if settings.binary:
105
+ configured = Path(settings.binary).expanduser()
106
+ candidates.append(configured if configured.is_absolute() else project_root / configured)
107
+ candidates.append(project_root / ".phlo" / "bin" / binary_name())
108
+ on_path = shutil.which(BINARY_NAME)
109
+ if on_path:
110
+ candidates.append(Path(on_path))
111
+ for candidate in candidates:
112
+ if candidate.is_file():
113
+ return candidate
114
+ return None
115
+
116
+
117
+ def require_binary(project_root: Path, settings: TransformSettings) -> Path:
118
+ """Return the installed binary or raise actionable setup guidance."""
119
+
120
+ binary = find_binary(project_root, settings)
121
+ if binary is not None:
122
+ return binary
123
+ raise PhloCapabilitySetupError(
124
+ capability="transform",
125
+ required=True,
126
+ message="phlo-transform workspace found but the phlo-transform executable is missing",
127
+ suggestions=[
128
+ "Run: phlo transform install",
129
+ "Or install it on PATH: cargo install --path crates/phlo-transform-cli",
130
+ "Or set PHLO_TRANSFORM_BIN to an existing executable",
131
+ ],
132
+ )
133
+
134
+
135
+ def binary_version(binary: Path, settings: TransformSettings) -> str | None:
136
+ """Return the binary's reported version, or None when it cannot be read."""
137
+
138
+ invocation = run_cli(binary, [], settings=settings, root=None, extra_args=["--version"])
139
+ text = (invocation.stdout or invocation.stderr).strip().splitlines()
140
+ if not text:
141
+ return None
142
+ return text[0].strip()
143
+
144
+
145
+ def _public_command(command: list[str]) -> list[str]:
146
+ public: list[str] = []
147
+ redact_next = False
148
+ for argument in command:
149
+ if redact_next:
150
+ public.append("[redacted]")
151
+ redact_next = False
152
+ elif argument in {"--trino-password", "--nessie-token"}:
153
+ public.append(argument)
154
+ redact_next = True
155
+ elif argument.startswith(("--trino-password=", "--nessie-token=")):
156
+ public.append(argument.partition("=")[0] + "=[redacted]")
157
+ else:
158
+ public.append(argument)
159
+ return public
160
+
161
+
162
+ def run_cli(
163
+ binary: Path,
164
+ args: list[str],
165
+ *,
166
+ settings: TransformSettings,
167
+ root: Path | None,
168
+ extra_args: list[str] | None = None,
169
+ environment: Mapping[str, str | None] | None = None,
170
+ ) -> Invocation:
171
+ """Invoke the CLI and capture its output without raising on failure."""
172
+
173
+ command = [str(binary)]
174
+ if root is not None:
175
+ command.extend(["--root", str(root)])
176
+ command.extend(extra_args or [])
177
+ command.extend(args)
178
+ public_command = _public_command(command)
179
+ env = {**os.environ}
180
+ for key, value in (environment or {}).items():
181
+ if value is None:
182
+ env.pop(key, None)
183
+ else:
184
+ env[key] = value
185
+ try:
186
+ # reason: the executable path is resolved from settings or PATH, not shell input.
187
+ completed = subprocess.run( # noqa: S603 - the executable path is resolved locally
188
+ command,
189
+ capture_output=True,
190
+ text=True,
191
+ check=False,
192
+ env=env,
193
+ timeout=settings.timeout_seconds,
194
+ )
195
+ except FileNotFoundError as exc:
196
+ raise PhloCapabilitySetupError(
197
+ capability="transform",
198
+ required=True,
199
+ message=f"phlo-transform executable not found: {binary}",
200
+ suggestions=["Run: phlo transform install"],
201
+ cause=exc,
202
+ ) from exc
203
+ except subprocess.TimeoutExpired as exc:
204
+ exc.cmd = public_command
205
+ raise PhloCapabilitySetupError(
206
+ capability="transform",
207
+ required=True,
208
+ message=f"phlo-transform exceeded {settings.timeout_seconds:.0f}s: {' '.join(public_command)}",
209
+ suggestions=["Raise PHLO_TRANSFORM_TIMEOUT_SECONDS or narrow the selection"],
210
+ cause=exc,
211
+ ) from exc
212
+ logger.debug(
213
+ "phlo_transform_cli_finished",
214
+ command=" ".join(public_command),
215
+ returncode=completed.returncode,
216
+ )
217
+ return Invocation(
218
+ command=tuple(public_command),
219
+ returncode=completed.returncode,
220
+ stdout=completed.stdout or "",
221
+ stderr=completed.stderr or "",
222
+ )
223
+
224
+
225
+ def run_json(
226
+ binary: Path,
227
+ args: list[str],
228
+ *,
229
+ settings: TransformSettings,
230
+ root: Path,
231
+ environment: Mapping[str, str | None] | None = None,
232
+ ) -> tuple[dict | None, Invocation]:
233
+ """Invoke the CLI with ``--json`` and return the parsed report and process."""
234
+
235
+ invocation = run_cli(
236
+ binary, ["--json", *args], settings=settings, root=root, environment=environment
237
+ )
238
+ return invocation.json(), invocation
239
+
240
+
241
+ def _download(url: str, timeout: float) -> bytes:
242
+ # reason: the URL is a fixed GitHub release asset built by this package.
243
+ with urlopen(url, timeout=timeout) as response: # noqa: S310 - fixed GitHub release URL
244
+ return response.read()
245
+
246
+
247
+ def _sha256(data: bytes) -> str:
248
+ return hashlib.sha256(data).hexdigest()
249
+
250
+
251
+ def _safe_extract(archive: Path, destination: Path) -> list[Path]:
252
+ """Extract a release archive without path traversal and return members."""
253
+
254
+ extracted: list[Path] = []
255
+ with tarfile.open(archive, "r:gz") as tar:
256
+ for member in tar.getmembers():
257
+ target = (destination / member.name).resolve()
258
+ if not target.is_relative_to(destination.resolve()):
259
+ raise ValueError(f"archive member escapes the destination: {member.name}")
260
+ if not member.isfile():
261
+ continue
262
+ tar.extract(member, path=destination, filter="data")
263
+ extracted.append(target)
264
+ return extracted
265
+
266
+
267
+ def install_binary(
268
+ project_root: Path,
269
+ settings: TransformSettings,
270
+ *,
271
+ version: str | None = None,
272
+ force: bool = False,
273
+ ) -> Path:
274
+ """Download the pinned release binary into ``.phlo/bin`` and return it."""
275
+
276
+ destination = project_root / ".phlo" / "bin"
277
+ destination.mkdir(parents=True, exist_ok=True)
278
+ target_path = destination / binary_name()
279
+ if target_path.exists() and not force:
280
+ return target_path
281
+
282
+ release = version or settings.release_version
283
+ target = release_target()
284
+ archive_url = f"{RELEASE_BASE_URL}/v{release}/{BINARY_NAME}-{target}.tar.gz"
285
+ archive_bytes = _download(archive_url, timeout=max(settings.timeout_seconds, 60.0))
286
+ checksum_bytes = _download(f"{archive_url}.sha256", timeout=max(settings.timeout_seconds, 60.0))
287
+ expected = checksum_bytes.decode("utf-8").split()[0].strip().lower()
288
+ actual = _sha256(archive_bytes)
289
+ if actual != expected:
290
+ raise PhloCapabilitySetupError(
291
+ capability="transform",
292
+ required=True,
293
+ message=(
294
+ f"phlo-transform {release} checksum mismatch for {target}: "
295
+ f"expected {expected}, got {actual}"
296
+ ),
297
+ suggestions=[
298
+ "Retry phlo transform install",
299
+ "Pin a different PHLO_TRANSFORM_RELEASE_VERSION",
300
+ ],
301
+ )
302
+
303
+ with tempfile.TemporaryDirectory(dir=destination) as temporary:
304
+ archive = Path(temporary) / "release.tar.gz"
305
+ archive.write_bytes(archive_bytes)
306
+ extracted = _safe_extract(archive, Path(temporary))
307
+ candidate = next(
308
+ (path for path in extracted if path.name in {BINARY_NAME, f"{BINARY_NAME}.exe"}),
309
+ None,
310
+ )
311
+ if candidate is None:
312
+ raise PhloCapabilitySetupError(
313
+ capability="transform",
314
+ required=True,
315
+ message=f"release archive {archive_url} does not contain {BINARY_NAME}",
316
+ suggestions=["Report the broken release or pin another version"],
317
+ )
318
+ staged = destination / f".{binary_name()}.tmp"
319
+ shutil.copyfile(candidate, staged)
320
+ staged.chmod(0o755)
321
+ staged.replace(target_path)
322
+ logger.info(
323
+ "phlo_transform_binary_installed",
324
+ version=release,
325
+ target=target,
326
+ path=str(target_path),
327
+ )
328
+ return target_path
329
+
330
+
331
+ __all__ = [
332
+ "BINARY_NAME",
333
+ "RELEASE_BASE_URL",
334
+ "Invocation",
335
+ "binary_name",
336
+ "binary_version",
337
+ "find_binary",
338
+ "install_binary",
339
+ "release_target",
340
+ "require_binary",
341
+ "run_cli",
342
+ "run_json",
343
+ ]