vitna-local 0.3.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,35 @@
1
+ """Python wrapper for the single-binary Apache-2.0 Rust `vitna-local` engine."""
2
+
3
+ from ._binary import (
4
+ PACKAGE_VERSION as __version__,
5
+ BinaryNotFoundError,
6
+ ChecksumError,
7
+ VitnaLocalError,
8
+ ensure_binary,
9
+ find_binary,
10
+ install_binary,
11
+ parse_sha256sums,
12
+ resolve_target,
13
+ verify_sha256,
14
+ )
15
+ from .client import crawl, diff, extract, map_site, scrape
16
+ from .server import VitnaLocalServer
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "BinaryNotFoundError",
21
+ "ChecksumError",
22
+ "VitnaLocalError",
23
+ "VitnaLocalServer",
24
+ "crawl",
25
+ "diff",
26
+ "ensure_binary",
27
+ "extract",
28
+ "find_binary",
29
+ "install_binary",
30
+ "map_site",
31
+ "parse_sha256sums",
32
+ "resolve_target",
33
+ "scrape",
34
+ "verify_sha256",
35
+ ]
@@ -0,0 +1,6 @@
1
+ """Support `python -m vitna_local`."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
vitna_local/_binary.py ADDED
@@ -0,0 +1,347 @@
1
+ """Binary discovery and SHA-256 verified installation for Vitna Local."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ import io
8
+ import os
9
+ import platform
10
+ import shutil
11
+ import stat
12
+ import tarfile
13
+ import tempfile
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ import zipfile
18
+ from pathlib import Path
19
+ from typing import Optional, Tuple, Union
20
+
21
+ PACKAGE_VERSION = "0.3.0"
22
+ DEFAULT_REPO = "convexityos/vitna-local"
23
+
24
+
25
+ class VitnaLocalError(RuntimeError):
26
+ """Base error raised when invoking vitna-local fails."""
27
+
28
+ def __init__(
29
+ self,
30
+ message: str,
31
+ *,
32
+ returncode: Optional[int] = None,
33
+ stderr: Optional[str] = None,
34
+ status_code: Optional[int] = None,
35
+ error_code: Optional[str] = None,
36
+ ) -> None:
37
+ super().__init__(message)
38
+ self.returncode = returncode
39
+ self.stderr = stderr
40
+ self.status_code = status_code
41
+ self.error_code = error_code
42
+
43
+
44
+ class BinaryNotFoundError(VitnaLocalError):
45
+ """Raised when no vitna-local native binary can be located."""
46
+
47
+
48
+ class ChecksumError(VitnaLocalError):
49
+ """Raised when SHA-256 verification of a downloaded archive fails."""
50
+
51
+
52
+ def resolve_target(
53
+ system: Optional[str] = None,
54
+ machine: Optional[str] = None,
55
+ ) -> Tuple[str, str, str]:
56
+ """Return `(rust_target_triple, archive_ext, binary_name)` matching release artifacts."""
57
+ sys_name = (system or platform.system()).lower()
58
+ arch_raw = (machine or platform.machine()).lower()
59
+
60
+ if arch_raw in ("x86_64", "amd64"):
61
+ arch = "x86_64"
62
+ elif arch_raw in ("aarch64", "arm64"):
63
+ arch = "aarch64"
64
+ else:
65
+ arch = arch_raw
66
+
67
+ if sys_name == "linux" and arch == "x86_64":
68
+ return ("x86_64-unknown-linux-gnu", "tar.gz", "vitna-local")
69
+ if sys_name == "linux" and arch == "aarch64":
70
+ return ("aarch64-unknown-linux-gnu", "tar.gz", "vitna-local")
71
+ if sys_name == "darwin" and arch == "aarch64":
72
+ return ("aarch64-apple-darwin", "tar.gz", "vitna-local")
73
+ if sys_name == "darwin" and arch == "x86_64":
74
+ return ("x86_64-apple-darwin", "tar.gz", "vitna-local")
75
+ if sys_name in ("windows", "win32") and arch == "x86_64":
76
+ return ("x86_64-pc-windows-msvc", "zip", "vitna-local.exe")
77
+
78
+ repo = os.environ.get("VITNA_LOCAL_REPO") or DEFAULT_REPO
79
+ raise VitnaLocalError(
80
+ f"Unsupported platform {sys_name}/{arch_raw}. Build from source at https://github.com/{repo}"
81
+ )
82
+
83
+
84
+ def default_cache_dir(version: Optional[str] = None) -> Path:
85
+ """Return the default per-user cache directory for downloaded binaries."""
86
+ target, _, _ = resolve_target()
87
+ tag = _normalize_version_tag(version) or f"v{PACKAGE_VERSION}"
88
+ if os.name == "nt":
89
+ local_app_data = os.environ.get("LOCALAPPDATA")
90
+ if local_app_data:
91
+ return Path(local_app_data) / "vitna-local" / "cache" / tag / target
92
+ cache_root = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
93
+ return Path(cache_root) / "vitna-local" / tag / target
94
+
95
+
96
+ def _normalize_version_tag(version: Optional[str]) -> Optional[str]:
97
+ if not version:
98
+ return None
99
+ cleaned = version.strip()
100
+ if not cleaned:
101
+ return None
102
+ if cleaned.lower() == "latest":
103
+ return "latest"
104
+ return cleaned if cleaned.startswith("v") else f"v{cleaned}"
105
+
106
+
107
+ def _binary_name_for_host() -> str:
108
+ return "vitna-local.exe" if os.name == "nt" else "vitna-local"
109
+
110
+
111
+ def find_binary(explicit: Optional[Union[str, Path]] = None) -> Optional[Path]:
112
+ """Locate the native `vitna-local` binary.
113
+
114
+ Search order:
115
+ 1. Explicit `explicit` path argument (raises BinaryNotFoundError if missing).
116
+ 2. `VITNA_LOCAL_BIN` environment variable (raises BinaryNotFoundError if missing).
117
+ 3. Bundled binary inside `vitna_local/bin/`.
118
+ 4. Cached downloaded binary or standard installer location.
119
+ 5. `PATH` lookup via `shutil.which`.
120
+ """
121
+ if explicit is not None:
122
+ p = Path(explicit)
123
+ if not p.is_file():
124
+ raise BinaryNotFoundError(f"Explicit vitna-local binary not found: {p}")
125
+ return p
126
+
127
+ env_bin = os.environ.get("VITNA_LOCAL_BIN")
128
+ if env_bin:
129
+ p = Path(env_bin)
130
+ if not p.is_file():
131
+ raise BinaryNotFoundError(
132
+ f"VITNA_LOCAL_BIN points to a missing file: {p}"
133
+ )
134
+ return p
135
+
136
+ bin_name = _binary_name_for_host()
137
+
138
+ bundled = Path(__file__).resolve().parent / "bin" / bin_name
139
+ if bundled.is_file():
140
+ return bundled
141
+
142
+ try:
143
+ cached = default_cache_dir(os.environ.get("VITNA_LOCAL_VERSION")) / bin_name
144
+ if cached.is_file():
145
+ return cached
146
+ except VitnaLocalError:
147
+ pass
148
+
149
+ # Also check standard install.sh / install.ps1 destinations.
150
+ if os.name == "nt":
151
+ local_app_data = os.environ.get("LOCALAPPDATA")
152
+ if local_app_data:
153
+ ps_bin = Path(local_app_data) / "vitna-local" / "bin" / "vitna-local.exe"
154
+ if ps_bin.is_file():
155
+ return ps_bin
156
+ else:
157
+ sh_bin = Path.home() / ".local" / "bin" / "vitna-local"
158
+ if sh_bin.is_file():
159
+ return sh_bin
160
+
161
+ on_path = shutil.which(bin_name) or shutil.which("vitna-local")
162
+ if on_path:
163
+ return Path(on_path)
164
+
165
+ return None
166
+
167
+
168
+ def parse_sha256sums(sums_text: str, archive_name: str) -> str:
169
+ """Extract the expected lowercase SHA-256 hex digest for `archive_name`."""
170
+ suffix = f" {archive_name}"
171
+ for line in sums_text.splitlines():
172
+ if line.endswith(suffix):
173
+ digest = line.strip().split()[0].lower()
174
+ if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
175
+ raise ChecksumError(
176
+ f"Malformed SHA-256 entry for {archive_name} in SHA256SUMS.txt"
177
+ )
178
+ return digest
179
+ raise ChecksumError(
180
+ f"Checksum entry for {archive_name} not found in SHA256SUMS.txt"
181
+ )
182
+
183
+
184
+ def verify_sha256(data: bytes, expected_hex: str, label: str = "archive") -> str:
185
+ """Verify SHA-256 of `data` in constant time; raises ChecksumError on mismatch."""
186
+ expected = expected_hex.strip().lower()
187
+ actual = hashlib.sha256(data).hexdigest().lower()
188
+ if not hmac.compare_digest(actual, expected):
189
+ raise ChecksumError(
190
+ f"SHA-256 mismatch for {label}: expected {expected}, got {actual}"
191
+ )
192
+ return actual
193
+
194
+
195
+ def _validate_download_url(url: str, *, allow_loopback_http: bool = False) -> None:
196
+ parsed = urllib.parse.urlparse(url)
197
+ if parsed.scheme == "https":
198
+ return
199
+ if (
200
+ allow_loopback_http
201
+ and parsed.scheme == "http"
202
+ and parsed.hostname in ("127.0.0.1", "localhost", "::1")
203
+ ):
204
+ return
205
+ raise VitnaLocalError(
206
+ f"Refusing insecure binary download URL '{url}': HTTPS is required"
207
+ )
208
+
209
+
210
+ def _fetch_bytes(url: str, *, timeout: float, allow_loopback_http: bool) -> bytes:
211
+ _validate_download_url(url, allow_loopback_http=allow_loopback_http)
212
+ req = urllib.request.Request(
213
+ url,
214
+ headers={"User-Agent": f"vitna-local-python/{PACKAGE_VERSION}"},
215
+ )
216
+ try:
217
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
218
+ status = getattr(resp, "status", 200)
219
+ if status != 200:
220
+ raise VitnaLocalError(
221
+ f"HTTP {status} downloading {url}",
222
+ status_code=status,
223
+ )
224
+ return resp.read()
225
+ except urllib.error.HTTPError as exc:
226
+ raise VitnaLocalError(
227
+ f"HTTP {exc.code} downloading {url}",
228
+ status_code=exc.code,
229
+ ) from exc
230
+ except urllib.error.URLError as exc:
231
+ raise VitnaLocalError(f"Failed downloading {url}: {exc.reason}") from exc
232
+
233
+
234
+ def _extract_single_binary(archive_bytes: bytes, ext: str, bin_name: str) -> bytes:
235
+ """Safely extract only the exact target executable member from a release archive."""
236
+ if ext == "tar.gz":
237
+ with tarfile.open(fileobj=io.BytesIO(archive_bytes), mode="r:gz") as tf:
238
+ for member in tf.getmembers():
239
+ normalized = member.name.lstrip("./")
240
+ if normalized == bin_name and member.isfile():
241
+ fh = tf.extractfile(member)
242
+ if fh is None:
243
+ break
244
+ return fh.read()
245
+ raise VitnaLocalError(f"Binary '{bin_name}' not found inside tar.gz archive")
246
+ if ext == "zip":
247
+ with zipfile.ZipFile(io.BytesIO(archive_bytes), mode="r") as zf:
248
+ for info in zf.infolist():
249
+ normalized = info.filename.replace("\\", "/").lstrip("./")
250
+ if normalized == bin_name and not info.is_dir():
251
+ return zf.read(info)
252
+ raise VitnaLocalError(f"Binary '{bin_name}' not found inside zip archive")
253
+ raise VitnaLocalError(f"Unsupported archive format: {ext}")
254
+
255
+
256
+ def install_binary(
257
+ *,
258
+ version: Optional[str] = None,
259
+ dest_dir: Optional[Union[str, Path]] = None,
260
+ repo: Optional[str] = None,
261
+ base_url: Optional[str] = None,
262
+ timeout: float = 60.0,
263
+ ) -> Path:
264
+ """Download, SHA-256 verify, and install the matching prebuilt `vitna-local` binary.
265
+
266
+ Matches the release artifact layout and `SHA256SUMS.txt` verification used by
267
+ `install.sh`, `install.ps1`, and `npm/bin/vitna-local.mjs`.
268
+ """
269
+ target, ext, bin_name = resolve_target()
270
+ archive_name = f"vitna-local-{target}.{ext}"
271
+ resolved_repo = repo or os.environ.get("VITNA_LOCAL_REPO") or DEFAULT_REPO
272
+ tag = _normalize_version_tag(version or os.environ.get("VITNA_LOCAL_VERSION"))
273
+
274
+ allow_loopback = base_url is not None
275
+ if base_url is not None:
276
+ release_base = base_url.rstrip("/")
277
+ elif tag and tag != "latest":
278
+ release_base = f"https://github.com/{resolved_repo}/releases/download/{tag}"
279
+ else:
280
+ release_base = (
281
+ f"https://github.com/{resolved_repo}/releases/download/v{PACKAGE_VERSION}"
282
+ if tag is None
283
+ else f"https://github.com/{resolved_repo}/releases/latest/download"
284
+ )
285
+
286
+ archive_bytes = _fetch_bytes(
287
+ f"{release_base}/{archive_name}",
288
+ timeout=timeout,
289
+ allow_loopback_http=allow_loopback,
290
+ )
291
+ sums_bytes = _fetch_bytes(
292
+ f"{release_base}/SHA256SUMS.txt",
293
+ timeout=timeout,
294
+ allow_loopback_http=allow_loopback,
295
+ )
296
+ expected_hash = parse_sha256sums(sums_bytes.decode("utf-8"), archive_name)
297
+ verify_sha256(archive_bytes, expected_hash, label=archive_name)
298
+
299
+ bin_bytes = _extract_single_binary(archive_bytes, ext, bin_name)
300
+
301
+ target_dir = Path(dest_dir) if dest_dir is not None else default_cache_dir(tag)
302
+ target_dir.mkdir(parents=True, exist_ok=True)
303
+ dest_path = target_dir / bin_name
304
+
305
+ fd, tmp_name = tempfile.mkstemp(prefix=".vitna-local-", dir=str(target_dir))
306
+ tmp_path = Path(tmp_name)
307
+ try:
308
+ with os.fdopen(fd, "wb") as out:
309
+ out.write(bin_bytes)
310
+ if os.name != "nt":
311
+ os.chmod(
312
+ tmp_path,
313
+ stat.S_IRUSR
314
+ | stat.S_IWUSR
315
+ | stat.S_IXUSR
316
+ | stat.S_IRGRP
317
+ | stat.S_IXGRP
318
+ | stat.S_IROTH
319
+ | stat.S_IXOTH,
320
+ )
321
+ os.replace(tmp_path, dest_path)
322
+ finally:
323
+ if tmp_path.exists():
324
+ try:
325
+ tmp_path.unlink()
326
+ except OSError:
327
+ pass
328
+
329
+ return dest_path
330
+
331
+
332
+ def ensure_binary(
333
+ explicit: Optional[Union[str, Path]] = None,
334
+ *,
335
+ auto_install: bool = False,
336
+ ) -> Path:
337
+ """Return a ready-to-execute `vitna-local` binary path or raise BinaryNotFoundError."""
338
+ found = find_binary(explicit)
339
+ if found is not None:
340
+ return found
341
+ if auto_install:
342
+ return install_binary()
343
+ raise BinaryNotFoundError(
344
+ "Could not locate the native `vitna-local` binary. "
345
+ "Set VITNA_LOCAL_BIN, add `vitna-local` to PATH, or run "
346
+ "`python -m vitna_local install-binary`."
347
+ )
vitna_local/cli.py ADDED
@@ -0,0 +1,58 @@
1
+ """CLI entrypoint for `vitna-local-py` and `python -m vitna_local`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from typing import Optional, Sequence
10
+
11
+ from ._binary import VitnaLocalError, ensure_binary, install_binary
12
+
13
+
14
+ def _run_install_subcommand(args: Sequence[str]) -> int:
15
+ parser = argparse.ArgumentParser(
16
+ prog="vitna-local-py install-binary",
17
+ description="Download and SHA-256 verify the matching prebuilt vitna-local native binary.",
18
+ )
19
+ parser.add_argument("--version", default=None, help="Release tag (e.g. v0.3.0 or latest)")
20
+ parser.add_argument("--dir", dest="dest_dir", default=None, help="Destination directory")
21
+ parser.add_argument("--repo", default=None, help="GitHub repo slug")
22
+ parser.add_argument("--base-url", default=None, help="Override release base URL")
23
+ ns = parser.parse_args(list(args))
24
+
25
+ path = install_binary(
26
+ version=ns.version,
27
+ dest_dir=ns.dest_dir,
28
+ repo=ns.repo,
29
+ base_url=ns.base_url,
30
+ )
31
+ print(path)
32
+ return 0
33
+
34
+
35
+ def main(argv: Optional[Sequence[str]] = None) -> int:
36
+ args = list(sys.argv[1:] if argv is None else argv)
37
+
38
+ try:
39
+ if args and args[0] == "install-binary":
40
+ return _run_install_subcommand(args[1:])
41
+
42
+ auto_install = os.environ.get("VITNA_LOCAL_AUTO_INSTALL", "").lower() in (
43
+ "1",
44
+ "true",
45
+ "yes",
46
+ )
47
+ bin_path = ensure_binary(auto_install=auto_install)
48
+ completed = subprocess.run([str(bin_path), *args], check=False)
49
+ return int(completed.returncode)
50
+ except VitnaLocalError as exc:
51
+ print(f"vitna-local-py error: {exc}", file=sys.stderr)
52
+ return 1
53
+ except KeyboardInterrupt:
54
+ return 130
55
+
56
+
57
+ if __name__ == "__main__":
58
+ raise SystemExit(main())