enchi 0.8.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,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: enchi
3
+ Version: 0.8.0
4
+ Summary: Python install package for the native Enchi release bundles (formerly pyenv-native).
5
+ Project-URL: Homepage, https://github.com/imyourboyroy
6
+ Project-URL: Repository, https://github.com/imyourboyroy/pyenv-native
7
+ Project-URL: Issues, https://github.com/imyourboyroy/pyenv-native/issues
8
+ Author-email: Roy Dawson IV <Roy.Dawson.IV@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: bootstrap,enchi,pipx,pyenv,python,windows
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Classifier: Programming Language :: Python :: 3.15
29
+ Classifier: Topic :: Software Development
30
+ Classifier: Topic :: System :: Installation/Setup
31
+ Requires-Python: >=3.8
32
+ Description-Content-Type: text/markdown
33
+
34
+ # enchi (Python install package)
35
+
36
+ ![PyPI Channel](https://img.shields.io/badge/channel-PyPI%20%2F%20pipx-3775A9?style=for-the-badge&logo=pypi&logoColor=white)
37
+ ![Runtime](https://img.shields.io/badge/runtime-install%20package%20for%20native%20bundles-2563eb?style=for-the-badge)
38
+ ![License](https://img.shields.io/badge/license-MIT-15803D?style=for-the-badge)
39
+
40
+ `enchi` on PyPI is the Python convenience package for installing the native Enchi release bundles.
41
+ Enchi was called `pyenv-native` before; the `pyenv-native` PyPI package is now a thin wrapper that
42
+ depends on this one.
43
+
44
+ Those bundles install:
45
+ - `enchi` (the CLI)
46
+ - `enchi-mcp` (the MCP server for coding agents)
47
+ - `enchi-gui` (desktop builds)
48
+
49
+ It exists for users who:
50
+ - already have Python installed,
51
+ - want a `pip` or `pipx` entrypoint,
52
+ - still want the real runtime to remain native.
53
+
54
+ The console script this package adds is **`enchi-bootstrap`**, not `enchi`, so it never shadows the
55
+ real `enchi` binary the bundle installs.
56
+
57
+ ## Important principle
58
+
59
+ > This package installs Enchi.
60
+ > It does **not** replace Enchi with a Python implementation.
61
+
62
+ ## Release selection behavior
63
+
64
+ By default, the package targets the **latest published GitHub release**.
65
+
66
+ ## What it does
67
+
68
+ - downloads native release bundles (`enchi-<platform>-<arch>`),
69
+ - verifies checksums,
70
+ - reads bundle metadata,
71
+ - extracts the bundle,
72
+ - runs the bundled installer (`enchi self-install`),
73
+ - installs the companion `enchi-mcp` server when the bundle provides it,
74
+ - supports GitHub Release-based installs,
75
+ - works with Windows ZIP bundles and Linux/macOS `.tar.gz` bundles.
76
+
77
+ Where the install goes is decided by `enchi self-install`: a fresh install uses `~/.enchi`, and an
78
+ existing pyenv-native install keeps its `~/.pyenv` root. Pass `--install-root` to choose one.
79
+
80
+ ## Quick start
81
+
82
+ ### `pipx` latest release
83
+
84
+ ```powershell
85
+ pipx install enchi
86
+ enchi-bootstrap install --github-repo imyourboyroy/pyenv-native
87
+ ```
88
+
89
+ ### `pip` latest release
90
+
91
+ ```powershell
92
+ python -m pip install enchi
93
+ enchi-bootstrap install --github-repo imyourboyroy/pyenv-native
94
+ ```
95
+
96
+ ### POSIX latest release
97
+
98
+ ```sh
99
+ python -m pip install enchi
100
+ enchi-bootstrap install --github-repo imyourboyroy/pyenv-native
101
+ ```
102
+
103
+ (`imyourboyroy/pyenv-native` is the GitHub repository that publishes the releases; it keeps that
104
+ name until the repository itself is renamed.)
105
+
106
+ ## Commands
107
+
108
+ ```text
109
+ enchi-bootstrap verify <bundle-archive> [--checksum-path <bundle.sha256>]
110
+ enchi-bootstrap download [--bundle-url <url> | --release-base-url <url> | --github-repo <owner/repo>] [--tag <tag>]
111
+ enchi-bootstrap install [--bundle-path <bundle-archive> | --release-base-url <url> | --github-repo <owner/repo>] [--tag <tag>] [--install-root <dir>]
112
+ ```
113
+
114
+ `python -m enchi_bootstrap` runs the same commands.
115
+
116
+ Environment variables: `ENCHI_BOOTSTRAP_RELEASE_BASE_URL` and `ENCHI_BOOTSTRAP_GITHUB_REPO` supply
117
+ the download source. The earlier `PYENV_NATIVE_BOOTSTRAP_*` names are still read as a fallback.
118
+
119
+ ## Examples
120
+
121
+ Verify a local bundle:
122
+
123
+ ```powershell
124
+ enchi-bootstrap verify .\dist\enchi-windows-x64.zip --checksum-path .\dist\enchi-windows-x64.zip.sha256
125
+ ```
126
+
127
+ Install from a local bundle:
128
+
129
+ ```powershell
130
+ enchi-bootstrap install --bundle-path .\dist\enchi-windows-x64.zip --checksum-path .\dist\enchi-windows-x64.zip.sha256
131
+ ```
132
+
133
+ Install from the latest GitHub release into a chosen root:
134
+
135
+ ```powershell
136
+ enchi-bootstrap install --github-repo imyourboyroy/pyenv-native --install-root ~\.enchi
137
+ ```
138
+
139
+ Install a POSIX bundle:
140
+
141
+ ```sh
142
+ enchi-bootstrap install --bundle-path ./dist/enchi-linux-x64.tar.gz --checksum-path ./dist/enchi-linux-x64.tar.gz.sha256 --shell bash
143
+ ```
144
+
145
+ Releases published before the rename only carry `pyenv-native-<platform>-<arch>` bundles. When a
146
+ release has no `enchi-…` bundle, the GitHub download falls back to that name.
147
+
148
+ ## Relationship to the main project
149
+
150
+ For the full project overview, install scripts, release-bundle flow, and command reference, see the main repository README:
151
+
152
+ - <https://github.com/imyourboyroy/pyenv-native>
@@ -0,0 +1,12 @@
1
+ enchi_bootstrap/__init__.py,sha256=0Lu6-b0OFMG0v0eIHj73n3mD5Gm-Mrssjb04Pvw_7v4,155
2
+ enchi_bootstrap/__main__.py,sha256=kUy7cvmkTykll6wbvVOZhI4ID2ncIKZtgl3CV0PNT_0,185
3
+ enchi_bootstrap/bundle.py,sha256=gY0fvyKZreTIB7vTbEh6inC8H99Kv_0hLejaKwo1uYE,5972
4
+ enchi_bootstrap/cli.py,sha256=iJAjOh9ifVOWu17Au6loiA4rGWH7sxfIaW5ooPaLnO8,7902
5
+ enchi_bootstrap/github.py,sha256=9sUIt2Gl3rjGq-7ZMOUoCovs6HqxMpjCmkkorqycOwQ,3505
6
+ enchi_bootstrap/installer.py,sha256=UU_qXH1xnTrNdftJ3av5pP4UGPNPnuHRn_reS-y7qHg,11938
7
+ enchi_bootstrap/platforms.py,sha256=e6XSdgYh9jwauRCNcbQMFu6j6UOnLb7ChF1osM0sBUs,2392
8
+ enchi-0.8.0.dist-info/METADATA,sha256=bv-1XitZDVGVXamqB3Cwsuc9FgLrCw5HMlWGLzxei_U,5469
9
+ enchi-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ enchi-0.8.0.dist-info/entry_points.txt,sha256=uGqw1NuDJ5KzqYK9XY8xTxB9me2y6tZpttgSKnE00-Y,61
11
+ enchi-0.8.0.dist-info/licenses/LICENSE,sha256=5PhY0JRIWCGE2aXRepu_qOwBO2QPTR3DfqRwwR_RaY0,1091
12
+ enchi-0.8.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ enchi-bootstrap = enchi_bootstrap.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roy Dawson IV
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,6 @@
1
+ # ./python-package/src/enchi_bootstrap/__init__.py
2
+ """Package metadata for the Enchi bootstrap helper."""
3
+
4
+ __all__ = ["__version__"]
5
+
6
+ __version__ = "0.8.0"
@@ -0,0 +1,8 @@
1
+ # ./python-package/src/enchi_bootstrap/__main__.py
2
+ """Module runner for `python -m enchi_bootstrap`."""
3
+
4
+ from .cli import main
5
+
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
@@ -0,0 +1,171 @@
1
+ # ./python-package/src/enchi_bootstrap/bundle.py
2
+ """Bundle metadata, checksum, and download helpers for Enchi release assets."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ import tarfile
9
+ import urllib.request
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Optional
13
+ from zipfile import ZipFile
14
+
15
+ from . import __version__
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class BundleManifest:
20
+ """Describes a built release bundle.
21
+
22
+ Current bundles install through the bundled binary (`<executable> self-install`) and carry no
23
+ scripts. Bundles published before that change name `install_script`/`uninstall_script`
24
+ instead; both are optional so either generation can be installed. Bundles that also carry a
25
+ `pyenv`-named copy of the CLI (the legacy-compat archives) name it in `legacy_executable`.
26
+ """
27
+
28
+ bundle_name: str
29
+ bundle_version: str
30
+ platform: str
31
+ architecture: str
32
+ executable: str
33
+ install_script: Optional[str] = None
34
+ uninstall_script: Optional[str] = None
35
+ legacy_executable: Optional[str] = None
36
+
37
+
38
+ def sha256_file(path: Path) -> str:
39
+ """Return the SHA-256 digest for a file."""
40
+
41
+ digest = hashlib.sha256()
42
+ with path.open("rb") as handle:
43
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
44
+ digest.update(chunk)
45
+ return digest.hexdigest()
46
+
47
+
48
+ def parse_checksum_text(text: str, expected_file_name: Optional[str] = None) -> str:
49
+ """Extract a SHA-256 value from a checksum file or raw string."""
50
+
51
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
52
+ if not lines:
53
+ raise ValueError("checksum text did not contain any usable lines")
54
+
55
+ for line in lines:
56
+ parts = line.split()
57
+ if len(parts) == 1 and len(parts[0]) == 64:
58
+ return parts[0].lower()
59
+ if len(parts) >= 2 and len(parts[0]) == 64:
60
+ candidate_name = parts[-1].lstrip("*")
61
+ if expected_file_name is None or candidate_name == expected_file_name:
62
+ return parts[0].lower()
63
+
64
+ raise ValueError("checksum text did not contain a valid SHA-256 entry")
65
+
66
+
67
+ def is_tar_bundle(bundle_path: Path) -> bool:
68
+ """Return true when a bundle path uses a tar-based archive format."""
69
+
70
+ suffixes = [suffix.lower() for suffix in bundle_path.suffixes]
71
+ return suffixes[-2:] == [".tar", ".gz"] or bundle_path.suffix.lower() == ".tgz"
72
+
73
+
74
+ def read_manifest_from_bundle(bundle_path: Path) -> BundleManifest:
75
+ """Read and parse the bundle manifest embedded inside a release archive."""
76
+
77
+ if is_tar_bundle(bundle_path):
78
+ with tarfile.open(bundle_path, "r:*") as archive:
79
+ member = next(
80
+ (
81
+ candidate
82
+ for candidate in archive.getmembers()
83
+ if Path(candidate.name).name == "bundle-manifest.json"
84
+ ),
85
+ None,
86
+ )
87
+ if member is None:
88
+ raise FileNotFoundError("bundle-manifest.json was not found in the bundle archive")
89
+ handle = archive.extractfile(member)
90
+ if handle is None:
91
+ raise FileNotFoundError("bundle-manifest.json could not be extracted")
92
+ payload = json.loads(handle.read().decode("utf-8-sig"))
93
+ else:
94
+ with ZipFile(bundle_path, "r") as archive:
95
+ with archive.open("bundle-manifest.json", "r") as handle:
96
+ payload = json.loads(handle.read().decode("utf-8-sig"))
97
+
98
+ return BundleManifest(
99
+ bundle_name=payload["bundle_name"],
100
+ bundle_version=payload["bundle_version"],
101
+ platform=payload["platform"],
102
+ architecture=payload["architecture"],
103
+ executable=payload["executable"],
104
+ install_script=payload.get("install_script"),
105
+ uninstall_script=payload.get("uninstall_script"),
106
+ legacy_executable=payload.get("legacy_executable"),
107
+ )
108
+
109
+
110
+ def read_manifest_from_zip(bundle_path: Path) -> BundleManifest:
111
+ """Backward-compatible wrapper for zip-based bundle manifest reads."""
112
+
113
+ return read_manifest_from_bundle(bundle_path)
114
+
115
+
116
+ def download_file(url: str, destination: Path) -> Path:
117
+ """Download a file to a destination path, replacing any prior file."""
118
+
119
+ destination.parent.mkdir(parents=True, exist_ok=True)
120
+ request = urllib.request.Request(
121
+ url,
122
+ headers={"User-Agent": f"enchi-bootstrap/{__version__}"},
123
+ )
124
+ with urllib.request.urlopen(request) as response, destination.open("wb") as handle: # noqa: S310
125
+ handle.write(response.read())
126
+ return destination
127
+
128
+
129
+ def load_checksum_text(
130
+ checksum: Optional[str],
131
+ checksum_path: Optional[Path],
132
+ checksum_url: Optional[str],
133
+ cache_path: Path,
134
+ ) -> Optional[str]:
135
+ """Load checksum content from an inline value, local file, or remote URL."""
136
+
137
+ if checksum:
138
+ return checksum.strip()
139
+ if checksum_path:
140
+ return checksum_path.read_text(encoding="utf-8")
141
+ if checksum_url:
142
+ checksum_target = cache_path.with_suffix(cache_path.suffix + ".sha256")
143
+ download_file(checksum_url, checksum_target)
144
+ return checksum_target.read_text(encoding="utf-8")
145
+ return None
146
+
147
+
148
+ def verify_bundle_checksum(
149
+ bundle_path: Path,
150
+ checksum: Optional[str] = None,
151
+ checksum_path: Optional[Path] = None,
152
+ checksum_url: Optional[str] = None,
153
+ ) -> str:
154
+ """Verify the bundle against a supplied checksum source and return the digest."""
155
+
156
+ checksum_text = load_checksum_text(
157
+ checksum=checksum,
158
+ checksum_path=checksum_path,
159
+ checksum_url=checksum_url,
160
+ cache_path=bundle_path,
161
+ )
162
+ actual = sha256_file(bundle_path)
163
+ if checksum_text is None:
164
+ return actual
165
+
166
+ expected = parse_checksum_text(checksum_text, bundle_path.name)
167
+ if actual.lower() != expected.lower():
168
+ raise ValueError(
169
+ f"checksum mismatch for {bundle_path}: expected {expected}, got {actual}"
170
+ )
171
+ return actual
enchi_bootstrap/cli.py ADDED
@@ -0,0 +1,218 @@
1
+ # ./python-package/src/enchi_bootstrap/cli.py
2
+ """Command-line entrypoint for the Enchi Python install package (`enchi-bootstrap`)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ from .bundle import read_manifest_from_bundle, verify_bundle_checksum
11
+ from .installer import InstallRequest, format_command, format_plan_json, run_install, resolve_bundle_path
12
+ from .platforms import current_target
13
+
14
+
15
+ def default_install_shell() -> str:
16
+ """Return the default shell choice for the current platform."""
17
+
18
+ return "pwsh" if current_target().operating_system == "windows" else "bash"
19
+
20
+
21
+ def str_to_bool(value: str) -> bool:
22
+ """Parse common boolean command-line strings."""
23
+
24
+ normalized = value.strip().lower()
25
+ if normalized in {"1", "true", "yes", "on"}:
26
+ return True
27
+ if normalized in {"0", "false", "no", "off"}:
28
+ return False
29
+ raise argparse.ArgumentTypeError(
30
+ f"invalid boolean value {value!r}; use true/false, yes/no, on/off, or 1/0"
31
+ )
32
+
33
+
34
+ def build_parser() -> argparse.ArgumentParser:
35
+ """Create the top-level argument parser."""
36
+
37
+ parser = argparse.ArgumentParser(
38
+ prog="enchi-bootstrap",
39
+ description="Download, verify, and install the native Enchi release bundles.",
40
+ )
41
+ subparsers = parser.add_subparsers(dest="command", required=True)
42
+
43
+ install = subparsers.add_parser("install", help="install a native Enchi release bundle")
44
+ install.add_argument("--bundle-path", type=Path)
45
+ install.add_argument("--bundle-url")
46
+ install.add_argument("--release-base-url")
47
+ install.add_argument("--github-repo")
48
+ install.add_argument("--tag")
49
+ install.add_argument("--checksum")
50
+ install.add_argument("--checksum-path", type=Path)
51
+ install.add_argument("--checksum-url")
52
+ install.add_argument("--install-root", type=Path)
53
+ install.add_argument(
54
+ "--shell",
55
+ choices=["pwsh", "cmd", "bash", "zsh", "fish", "sh", "none"],
56
+ default=default_install_shell(),
57
+ )
58
+ install.add_argument("--add-to-user-path", type=str_to_bool, default=True)
59
+ install.add_argument(
60
+ "--update-shell-profile",
61
+ "--update-powershell-profile",
62
+ dest="update_shell_profile",
63
+ type=str_to_bool,
64
+ default=True,
65
+ )
66
+ install.add_argument("--refresh-shims", type=str_to_bool, default=True)
67
+ install.add_argument("--force", action="store_true")
68
+ install.add_argument("--cache-dir", type=Path)
69
+ install.add_argument("--keep-extracted", action="store_true")
70
+ install.add_argument("--dry-run", action="store_true")
71
+ install.add_argument("--json", action="store_true")
72
+
73
+ download = subparsers.add_parser("download", help="download and optionally verify a release bundle")
74
+ download.add_argument("--bundle-path", type=Path)
75
+ download.add_argument("--bundle-url")
76
+ download.add_argument("--release-base-url")
77
+ download.add_argument("--github-repo")
78
+ download.add_argument("--tag")
79
+ download.add_argument("--checksum")
80
+ download.add_argument("--checksum-path", type=Path)
81
+ download.add_argument("--checksum-url")
82
+ download.add_argument("--cache-dir", type=Path)
83
+ download.add_argument("--json", action="store_true")
84
+
85
+ verify = subparsers.add_parser("verify", help="verify a local release bundle")
86
+ verify.add_argument("bundle_path", type=Path)
87
+ verify.add_argument("--checksum")
88
+ verify.add_argument("--checksum-path", type=Path)
89
+ verify.add_argument("--checksum-url")
90
+ verify.add_argument("--json", action="store_true")
91
+
92
+ return parser
93
+
94
+
95
+ def request_from_args(args: argparse.Namespace) -> InstallRequest:
96
+ """Convert argparse output into an install request."""
97
+
98
+ return InstallRequest(
99
+ bundle_path=args.bundle_path,
100
+ bundle_url=getattr(args, "bundle_url", None),
101
+ release_base_url=getattr(args, "release_base_url", None),
102
+ github_repo=getattr(args, "github_repo", None),
103
+ tag=getattr(args, "tag", None),
104
+ checksum=getattr(args, "checksum", None),
105
+ checksum_path=getattr(args, "checksum_path", None),
106
+ checksum_url=getattr(args, "checksum_url", None),
107
+ install_root=getattr(args, "install_root", None),
108
+ shell=getattr(args, "shell", default_install_shell()),
109
+ add_to_user_path=getattr(args, "add_to_user_path", True),
110
+ update_powershell_profile=getattr(args, "update_shell_profile", True),
111
+ refresh_shims=getattr(args, "refresh_shims", True),
112
+ force=getattr(args, "force", False),
113
+ cache_dir=getattr(args, "cache_dir", None),
114
+ keep_extracted=getattr(args, "keep_extracted", False),
115
+ dry_run=getattr(args, "dry_run", False),
116
+ )
117
+
118
+
119
+ def cmd_install(args: argparse.Namespace) -> int:
120
+ """Handle the install subcommand."""
121
+
122
+ plan = run_install(request_from_args(args))
123
+ if args.json:
124
+ print(format_plan_json(plan))
125
+ return 0
126
+
127
+ print(f"Bundle: {plan.bundle_path}")
128
+ print(f"Source: {plan.bundle_source}")
129
+ print(f"Version: {plan.bundle_manifest.bundle_version}")
130
+ print(f"Target: {plan.bundle_manifest.platform}/{plan.bundle_manifest.architecture}")
131
+ print(f"Checksum: {plan.checksum_sha256}")
132
+ print(f"Installer: {format_command(plan.install_command)}")
133
+ if args.dry_run:
134
+ print("Mode: dry-run")
135
+ else:
136
+ print("Status: installed")
137
+ return 0
138
+
139
+
140
+ def cmd_download(args: argparse.Namespace) -> int:
141
+ """Handle the download subcommand."""
142
+
143
+ request = request_from_args(args)
144
+ bundle_path, resolved_checksum_url, bundle_source = resolve_bundle_path(request, current_target())
145
+ digest = verify_bundle_checksum(
146
+ bundle_path,
147
+ checksum=request.checksum,
148
+ checksum_path=request.checksum_path,
149
+ checksum_url=resolved_checksum_url,
150
+ )
151
+ manifest = read_manifest_from_bundle(bundle_path)
152
+ payload = {
153
+ "bundle_path": str(bundle_path),
154
+ "bundle_source": bundle_source,
155
+ "checksum_sha256": digest,
156
+ "bundle_manifest": {
157
+ "bundle_name": manifest.bundle_name,
158
+ "bundle_version": manifest.bundle_version,
159
+ "platform": manifest.platform,
160
+ "architecture": manifest.architecture,
161
+ },
162
+ }
163
+ if args.json:
164
+ print(json.dumps(payload, indent=2))
165
+ else:
166
+ print(f"Bundle: {payload['bundle_path']}")
167
+ print(f"Source: {payload['bundle_source']}")
168
+ print(f"Checksum: {payload['checksum_sha256']}")
169
+ print(f"Version: {manifest.bundle_version}")
170
+ return 0
171
+
172
+
173
+ def cmd_verify(args: argparse.Namespace) -> int:
174
+ """Handle the verify subcommand."""
175
+
176
+ digest = verify_bundle_checksum(
177
+ args.bundle_path,
178
+ checksum=args.checksum,
179
+ checksum_path=args.checksum_path,
180
+ checksum_url=args.checksum_url,
181
+ )
182
+ manifest = read_manifest_from_bundle(args.bundle_path)
183
+ payload = {
184
+ "bundle_path": str(args.bundle_path),
185
+ "checksum_sha256": digest,
186
+ "bundle_manifest": {
187
+ "bundle_name": manifest.bundle_name,
188
+ "bundle_version": manifest.bundle_version,
189
+ "platform": manifest.platform,
190
+ "architecture": manifest.architecture,
191
+ },
192
+ }
193
+ if args.json:
194
+ print(json.dumps(payload, indent=2))
195
+ else:
196
+ print(f"Bundle: {payload['bundle_path']}")
197
+ print(f"Checksum: {payload['checksum_sha256']}")
198
+ print(f"Manifest: {manifest.bundle_name} {manifest.bundle_version}")
199
+ return 0
200
+
201
+
202
+ def main() -> int:
203
+ """Program entrypoint."""
204
+
205
+ parser = build_parser()
206
+ args = parser.parse_args()
207
+ if args.command == "install":
208
+ return cmd_install(args)
209
+ if args.command == "download":
210
+ return cmd_download(args)
211
+ if args.command == "verify":
212
+ return cmd_verify(args)
213
+ parser.error(f"unknown command {args.command!r}")
214
+ return 2
215
+
216
+
217
+ if __name__ == "__main__":
218
+ raise SystemExit(main())
@@ -0,0 +1,109 @@
1
+ # ./python-package/src/enchi_bootstrap/github.py
2
+ """GitHub release discovery helpers for locating Enchi bundle assets."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import urllib.request
8
+ from dataclasses import dataclass
9
+ from typing import Callable, Optional
10
+
11
+ from . import __version__
12
+
13
+ # The repository that publishes releases. It keeps its pre-rename name until it is renamed on
14
+ # GitHub (old URLs redirect); change it here when that happens.
15
+ DEFAULT_GITHUB_REPO = "imyourboyroy/pyenv-native"
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class GitHubReleaseAsset:
20
+ """A single downloadable asset from a GitHub release payload."""
21
+
22
+ name: str
23
+ browser_download_url: str
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class GitHubRelease:
28
+ """Normalized release metadata used by the bootstrap installer."""
29
+
30
+ tag_name: str
31
+ assets: tuple[GitHubReleaseAsset, ...]
32
+
33
+
34
+ def github_release_api_url(repo: str, tag: Optional[str] = None) -> str:
35
+ """Return the GitHub API URL for the latest or a tagged release."""
36
+
37
+ cleaned_repo = repo.strip().strip("/")
38
+ if not cleaned_repo or "/" not in cleaned_repo:
39
+ raise ValueError("github repo must be in the form owner/name")
40
+
41
+ if tag:
42
+ return f"https://api.github.com/repos/{cleaned_repo}/releases/tags/{tag}"
43
+ return f"https://api.github.com/repos/{cleaned_repo}/releases/latest"
44
+
45
+
46
+ def fetch_release_payload(url: str) -> dict[str, object]:
47
+ """Fetch a GitHub release payload from the API."""
48
+
49
+ request = urllib.request.Request(
50
+ url,
51
+ headers={
52
+ "Accept": "application/vnd.github+json",
53
+ "User-Agent": f"enchi-bootstrap/{__version__}",
54
+ },
55
+ )
56
+ with urllib.request.urlopen(request) as response: # noqa: S310
57
+ return json.loads(response.read().decode("utf-8"))
58
+
59
+
60
+ def parse_release_payload(payload: dict[str, object]) -> GitHubRelease:
61
+ """Normalize a GitHub release payload into the local dataclass shape."""
62
+
63
+ tag_name = str(payload["tag_name"])
64
+ assets_payload = payload.get("assets", [])
65
+ assets = tuple(
66
+ GitHubReleaseAsset(
67
+ name=str(asset["name"]),
68
+ browser_download_url=str(asset["browser_download_url"]),
69
+ )
70
+ for asset in assets_payload
71
+ if isinstance(asset, dict)
72
+ and "name" in asset
73
+ and "browser_download_url" in asset
74
+ )
75
+ return GitHubRelease(tag_name=tag_name, assets=assets)
76
+
77
+
78
+ def resolve_release_asset_urls(
79
+ repo: str,
80
+ bundle_file_name: str,
81
+ tag: Optional[str] = None,
82
+ fetcher: Optional[Callable[[str], dict[str, object]]] = None,
83
+ ) -> tuple[str, str, str]:
84
+ """Resolve bundle and checksum URLs from a GitHub release."""
85
+
86
+ url = github_release_api_url(repo, tag)
87
+ payload = (fetcher or fetch_release_payload)(url)
88
+ release = parse_release_payload(payload)
89
+
90
+ bundle_asset = next(
91
+ (asset for asset in release.assets if asset.name == bundle_file_name),
92
+ None,
93
+ )
94
+ if bundle_asset is None:
95
+ raise ValueError(
96
+ f"release {repo}@{release.tag_name} did not contain asset {bundle_file_name!r}"
97
+ )
98
+
99
+ checksum_name = f"{bundle_file_name}.sha256"
100
+ checksum_asset = next(
101
+ (asset for asset in release.assets if asset.name == checksum_name),
102
+ None,
103
+ )
104
+ if checksum_asset is None:
105
+ raise ValueError(
106
+ f"release {repo}@{release.tag_name} did not contain asset {checksum_name!r}"
107
+ )
108
+
109
+ return bundle_asset.browser_download_url, checksum_asset.browser_download_url, release.tag_name
@@ -0,0 +1,353 @@
1
+ # ./python-package/src/enchi_bootstrap/installer.py
2
+ """Bundle resolution, extraction, and installer execution for the Enchi Python install package."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import shutil
9
+ import stat
10
+ import subprocess
11
+ import tarfile
12
+ import tempfile
13
+ from dataclasses import asdict, dataclass
14
+ from pathlib import Path
15
+ from typing import Optional, Sequence
16
+ from zipfile import ZipFile
17
+
18
+ from .bundle import (
19
+ BundleManifest,
20
+ download_file,
21
+ is_tar_bundle,
22
+ read_manifest_from_bundle,
23
+ verify_bundle_checksum,
24
+ )
25
+ from .github import DEFAULT_GITHUB_REPO, resolve_release_asset_urls
26
+ from .platforms import PlatformTarget, current_target
27
+
28
+
29
+ def env_setting(name: str) -> Optional[str]:
30
+ """Read `ENCHI_BOOTSTRAP_<name>`, falling back to the pre-rename `PYENV_NATIVE_BOOTSTRAP_<name>`."""
31
+
32
+ return os.environ.get(f"ENCHI_BOOTSTRAP_{name}") or os.environ.get(
33
+ f"PYENV_NATIVE_BOOTSTRAP_{name}"
34
+ )
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class InstallRequest:
39
+ """Parameters accepted by the Python install package flow."""
40
+
41
+ bundle_path: Optional[Path] = None
42
+ bundle_url: Optional[str] = None
43
+ release_base_url: Optional[str] = None
44
+ github_repo: Optional[str] = None
45
+ tag: Optional[str] = None
46
+ checksum: Optional[str] = None
47
+ checksum_path: Optional[Path] = None
48
+ checksum_url: Optional[str] = None
49
+ install_root: Optional[Path] = None
50
+ shell: str = "pwsh"
51
+ add_to_user_path: bool = True
52
+ update_powershell_profile: bool = True
53
+ refresh_shims: bool = True
54
+ force: bool = False
55
+ cache_dir: Optional[Path] = None
56
+ keep_extracted: bool = False
57
+ dry_run: bool = False
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class InstallPlan:
62
+ """Resolved bundle, manifest, and command for an install operation."""
63
+
64
+ bundle_path: Path
65
+ bundle_source: str
66
+ bundle_manifest: BundleManifest
67
+ checksum_sha256: str
68
+ extracted_dir: Path
69
+ install_command: list[str]
70
+
71
+ def to_dict(self) -> dict[str, object]:
72
+ """Return a JSON-friendly representation."""
73
+
74
+ return {
75
+ "bundle_path": str(self.bundle_path),
76
+ "bundle_source": self.bundle_source,
77
+ "bundle_manifest": asdict(self.bundle_manifest),
78
+ "checksum_sha256": self.checksum_sha256,
79
+ "extracted_dir": str(self.extracted_dir),
80
+ "install_command": self.install_command,
81
+ }
82
+
83
+
84
+ def default_cache_dir() -> Path:
85
+ """Return the default Enchi package cache location."""
86
+
87
+ if os.name == "nt":
88
+ local_app_data = os.environ.get("LOCALAPPDATA")
89
+ if local_app_data:
90
+ return Path(local_app_data) / "enchi" / "cache"
91
+ return Path.home() / ".cache" / "enchi"
92
+
93
+
94
+ def resolve_release_urls(
95
+ target: PlatformTarget,
96
+ release_base_url: str,
97
+ ) -> tuple[str, str]:
98
+ """Resolve the bundle and checksum URLs from a release base URL."""
99
+
100
+ base = release_base_url.rstrip("/")
101
+ asset_name = target.bundle_file_name
102
+ bundle_url = f"{base}/{asset_name}"
103
+ checksum_url = f"{bundle_url}.sha256"
104
+ return bundle_url, checksum_url
105
+
106
+
107
+ def resolve_bundle_path(
108
+ request: InstallRequest,
109
+ target: Optional[PlatformTarget] = None,
110
+ ) -> tuple[Path, Optional[str], str]:
111
+ """Resolve the bundle to a local file, downloading it if needed."""
112
+
113
+ active_target = target or current_target()
114
+ if request.bundle_path:
115
+ return (
116
+ request.bundle_path.expanduser().resolve(),
117
+ request.checksum_url,
118
+ "local bundle path",
119
+ )
120
+
121
+ cache_dir = (request.cache_dir or default_cache_dir()).expanduser().resolve()
122
+ bundle_url = request.bundle_url
123
+ checksum_url = request.checksum_url
124
+ release_base_url = request.release_base_url or env_setting("RELEASE_BASE_URL")
125
+ github_repo = request.github_repo or env_setting("GITHUB_REPO")
126
+ bundle_source = "explicit bundle url" if bundle_url else "unknown"
127
+ bundle_file_name: Optional[str] = None
128
+ if not bundle_url and release_base_url:
129
+ bundle_url, checksum_url = resolve_release_urls(active_target, release_base_url)
130
+ bundle_source = f"release base url {release_base_url}"
131
+ elif not bundle_url and github_repo:
132
+ bundle_file_name = active_target.bundle_file_name
133
+ try:
134
+ bundle_url, checksum_url, resolved_tag = resolve_release_asset_urls(
135
+ github_repo,
136
+ bundle_file_name,
137
+ request.tag,
138
+ )
139
+ except ValueError:
140
+ # Releases cut before the rename only publish the pyenv-native-named bundle.
141
+ bundle_file_name = active_target.legacy_bundle_file_name
142
+ bundle_url, checksum_url, resolved_tag = resolve_release_asset_urls(
143
+ github_repo,
144
+ bundle_file_name,
145
+ request.tag,
146
+ )
147
+ requested_tag = request.tag or resolved_tag
148
+ bundle_source = f"github release {github_repo}@{requested_tag}"
149
+
150
+ if bundle_url:
151
+ bundle_path = cache_dir / (bundle_file_name or active_target.bundle_file_name)
152
+ download_file(bundle_url, bundle_path)
153
+ return bundle_path, checksum_url, bundle_source
154
+
155
+ local_dev_bundle = Path.cwd() / "dist" / active_target.bundle_file_name
156
+ if local_dev_bundle.is_file():
157
+ return local_dev_bundle.resolve(), checksum_url, "local dev dist bundle"
158
+
159
+ raise ValueError(
160
+ "unable to resolve an Enchi bundle; pass --bundle-path, --bundle-url, --release-base-url, "
161
+ f"or --github-repo (the project repository is {DEFAULT_GITHUB_REPO})"
162
+ )
163
+
164
+
165
+ def extract_bundle(bundle_path: Path, target_dir: Path) -> Path:
166
+ """Extract a release bundle into a target directory."""
167
+
168
+ target_dir.mkdir(parents=True, exist_ok=True)
169
+ if is_tar_bundle(bundle_path):
170
+ with tarfile.open(bundle_path, "r:*") as archive:
171
+ try:
172
+ archive.extractall(target_dir, filter="data")
173
+ except TypeError:
174
+ archive.extractall(target_dir)
175
+ else:
176
+ with ZipFile(bundle_path, "r") as archive:
177
+ archive.extractall(target_dir)
178
+ return target_dir
179
+
180
+
181
+ def powershell_executable() -> str:
182
+ """Return the PowerShell executable used to run the bundled installer."""
183
+
184
+ return env_setting("POWERSHELL") or "powershell"
185
+
186
+
187
+ def shell_executable() -> str:
188
+ """Return the shell executable used for POSIX install scripts."""
189
+
190
+ return env_setting("SHELL") or "sh"
191
+
192
+
193
+ def build_windows_install_command(
194
+ extracted_dir: Path,
195
+ request: InstallRequest,
196
+ manifest: BundleManifest,
197
+ ) -> list[str]:
198
+ """Build the PowerShell command used to invoke a legacy bundle's installer script."""
199
+
200
+ install_script = extracted_dir / manifest.install_script
201
+ executable = extracted_dir / manifest.executable
202
+ command = [
203
+ powershell_executable(),
204
+ "-ExecutionPolicy",
205
+ "Bypass",
206
+ "-File",
207
+ str(install_script),
208
+ "-SourcePath",
209
+ str(executable),
210
+ "-Shell",
211
+ request.shell,
212
+ "-AddToUserPath",
213
+ str(request.add_to_user_path).lower(),
214
+ "-UpdatePowerShellProfile",
215
+ str(request.update_powershell_profile).lower(),
216
+ "-RefreshShims",
217
+ str(request.refresh_shims).lower(),
218
+ ]
219
+ if request.install_root:
220
+ command.extend(["-InstallRoot", str(request.install_root.expanduser().resolve())])
221
+ if request.force:
222
+ command.append("-Force")
223
+ return command
224
+
225
+
226
+ def build_posix_install_command(
227
+ extracted_dir: Path,
228
+ request: InstallRequest,
229
+ manifest: BundleManifest,
230
+ ) -> list[str]:
231
+ """Build the shell command used to invoke a legacy bundle's POSIX installer script."""
232
+
233
+ install_script = extracted_dir / manifest.install_script
234
+ executable = extracted_dir / manifest.executable
235
+ install_script.chmod(install_script.stat().st_mode | stat.S_IXUSR)
236
+ executable.chmod(executable.stat().st_mode | stat.S_IXUSR)
237
+ command = [
238
+ shell_executable(),
239
+ str(install_script),
240
+ "--source-path",
241
+ str(executable),
242
+ "--shell",
243
+ request.shell,
244
+ "--add-to-user-path",
245
+ str(request.add_to_user_path).lower(),
246
+ "--update-shell-profile",
247
+ str(request.update_powershell_profile).lower(),
248
+ "--refresh-shims",
249
+ str(request.refresh_shims).lower(),
250
+ ]
251
+ if request.install_root:
252
+ command.extend(["--install-root", str(request.install_root.expanduser().resolve())])
253
+ if request.force:
254
+ command.append("--force")
255
+ return command
256
+
257
+
258
+ def build_self_install_command(
259
+ extracted_dir: Path,
260
+ request: InstallRequest,
261
+ manifest: BundleManifest,
262
+ ) -> list[str]:
263
+ """Build the `enchi self-install` command for a bundle that installs through its binary."""
264
+
265
+ executable = extracted_dir / manifest.executable
266
+ if os.name != "nt":
267
+ executable.chmod(executable.stat().st_mode | stat.S_IXUSR)
268
+ command = [
269
+ str(executable),
270
+ "self-install",
271
+ "--source-dir",
272
+ str(extracted_dir),
273
+ "--shell",
274
+ request.shell,
275
+ "--add-to-user-path",
276
+ str(request.add_to_user_path).lower(),
277
+ "--update-shell-profile",
278
+ str(request.update_powershell_profile).lower(),
279
+ "--refresh-shims",
280
+ str(request.refresh_shims).lower(),
281
+ ]
282
+ if request.install_root:
283
+ command.extend(["--install-root", str(request.install_root.expanduser().resolve())])
284
+ if request.force:
285
+ command.append("--force")
286
+ return command
287
+
288
+
289
+ def plan_install(request: InstallRequest) -> InstallPlan:
290
+ """Resolve, verify, and prepare a bundle install plan."""
291
+
292
+ bundle_path, resolved_checksum_url, bundle_source = resolve_bundle_path(request)
293
+ checksum_sha256 = verify_bundle_checksum(
294
+ bundle_path,
295
+ checksum=request.checksum,
296
+ checksum_path=request.checksum_path,
297
+ checksum_url=resolved_checksum_url,
298
+ )
299
+ manifest = read_manifest_from_bundle(bundle_path)
300
+ cache_root = (request.cache_dir or default_cache_dir()).expanduser().resolve()
301
+ cache_root.mkdir(parents=True, exist_ok=True)
302
+ extracted_dir = Path(
303
+ tempfile.mkdtemp(prefix=f"{manifest.bundle_name}-", dir=str(cache_root))
304
+ ).resolve()
305
+ extract_bundle(bundle_path, extracted_dir)
306
+ host_target = current_target()
307
+ if manifest.platform != host_target.operating_system:
308
+ raise RuntimeError(
309
+ f"bundle platform {manifest.platform!r} does not match the current host platform {host_target.operating_system!r}"
310
+ )
311
+
312
+ if manifest.install_script is None:
313
+ install_command = build_self_install_command(extracted_dir, request, manifest)
314
+ elif manifest.platform == "windows":
315
+ install_command = build_windows_install_command(extracted_dir, request, manifest)
316
+ elif manifest.platform in {"linux", "macos", "android"}:
317
+ install_command = build_posix_install_command(extracted_dir, request, manifest)
318
+ else:
319
+ raise RuntimeError(f"unsupported bundle platform {manifest.platform!r}")
320
+
321
+ return InstallPlan(
322
+ bundle_path=bundle_path,
323
+ bundle_source=bundle_source,
324
+ bundle_manifest=manifest,
325
+ checksum_sha256=checksum_sha256,
326
+ extracted_dir=extracted_dir,
327
+ install_command=install_command,
328
+ )
329
+
330
+
331
+ def run_install(request: InstallRequest) -> InstallPlan:
332
+ """Execute the bootstrap install flow and return the resolved plan."""
333
+
334
+ plan = plan_install(request)
335
+ if request.dry_run:
336
+ return plan
337
+
338
+ subprocess.run(plan.install_command, check=True)
339
+ if not request.keep_extracted:
340
+ shutil.rmtree(plan.extracted_dir, ignore_errors=True)
341
+ return plan
342
+
343
+
344
+ def format_plan_json(plan: InstallPlan) -> str:
345
+ """Serialize an install plan to indented JSON."""
346
+
347
+ return json.dumps(plan.to_dict(), indent=2)
348
+
349
+
350
+ def format_command(command: Sequence[str]) -> str:
351
+ """Render a subprocess command in a readable shell form."""
352
+
353
+ return subprocess.list2cmdline(list(command))
@@ -0,0 +1,80 @@
1
+ # ./python-package/src/enchi_bootstrap/platforms.py
2
+ """Platform helpers for selecting and naming Enchi release bundles."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import platform
7
+ import sys
8
+ import os
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class PlatformTarget:
14
+ """Normalized OS and architecture labels used by release bundle naming."""
15
+
16
+ operating_system: str
17
+ architecture: str
18
+
19
+ @property
20
+ def bundle_stem(self) -> str:
21
+ return f"enchi-{self.operating_system}-{self.architecture}"
22
+
23
+ @property
24
+ def legacy_bundle_stem(self) -> str:
25
+ """The name releases published before the rename (pyenv-native) used for the same bundle."""
26
+
27
+ return f"pyenv-native-{self.operating_system}-{self.architecture}"
28
+
29
+ @property
30
+ def bundle_extension(self) -> str:
31
+ return ".zip" if self.operating_system == "windows" else ".tar.gz"
32
+
33
+ @property
34
+ def bundle_file_name(self) -> str:
35
+ return f"{self.bundle_stem}{self.bundle_extension}"
36
+
37
+ @property
38
+ def legacy_bundle_file_name(self) -> str:
39
+ return f"{self.legacy_bundle_stem}{self.bundle_extension}"
40
+
41
+
42
+ def normalize_operating_system(value: str | None = None) -> str:
43
+ """Return a stable operating-system label for release asset naming."""
44
+
45
+ if os.environ.get("TERMUX_VERSION"):
46
+ return "android"
47
+ prefix = os.environ.get("PREFIX", "").lower()
48
+ if "com.termux" in prefix:
49
+ return "android"
50
+
51
+ candidate = (value or sys.platform).strip().lower()
52
+ if candidate.startswith("win"):
53
+ return "windows"
54
+ if candidate.startswith("linux"):
55
+ return "linux"
56
+ if candidate in {"darwin", "macos", "mac", "osx"}:
57
+ return "macos"
58
+ return candidate
59
+
60
+
61
+ def normalize_architecture(value: str | None = None) -> str:
62
+ """Return a stable CPU architecture label for release asset naming."""
63
+
64
+ candidate = (value or platform.machine()).strip().lower()
65
+ if candidate in {"amd64", "x86_64", "x64"}:
66
+ return "x64"
67
+ if candidate in {"arm64", "aarch64"}:
68
+ return "arm64"
69
+ if candidate in {"x86", "i386", "i686"}:
70
+ return "x86"
71
+ return candidate
72
+
73
+
74
+ def current_target() -> PlatformTarget:
75
+ """Return the normalized target for the current Python process."""
76
+
77
+ return PlatformTarget(
78
+ operating_system=normalize_operating_system(),
79
+ architecture=normalize_architecture(),
80
+ )