estrellio-py-env-tools 0.1.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.
- estrellio_py_env_tools-0.1.0.dist-info/METADATA +166 -0
- estrellio_py_env_tools-0.1.0.dist-info/RECORD +9 -0
- estrellio_py_env_tools-0.1.0.dist-info/WHEEL +5 -0
- estrellio_py_env_tools-0.1.0.dist-info/entry_points.txt +2 -0
- estrellio_py_env_tools-0.1.0.dist-info/licenses/LICENSE +21 -0
- estrellio_py_env_tools-0.1.0.dist-info/top_level.txt +1 -0
- py_env_tools/__init__.py +6 -0
- py_env_tools/cli.py +158 -0
- py_env_tools/core.py +692 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: estrellio-py-env-tools
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Configuration-driven Python environment helpers for AutoScripts-style repos
|
|
5
|
+
Author: shade
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/jiangnanqw12/py_env_tools
|
|
8
|
+
Project-URL: Repository, https://github.com/jiangnanqw12/py_env_tools
|
|
9
|
+
Project-URL: Issues, https://github.com/jiangnanqw12/py_env_tools/issues
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Provides-Extra: test
|
|
14
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# py_env_tools
|
|
18
|
+
|
|
19
|
+
Python API and CLI for configuration-driven environment resolution and setup.
|
|
20
|
+
Requires Python 3.10+ with no third-party runtime dependencies.
|
|
21
|
+
|
|
22
|
+
## Python package (release preparation)
|
|
23
|
+
|
|
24
|
+
Version `0.1.0` is being prepared; this change does not publish it to PyPI.
|
|
25
|
+
For local installation from this repository root:
|
|
26
|
+
|
|
27
|
+
```console
|
|
28
|
+
python -m pip install .
|
|
29
|
+
py-env-tool --help
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
After the first release is published, install with
|
|
33
|
+
`python -m pip install estrellio-py-env-tools==0.1.0`.
|
|
34
|
+
|
|
35
|
+
The installed `py-env-tool` command supports `resolve-env`, `describe-config`,
|
|
36
|
+
`resolve-python`, `create-venv`, and `install-pipx`. Pass `--config` and
|
|
37
|
+
`--project-dir` explicitly; pip installation does not create project config.
|
|
38
|
+
For example, with an existing configuration:
|
|
39
|
+
|
|
40
|
+
```console
|
|
41
|
+
py-env-tool resolve-env --config config/py_env.json --project-dir . --format json
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python integrations can use `PyEnvError`, `resolve_env_data`, and
|
|
45
|
+
`resolve_python_runtime` from `py_env_tools`, and the existing configuration
|
|
46
|
+
and setup helpers from `py_env_tools.core`. Configuration precedence remains
|
|
47
|
+
shared config, current-platform overrides, then the sibling local config.
|
|
48
|
+
|
|
49
|
+
## Repository scripts and templates
|
|
50
|
+
|
|
51
|
+
The wheel does **not** install the Bash/PowerShell launchers, minimal templates,
|
|
52
|
+
or installer scripts. `write-env`, `run-module`, bootstrap Python discovery,
|
|
53
|
+
and template installation still require the source/submodule layout. The
|
|
54
|
+
Python CLI has its existing output contract, including `AUTOSCRIPTS_*` JSON
|
|
55
|
+
keys; it is not a replacement for the shell wrappers' generic output contract.
|
|
56
|
+
|
|
57
|
+
Repository entrypoints remain `scripts/py_env.sh`, `scripts/py_env.ps1`, and
|
|
58
|
+
`scripts/install_minimal_repo.sh` / `.ps1`. They use the host repository's
|
|
59
|
+
`config/py_env.json` by default; wrappers can override `PY_ENV_CONFIG_PATH`.
|
|
60
|
+
`scripts/py_env_tool.py` is a source launcher for `py_env_tools.cli`, allowing
|
|
61
|
+
repository scripts to work before the package is installed.
|
|
62
|
+
|
|
63
|
+
See [Usage](docs/usage.md), [Testing](docs/testing.md), and
|
|
64
|
+
[Publishing](docs/publishing.md) for the supported interfaces and release checks.
|
|
65
|
+
|
|
66
|
+
## Common Submodule Operations
|
|
67
|
+
|
|
68
|
+
When this repository is used under a parent repo as `libs/py_env_tools`, Git
|
|
69
|
+
tracks two different states:
|
|
70
|
+
|
|
71
|
+
- the commit pinned by the parent repository
|
|
72
|
+
- the latest commit on this repository's own remote branch
|
|
73
|
+
|
|
74
|
+
Common commands from the parent repository root:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
# Inspect the submodule state recorded by the parent repo
|
|
78
|
+
git submodule status
|
|
79
|
+
git diff --submodule=log -- libs/py_env_tools
|
|
80
|
+
|
|
81
|
+
# Reset the submodule to the commit currently pinned by the parent repo
|
|
82
|
+
git submodule update --init --recursive
|
|
83
|
+
|
|
84
|
+
# Move the submodule itself to the latest origin/main commit
|
|
85
|
+
git -C libs/py_env_tools checkout main
|
|
86
|
+
git -C libs/py_env_tools pull --ff-only
|
|
87
|
+
|
|
88
|
+
# Record the updated submodule pointer in the parent repo
|
|
89
|
+
git add libs/py_env_tools
|
|
90
|
+
git commit -m "Update py_env_tools submodule"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`git submodule update --init --recursive` does not mean "pull the latest remote
|
|
94
|
+
changes for this submodule". It checks out the commit currently recorded by the
|
|
95
|
+
parent repository and commonly leaves the submodule in a detached `HEAD` state.
|
|
96
|
+
|
|
97
|
+
## Minimal Repo Template
|
|
98
|
+
|
|
99
|
+
If a new repository only needs Python environment management, it does not need
|
|
100
|
+
the full AutoScripts wrapper layout. A minimal cross-platform setup is available in:
|
|
101
|
+
|
|
102
|
+
- `templates/minimal_repo/py_env.sh`
|
|
103
|
+
- `templates/minimal_repo/py_env.ps1`
|
|
104
|
+
- `templates/minimal_repo/config/py_env.json`
|
|
105
|
+
- `templates/minimal_repo/config/requirements/default.txt`
|
|
106
|
+
|
|
107
|
+
Copy `py_env.sh` and/or `py_env.ps1` to the new repository root, copy
|
|
108
|
+
`config/py_env.json` into a `config/` directory, and vendor or initialize
|
|
109
|
+
`libs/py_env_tools/` in the new repository. The template entrypoints expose:
|
|
110
|
+
|
|
111
|
+
- `resolve-env`
|
|
112
|
+
- `write-env`
|
|
113
|
+
- `install-pipx`
|
|
114
|
+
- `create-venv`
|
|
115
|
+
|
|
116
|
+
The template keeps the existing `py_env.json` schema but maps environment
|
|
117
|
+
outputs to generic names such as `PY_ENV_PROJECT_DIR` and `PY_ENV_VENV_ROOT`.
|
|
118
|
+
`resolve-env` still reports those values, but `write-env` only persists
|
|
119
|
+
cross-repository-safe state such as `PY_BASE`, `PY_ENV_BOOTSTRAP_PYTHON`, and
|
|
120
|
+
PATH updates for the pipx shim directory.
|
|
121
|
+
|
|
122
|
+
`py_env.json` now also supports an optional top-level `platforms` mapping with
|
|
123
|
+
`windows`, `linux`, and `macos` branches. The effective config is resolved in
|
|
124
|
+
this order:
|
|
125
|
+
|
|
126
|
+
1. Shared config
|
|
127
|
+
2. `platforms.<current-platform>`
|
|
128
|
+
3. `py_env_local.json`
|
|
129
|
+
|
|
130
|
+
Use the shared config for machine-independent defaults, platform branches for
|
|
131
|
+
OS-specific paths such as `pythonBase`, `venvRoot`, and `pipxShimPath`, and
|
|
132
|
+
`py_env_local.json` for one-off machine overrides.
|
|
133
|
+
|
|
134
|
+
If the host repository keeps its public entrypoints under `scripts/`, use the
|
|
135
|
+
helper installer instead of copying files manually:
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
bash libs/py_env_tools/scripts/install_minimal_repo.sh --repo-root . --force
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```powershell
|
|
142
|
+
.\libs\py_env_tools\scripts\install_minimal_repo.ps1 -RepoRoot . -Force
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
That command adapts the minimal template for the `scripts/` layout and writes:
|
|
146
|
+
|
|
147
|
+
- `scripts/py_env.sh`
|
|
148
|
+
- `scripts/py_env.ps1`
|
|
149
|
+
- `scripts/config/py_env.json`
|
|
150
|
+
- `scripts/config/requirements/default.txt`
|
|
151
|
+
|
|
152
|
+
It is intended for repositories that only need the minimal environment
|
|
153
|
+
management surface. If your host repo also needs `run-module` wrappers, keep a
|
|
154
|
+
repository-specific `py_env` entry layer instead of overwriting it with the
|
|
155
|
+
minimal template.
|
|
156
|
+
|
|
157
|
+
## Tests
|
|
158
|
+
|
|
159
|
+
The submodule keeps its own pytest suite under `tests/` so it can be validated
|
|
160
|
+
without relying on the parent repository test tree.
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
python -m pytest -q tests
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
For target-platform and portable interpreter paths, see [runtime resolution for standalone runners](docs/usage.md#runtime-resolution-for-standalone-runners).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
estrellio_py_env_tools-0.1.0.dist-info/licenses/LICENSE,sha256=yAt48nv6oAYMWjETk8lC71NkGtpIBX7Op_svNv43RDQ,1062
|
|
2
|
+
py_env_tools/__init__.py,sha256=ikzd1Pl1uRmcHFMWR8j0pOCqU4PLOZh0M288lPyuqWo,197
|
|
3
|
+
py_env_tools/cli.py,sha256=Aqyl7_KiCRnVqlzfb3Zsr20CfsZTAXMhfd4bEL-rwGw,5041
|
|
4
|
+
py_env_tools/core.py,sha256=p7Pex2Tp9oI4spEUUco8Kz3d4k4SUDYahwYlhDt3AO0,24743
|
|
5
|
+
estrellio_py_env_tools-0.1.0.dist-info/METADATA,sha256=4iqqXsKIlTecoA0cJcxBf_Lw6j98qNHmQv6cVjcALEY,6278
|
|
6
|
+
estrellio_py_env_tools-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
estrellio_py_env_tools-0.1.0.dist-info/entry_points.txt,sha256=FLZvgkB3yCbR4IJVpoNlpz6iLJ6A3iyJ0vAUgaFpGJI,54
|
|
8
|
+
estrellio_py_env_tools-0.1.0.dist-info/top_level.txt,sha256=9QGtBjYk12IMWFoH4k5ugsAni_rCIXi6azeHuV3rnWQ,13
|
|
9
|
+
estrellio_py_env_tools-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 shade
|
|
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 @@
|
|
|
1
|
+
py_env_tools
|
py_env_tools/__init__.py
ADDED
py_env_tools/cli.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import shlex
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .core import PyEnvError, create_venvs, describe_config, install_pipx, resolve_env_data, resolve_python_runtime
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def emit_mapping(data: dict[str, str], fmt: str) -> None:
|
|
12
|
+
if fmt == "json":
|
|
13
|
+
print(json.dumps(data, ensure_ascii=False))
|
|
14
|
+
return
|
|
15
|
+
|
|
16
|
+
if fmt == "bash":
|
|
17
|
+
for key, value in data.items():
|
|
18
|
+
print(f"{key}={shlex.quote(value or '')}")
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
if fmt == "powershell":
|
|
22
|
+
for key, value in data.items():
|
|
23
|
+
escaped = (value or "").replace("'", "''")
|
|
24
|
+
print(f"$env:{key} = '{escaped}'")
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
raise PyEnvError(f"Unsupported format: {fmt}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
31
|
+
parser = argparse.ArgumentParser(prog="py_env_tool")
|
|
32
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
33
|
+
|
|
34
|
+
common_parser = argparse.ArgumentParser(add_help=False)
|
|
35
|
+
common_parser.add_argument("--config", required=True)
|
|
36
|
+
common_parser.add_argument("--project-dir", required=True)
|
|
37
|
+
|
|
38
|
+
resolve_env_parser = subparsers.add_parser("resolve-env", parents=[common_parser])
|
|
39
|
+
resolve_env_parser.add_argument("--format", choices=("json", "bash", "powershell"), default="json")
|
|
40
|
+
|
|
41
|
+
create_venv_parser = subparsers.add_parser("create-venv", parents=[common_parser])
|
|
42
|
+
create_venv_parser.add_argument("--profile", default="")
|
|
43
|
+
create_venv_parser.add_argument("--all-profiles", action="store_true")
|
|
44
|
+
|
|
45
|
+
describe_config_parser = subparsers.add_parser("describe-config", parents=[common_parser])
|
|
46
|
+
describe_config_parser.add_argument("--format", choices=("json", "bash", "powershell"), default="json")
|
|
47
|
+
|
|
48
|
+
install_pipx_parser = subparsers.add_parser("install-pipx", parents=[common_parser])
|
|
49
|
+
install_pipx_parser.add_argument("--python-base", default="")
|
|
50
|
+
|
|
51
|
+
resolve_python_parser = subparsers.add_parser("resolve-python", parents=[common_parser])
|
|
52
|
+
resolve_python_parser.add_argument("--module-name", required=True)
|
|
53
|
+
resolve_python_parser.add_argument("--format", choices=("json", "bash", "powershell"), default="json")
|
|
54
|
+
|
|
55
|
+
return parser
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def command_resolve_env(args: argparse.Namespace) -> int:
|
|
59
|
+
data = resolve_env_data(args.config, args.project_dir)
|
|
60
|
+
emit_mapping(
|
|
61
|
+
{
|
|
62
|
+
"PY_BASE": data["python_base"],
|
|
63
|
+
"CONFIG_PYTHON_BASE": data["configured_python_base"],
|
|
64
|
+
"AUTOSCRIPTS_DIR": data["autoscripts_dir"],
|
|
65
|
+
"AUTOSCRIPTS_VENV_ROOT": data["venv_root"],
|
|
66
|
+
"AUTOSCRIPTS_PIPX_SHIM_PATH": data["pipx_shim_path"],
|
|
67
|
+
"WINGET_PYTHON_ID": data["winget_python_id"],
|
|
68
|
+
},
|
|
69
|
+
args.format,
|
|
70
|
+
)
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def command_create_venv(args: argparse.Namespace) -> int:
|
|
75
|
+
if args.profile and args.all_profiles:
|
|
76
|
+
raise PyEnvError("Use either --profile or --all-profiles, not both.")
|
|
77
|
+
|
|
78
|
+
create_venvs(
|
|
79
|
+
args.config,
|
|
80
|
+
args.project_dir,
|
|
81
|
+
requested_profile=args.profile,
|
|
82
|
+
all_profiles=args.all_profiles,
|
|
83
|
+
)
|
|
84
|
+
return 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def command_describe_config(args: argparse.Namespace) -> int:
|
|
88
|
+
metadata = describe_config(args.config)
|
|
89
|
+
|
|
90
|
+
if args.format == "json":
|
|
91
|
+
print(
|
|
92
|
+
json.dumps(
|
|
93
|
+
{
|
|
94
|
+
"DEFAULT_PROFILE": metadata["default_profile"],
|
|
95
|
+
"PROFILE_NAMES": metadata["profile_names"],
|
|
96
|
+
},
|
|
97
|
+
ensure_ascii=False,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
emit_mapping(
|
|
103
|
+
{
|
|
104
|
+
"DEFAULT_PROFILE": metadata["default_profile"],
|
|
105
|
+
"PROFILE_NAMES": ",".join(metadata["profile_names"]),
|
|
106
|
+
},
|
|
107
|
+
args.format,
|
|
108
|
+
)
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def command_install_pipx(args: argparse.Namespace) -> int:
|
|
113
|
+
install_pipx(
|
|
114
|
+
args.config,
|
|
115
|
+
args.project_dir,
|
|
116
|
+
requested_python_base=args.python_base,
|
|
117
|
+
)
|
|
118
|
+
return 0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def command_resolve_python(args: argparse.Namespace) -> int:
|
|
122
|
+
data = resolve_python_runtime(args.config, args.project_dir, args.module_name)
|
|
123
|
+
emit_mapping(
|
|
124
|
+
{
|
|
125
|
+
"SELECTED_PROFILE": data["selected_profile"],
|
|
126
|
+
"PYTHON_EXECUTABLE": data["python_executable"],
|
|
127
|
+
"PROJECT_DIR": data["project_dir"],
|
|
128
|
+
},
|
|
129
|
+
args.format,
|
|
130
|
+
)
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def main(argv: list[str] | None = None) -> int:
|
|
135
|
+
parser = build_parser()
|
|
136
|
+
args = parser.parse_args(argv)
|
|
137
|
+
|
|
138
|
+
try:
|
|
139
|
+
if args.command == "resolve-env":
|
|
140
|
+
return command_resolve_env(args)
|
|
141
|
+
if args.command == "create-venv":
|
|
142
|
+
return command_create_venv(args)
|
|
143
|
+
if args.command == "describe-config":
|
|
144
|
+
return command_describe_config(args)
|
|
145
|
+
if args.command == "install-pipx":
|
|
146
|
+
return command_install_pipx(args)
|
|
147
|
+
if args.command == "resolve-python":
|
|
148
|
+
return command_resolve_python(args)
|
|
149
|
+
except PyEnvError as exc:
|
|
150
|
+
print(str(exc), file=sys.stderr)
|
|
151
|
+
return 1
|
|
152
|
+
|
|
153
|
+
parser.error(f"Unknown command: {args.command}")
|
|
154
|
+
return 2
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
raise SystemExit(main())
|
py_env_tools/core.py
ADDED
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import ntpath
|
|
5
|
+
import posixpath
|
|
6
|
+
import os
|
|
7
|
+
import shlex
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PyEnvError(RuntimeError):
|
|
16
|
+
"""Raised when py_env configuration or execution cannot proceed."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_value(container: Any, key: str, default: Any = None) -> Any:
|
|
20
|
+
if isinstance(container, dict):
|
|
21
|
+
return container.get(key, default)
|
|
22
|
+
return default
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def to_string_list(value: Any) -> list[str]:
|
|
26
|
+
if isinstance(value, list):
|
|
27
|
+
return [str(item) for item in value if item]
|
|
28
|
+
if value:
|
|
29
|
+
return [str(value)]
|
|
30
|
+
return []
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_json_file(path: str | os.PathLike[str]) -> dict[str, Any]:
|
|
34
|
+
file_path = Path(path)
|
|
35
|
+
if not file_path.is_file():
|
|
36
|
+
raise PyEnvError(f"py_env config file not found: {file_path}")
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
data = json.loads(file_path.read_text(encoding="utf-8"))
|
|
40
|
+
except Exception as exc: # pragma: no cover - exact parser message is not stable
|
|
41
|
+
raise PyEnvError(f"Failed to parse py_env config '{file_path}': {exc}") from exc
|
|
42
|
+
|
|
43
|
+
if not isinstance(data, dict):
|
|
44
|
+
raise PyEnvError(f"Expected JSON object in config: {file_path}")
|
|
45
|
+
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def merge_mapping(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
50
|
+
merged = dict(base)
|
|
51
|
+
for key, value in override.items():
|
|
52
|
+
current = merged.get(key)
|
|
53
|
+
if isinstance(current, dict) and isinstance(value, dict):
|
|
54
|
+
merged[key] = merge_mapping(current, value)
|
|
55
|
+
else:
|
|
56
|
+
merged[key] = value
|
|
57
|
+
return merged
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def current_platform_key(os_name: str | None = None, sys_platform: str | None = None) -> str:
|
|
61
|
+
resolved_os_name = os.name if os_name is None else os_name
|
|
62
|
+
resolved_sys_platform = sys.platform if sys_platform is None else sys_platform
|
|
63
|
+
|
|
64
|
+
if resolved_os_name == "nt":
|
|
65
|
+
return "windows"
|
|
66
|
+
if resolved_sys_platform == "darwin":
|
|
67
|
+
return "macos"
|
|
68
|
+
return "linux"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _target_platform(value: str | None) -> str:
|
|
72
|
+
platform = current_platform_key() if value is None else value
|
|
73
|
+
if platform not in {"windows", "linux", "macos"}:
|
|
74
|
+
raise PyEnvError(f"Unsupported target platform: {platform}")
|
|
75
|
+
return platform
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def apply_platform_overrides(
|
|
79
|
+
config: dict[str, Any], *, target_platform: str | None = None,
|
|
80
|
+
) -> dict[str, Any]:
|
|
81
|
+
platform = _target_platform(target_platform)
|
|
82
|
+
effective_config = dict(config)
|
|
83
|
+
platform_configs = get_value(config, "platforms", {})
|
|
84
|
+
if isinstance(platform_configs, dict):
|
|
85
|
+
platform_override = get_value(platform_configs, platform, {})
|
|
86
|
+
if isinstance(platform_override, dict):
|
|
87
|
+
effective_config = merge_mapping(effective_config, platform_override)
|
|
88
|
+
|
|
89
|
+
effective_config.pop("platforms", None)
|
|
90
|
+
return effective_config
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def local_override_path(config_path: str | os.PathLike[str]) -> Path:
|
|
94
|
+
main_config_path = Path(config_path)
|
|
95
|
+
return main_config_path.with_name(f"{main_config_path.stem}_local{main_config_path.suffix}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def load_py_env_config(
|
|
99
|
+
config_path: str | os.PathLike[str], *, target_platform: str | None = None,
|
|
100
|
+
) -> dict[str, Any]:
|
|
101
|
+
shared_config = apply_platform_overrides(load_json_file(config_path), target_platform=target_platform)
|
|
102
|
+
override_path = local_override_path(config_path)
|
|
103
|
+
if not override_path.is_file():
|
|
104
|
+
return shared_config
|
|
105
|
+
|
|
106
|
+
override_config = load_json_file(override_path)
|
|
107
|
+
merged = merge_mapping(shared_config, override_config)
|
|
108
|
+
merged.pop("platforms", None)
|
|
109
|
+
return merged
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def expand_config_path(value: Any) -> str:
|
|
113
|
+
if not value:
|
|
114
|
+
return ""
|
|
115
|
+
|
|
116
|
+
home = str(Path.home())
|
|
117
|
+
userprofile = os.environ.get("USERPROFILE", home)
|
|
118
|
+
localappdata = os.environ.get("LOCALAPPDATA", str(Path(home) / ".local" / "share"))
|
|
119
|
+
|
|
120
|
+
expanded = str(value)
|
|
121
|
+
expanded = expanded.replace("{HOME}", home)
|
|
122
|
+
expanded = expanded.replace("{USERPROFILE}", userprofile)
|
|
123
|
+
expanded = expanded.replace("{LOCALAPPDATA}", localappdata)
|
|
124
|
+
expanded = os.path.expandvars(expanded)
|
|
125
|
+
expanded = expanded.replace("\\", os.sep)
|
|
126
|
+
return os.path.normpath(expanded)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def normalize_repo_root(value: Any) -> str | None:
|
|
130
|
+
if not value:
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
normalized = os.path.expandvars(str(value))
|
|
134
|
+
if os.name != "nt" and len(normalized) >= 2 and normalized[1] == ":":
|
|
135
|
+
drive = normalized[0].lower()
|
|
136
|
+
rest = normalized[2:].replace("\\", "/").lstrip("/")
|
|
137
|
+
return os.path.normpath(f"/mnt/{drive}/{rest}")
|
|
138
|
+
|
|
139
|
+
return os.path.normpath(normalized.replace("\\", os.sep))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def resolve_project_dir_from_repo_path(
|
|
143
|
+
config: dict[str, Any],
|
|
144
|
+
fallback_project_dir: str | os.PathLike[str],
|
|
145
|
+
) -> str:
|
|
146
|
+
fallback = os.path.normpath(str(fallback_project_dir))
|
|
147
|
+
repo_path_config = get_value(config, "repoPath", {})
|
|
148
|
+
segments = to_string_list(get_value(repo_path_config, "projectDir"))
|
|
149
|
+
if not segments:
|
|
150
|
+
return fallback
|
|
151
|
+
|
|
152
|
+
candidate_roots: list[str] = []
|
|
153
|
+
for raw_root in (os.environ.get("USERPROFILE"), str(Path.home())):
|
|
154
|
+
normalized = normalize_repo_root(raw_root)
|
|
155
|
+
if normalized and normalized not in candidate_roots:
|
|
156
|
+
candidate_roots.append(normalized)
|
|
157
|
+
|
|
158
|
+
for root in candidate_roots:
|
|
159
|
+
candidate = os.path.join(root, *segments)
|
|
160
|
+
if os.path.isdir(candidate):
|
|
161
|
+
return os.path.normpath(candidate)
|
|
162
|
+
|
|
163
|
+
return fallback
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def is_runnable_python(candidate: str | None) -> bool:
|
|
167
|
+
if not candidate:
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
completed = subprocess.run(
|
|
172
|
+
[candidate, "--version"],
|
|
173
|
+
stdout=subprocess.DEVNULL,
|
|
174
|
+
stderr=subprocess.DEVNULL,
|
|
175
|
+
check=False,
|
|
176
|
+
)
|
|
177
|
+
except (OSError, ValueError):
|
|
178
|
+
return False
|
|
179
|
+
|
|
180
|
+
return completed.returncode == 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def python_candidates_from_path() -> list[str]:
|
|
184
|
+
candidates: list[str] = []
|
|
185
|
+
for command_name in ("python3", "python"):
|
|
186
|
+
command_path = shutil.which(command_name)
|
|
187
|
+
if command_path and command_path not in candidates:
|
|
188
|
+
candidates.append(command_path)
|
|
189
|
+
return candidates
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def conda_python_candidates() -> list[str]:
|
|
193
|
+
return [
|
|
194
|
+
os.path.join(Path.home(), "anaconda3", "bin", "python"),
|
|
195
|
+
"/opt/anaconda3/bin/python",
|
|
196
|
+
"/opt/conda/bin/python",
|
|
197
|
+
"/usr/local/anaconda3/bin/python",
|
|
198
|
+
"/usr/local/conda/bin/python",
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def miniconda_python_candidates() -> list[str]:
|
|
203
|
+
return [
|
|
204
|
+
os.path.join(Path.home(), "miniconda3", "bin", "python"),
|
|
205
|
+
"/opt/miniconda3/bin/python",
|
|
206
|
+
"/usr/local/miniconda3/bin/python",
|
|
207
|
+
]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def official_python_candidates() -> list[str]:
|
|
211
|
+
if os.name == "nt":
|
|
212
|
+
local_app_data = os.environ.get("LOCALAPPDATA", "")
|
|
213
|
+
program_files = os.environ.get("ProgramFiles", "")
|
|
214
|
+
program_files_x86 = os.environ.get("ProgramFiles(x86)", "")
|
|
215
|
+
roots = [
|
|
216
|
+
os.path.join(local_app_data, "Programs", "Python"),
|
|
217
|
+
os.path.join(program_files, "Python"),
|
|
218
|
+
os.path.join(program_files_x86, "Python"),
|
|
219
|
+
]
|
|
220
|
+
candidates: list[str] = []
|
|
221
|
+
for install_root in roots:
|
|
222
|
+
if not install_root or not os.path.isdir(install_root):
|
|
223
|
+
continue
|
|
224
|
+
for child in sorted(Path(install_root).glob("Python*/python.exe"), reverse=True):
|
|
225
|
+
candidates.append(str(child))
|
|
226
|
+
return candidates
|
|
227
|
+
|
|
228
|
+
return [
|
|
229
|
+
"/usr/bin/python3",
|
|
230
|
+
"/usr/local/bin/python3",
|
|
231
|
+
"/usr/bin/python",
|
|
232
|
+
"/usr/local/bin/python",
|
|
233
|
+
]
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def py_launcher_candidates(version_preference: str | None) -> list[str]:
|
|
237
|
+
if os.name != "nt":
|
|
238
|
+
return []
|
|
239
|
+
|
|
240
|
+
launcher = shutil.which("py")
|
|
241
|
+
if not launcher:
|
|
242
|
+
return []
|
|
243
|
+
|
|
244
|
+
selectors: list[str] = []
|
|
245
|
+
if version_preference:
|
|
246
|
+
selectors.append(version_preference)
|
|
247
|
+
selectors.append("3")
|
|
248
|
+
|
|
249
|
+
candidates: list[str] = []
|
|
250
|
+
for selector in selectors:
|
|
251
|
+
try:
|
|
252
|
+
completed = subprocess.run(
|
|
253
|
+
[launcher, f"-{selector}", "-c", "import sys; print(sys.executable)"],
|
|
254
|
+
check=False,
|
|
255
|
+
capture_output=True,
|
|
256
|
+
text=True,
|
|
257
|
+
)
|
|
258
|
+
except OSError:
|
|
259
|
+
continue
|
|
260
|
+
|
|
261
|
+
if completed.returncode == 0:
|
|
262
|
+
candidate = completed.stdout.strip()
|
|
263
|
+
if candidate and candidate not in candidates:
|
|
264
|
+
candidates.append(candidate)
|
|
265
|
+
|
|
266
|
+
return candidates
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def python_version_preference(configured_path: str, winget_python_id: str) -> str | None:
|
|
270
|
+
if winget_python_id.startswith("Python.Python."):
|
|
271
|
+
return winget_python_id.rsplit(".", 1)[-1]
|
|
272
|
+
|
|
273
|
+
configured = configured_path.replace("/", "\\")
|
|
274
|
+
marker = "Python"
|
|
275
|
+
python_index = configured.rfind(marker)
|
|
276
|
+
if python_index < 0:
|
|
277
|
+
return None
|
|
278
|
+
|
|
279
|
+
suffix = configured[python_index + len(marker) :]
|
|
280
|
+
digits = []
|
|
281
|
+
for char in suffix:
|
|
282
|
+
if char.isdigit():
|
|
283
|
+
digits.append(char)
|
|
284
|
+
else:
|
|
285
|
+
break
|
|
286
|
+
|
|
287
|
+
if len(digits) == 2:
|
|
288
|
+
return f"{digits[0]}.{digits[1]}"
|
|
289
|
+
if len(digits) == 3:
|
|
290
|
+
return f"{digits[0]}.{''.join(digits[1:])}"
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def resolve_python_interpreter(
|
|
295
|
+
configured_python_base: str,
|
|
296
|
+
winget_python_id: str = "",
|
|
297
|
+
explicit_python_base: str = "",
|
|
298
|
+
) -> str:
|
|
299
|
+
candidates: list[str] = []
|
|
300
|
+
|
|
301
|
+
for candidate in (
|
|
302
|
+
explicit_python_base,
|
|
303
|
+
os.environ.get("PY_BASE", ""),
|
|
304
|
+
configured_python_base,
|
|
305
|
+
os.environ.get("PY_ENV_BOOTSTRAP_PYTHON", ""),
|
|
306
|
+
os.environ.get("AUTOSCRIPTS_BOOTSTRAP_PYTHON", ""),
|
|
307
|
+
):
|
|
308
|
+
if candidate and candidate not in candidates:
|
|
309
|
+
candidates.append(candidate)
|
|
310
|
+
|
|
311
|
+
version_preference = python_version_preference(configured_python_base, winget_python_id)
|
|
312
|
+
candidates.extend(py_launcher_candidates(version_preference))
|
|
313
|
+
candidates.extend(python_candidates_from_path())
|
|
314
|
+
candidates.extend(conda_python_candidates())
|
|
315
|
+
candidates.extend(miniconda_python_candidates())
|
|
316
|
+
candidates.extend(official_python_candidates())
|
|
317
|
+
|
|
318
|
+
current_python = sys.executable
|
|
319
|
+
if current_python:
|
|
320
|
+
candidates.append(current_python)
|
|
321
|
+
|
|
322
|
+
seen: set[str] = set()
|
|
323
|
+
for candidate in candidates:
|
|
324
|
+
if not candidate or candidate in seen:
|
|
325
|
+
continue
|
|
326
|
+
seen.add(candidate)
|
|
327
|
+
if is_runnable_python(candidate):
|
|
328
|
+
return candidate
|
|
329
|
+
|
|
330
|
+
return ""
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def venv_python_path(venv_path: str) -> str:
|
|
334
|
+
if os.name == "nt":
|
|
335
|
+
return os.path.join(venv_path, "Scripts", "python.exe")
|
|
336
|
+
return os.path.join(venv_path, "bin", "python")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def resolve_profile_names(defaults: dict[str, Any], profiles: dict[str, Any], requested_profile: str, all_profiles: bool) -> list[str]:
|
|
340
|
+
if all_profiles:
|
|
341
|
+
return list(profiles.keys())
|
|
342
|
+
if requested_profile:
|
|
343
|
+
return [requested_profile]
|
|
344
|
+
|
|
345
|
+
default_profile = get_value(defaults, "profile")
|
|
346
|
+
if not default_profile:
|
|
347
|
+
raise PyEnvError("No profile was provided and defaults.profile is empty in py_env config.")
|
|
348
|
+
return [str(default_profile)]
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def get_pip_install_option_args(defaults: dict[str, Any]) -> list[str]:
|
|
352
|
+
args: list[str] = []
|
|
353
|
+
enable_pip_index_url = bool(get_value(defaults, "enablePipIndexUrl"))
|
|
354
|
+
enable_pip_trusted_hosts = bool(get_value(defaults, "enablePipTrustedHosts"))
|
|
355
|
+
pip_index_url = get_value(defaults, "pipIndexUrl")
|
|
356
|
+
|
|
357
|
+
if enable_pip_index_url and pip_index_url:
|
|
358
|
+
args.extend(["--index-url", str(pip_index_url)])
|
|
359
|
+
|
|
360
|
+
if enable_pip_trusted_hosts:
|
|
361
|
+
for trusted_host in to_string_list(get_value(defaults, "pipTrustedHosts")):
|
|
362
|
+
if trusted_host:
|
|
363
|
+
args.extend(["--trusted-host", trusted_host])
|
|
364
|
+
|
|
365
|
+
return args
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def has_socks_proxy_env(env: dict[str, str] | None = None) -> bool:
|
|
369
|
+
source = env or os.environ
|
|
370
|
+
for key in ("ALL_PROXY", "HTTPS_PROXY", "HTTP_PROXY", "all_proxy", "https_proxy", "http_proxy"):
|
|
371
|
+
value = source.get(key, "")
|
|
372
|
+
if value.startswith(("socks4://", "socks4a://", "socks5://", "socks5h://")):
|
|
373
|
+
return True
|
|
374
|
+
return False
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def pip_has_socks_support(interpreter: str) -> bool:
|
|
378
|
+
try:
|
|
379
|
+
completed = subprocess.run(
|
|
380
|
+
[interpreter, "-c", "import socks"],
|
|
381
|
+
stdout=subprocess.DEVNULL,
|
|
382
|
+
stderr=subprocess.DEVNULL,
|
|
383
|
+
check=False,
|
|
384
|
+
)
|
|
385
|
+
except OSError:
|
|
386
|
+
return False
|
|
387
|
+
return completed.returncode == 0
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def run_command(
|
|
391
|
+
args: list[str],
|
|
392
|
+
env: dict[str, str] | None = None,
|
|
393
|
+
cwd: str | os.PathLike[str] | None = None,
|
|
394
|
+
) -> None:
|
|
395
|
+
completed = subprocess.run(args, env=env, cwd=cwd, check=False)
|
|
396
|
+
if completed.returncode != 0:
|
|
397
|
+
raise PyEnvError(f"Command failed with exit code {completed.returncode}: {' '.join(shlex.quote(arg) for arg in args)}")
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def run_pip(
|
|
401
|
+
interpreter: str,
|
|
402
|
+
pip_args: list[str],
|
|
403
|
+
cwd: str | os.PathLike[str] | None = None,
|
|
404
|
+
) -> None:
|
|
405
|
+
env = os.environ.copy()
|
|
406
|
+
env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
|
|
407
|
+
if has_socks_proxy_env(env) and not pip_has_socks_support(interpreter):
|
|
408
|
+
print("SOCKS proxy environment detected but pip lacks PySocks support; retrying without proxy variables.")
|
|
409
|
+
for key in (
|
|
410
|
+
"ALL_PROXY",
|
|
411
|
+
"HTTPS_PROXY",
|
|
412
|
+
"HTTP_PROXY",
|
|
413
|
+
"NO_PROXY",
|
|
414
|
+
"all_proxy",
|
|
415
|
+
"https_proxy",
|
|
416
|
+
"http_proxy",
|
|
417
|
+
"no_proxy",
|
|
418
|
+
):
|
|
419
|
+
env.pop(key, None)
|
|
420
|
+
|
|
421
|
+
run_command([interpreter, "-m", "pip", *pip_args], env=env, cwd=cwd)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def ensure_python_venv_support(candidate: str) -> None:
|
|
425
|
+
try:
|
|
426
|
+
completed = subprocess.run(
|
|
427
|
+
[candidate, "-c", "import ensurepip, venv"],
|
|
428
|
+
stdout=subprocess.DEVNULL,
|
|
429
|
+
stderr=subprocess.DEVNULL,
|
|
430
|
+
check=False,
|
|
431
|
+
)
|
|
432
|
+
except OSError as exc:
|
|
433
|
+
raise PyEnvError(f"Python virtual environment prerequisites are missing for: {candidate}") from exc
|
|
434
|
+
|
|
435
|
+
if completed.returncode == 0:
|
|
436
|
+
return
|
|
437
|
+
|
|
438
|
+
package_hint = "python3-venv"
|
|
439
|
+
version_output = subprocess.run(
|
|
440
|
+
[candidate, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"],
|
|
441
|
+
check=False,
|
|
442
|
+
capture_output=True,
|
|
443
|
+
text=True,
|
|
444
|
+
)
|
|
445
|
+
if version_output.returncode == 0:
|
|
446
|
+
version = version_output.stdout.strip()
|
|
447
|
+
if version:
|
|
448
|
+
package_hint = f"{package_hint} python{version}-venv"
|
|
449
|
+
|
|
450
|
+
raise PyEnvError(
|
|
451
|
+
"Selected Python interpreter cannot create virtual environments with pip because stdlib module support is incomplete.\n"
|
|
452
|
+
f"Interpreter: {candidate}\n"
|
|
453
|
+
"Missing support: venv and/or ensurepip\n"
|
|
454
|
+
f"Install on Debian/Ubuntu: sudo apt-get install {package_hint}"
|
|
455
|
+
)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def resolve_profile_requirements_path(config_path: str, requirements_path: str) -> str:
|
|
459
|
+
expanded = expand_config_path(requirements_path)
|
|
460
|
+
if os.path.isabs(expanded):
|
|
461
|
+
return expanded
|
|
462
|
+
config_dir = str(Path(config_path).resolve().parent)
|
|
463
|
+
return os.path.normpath(os.path.join(config_dir, expanded))
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def find_pipx_executable(python_base: str, pipx_shim_path: str) -> str:
|
|
467
|
+
python_bin_dir = os.path.dirname(python_base)
|
|
468
|
+
candidate_names = ["pipx.exe", "pipx"] if os.name == "nt" else ["pipx", "pipx3"]
|
|
469
|
+
candidate_paths: list[str] = []
|
|
470
|
+
for name in candidate_names:
|
|
471
|
+
candidate_paths.append(os.path.join(python_bin_dir, name))
|
|
472
|
+
if pipx_shim_path:
|
|
473
|
+
candidate_paths.append(os.path.join(pipx_shim_path, name))
|
|
474
|
+
|
|
475
|
+
for candidate in candidate_paths:
|
|
476
|
+
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
|
|
477
|
+
return candidate
|
|
478
|
+
|
|
479
|
+
return ""
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def load_py_env_sections(
|
|
483
|
+
config_path: str, *, target_platform: str | None = None,
|
|
484
|
+
) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any], dict[str, Any]]:
|
|
485
|
+
config = load_py_env_config(config_path, target_platform=target_platform)
|
|
486
|
+
defaults = get_value(config, "defaults")
|
|
487
|
+
profiles = get_value(config, "profiles", {})
|
|
488
|
+
modules = get_value(config, "modules", {})
|
|
489
|
+
|
|
490
|
+
if not isinstance(defaults, dict):
|
|
491
|
+
raise PyEnvError(f"Missing 'defaults' section in py_env config: {config_path}")
|
|
492
|
+
if not isinstance(profiles, dict):
|
|
493
|
+
raise PyEnvError(f"Missing 'profiles' section in py_env config: {config_path}")
|
|
494
|
+
if not isinstance(modules, dict):
|
|
495
|
+
modules = {}
|
|
496
|
+
|
|
497
|
+
return config, defaults, profiles, modules
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def describe_config(config_path: str) -> dict[str, Any]:
|
|
501
|
+
_, defaults, profiles, _ = load_py_env_sections(config_path)
|
|
502
|
+
return {
|
|
503
|
+
"default_profile": str(get_value(defaults, "profile") or ""),
|
|
504
|
+
"profile_names": [str(name) for name in profiles.keys()],
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def resolve_env_data(
|
|
509
|
+
config_path: str,
|
|
510
|
+
project_dir: str,
|
|
511
|
+
) -> dict[str, str]:
|
|
512
|
+
config, defaults, _, _ = load_py_env_sections(config_path)
|
|
513
|
+
|
|
514
|
+
configured_python_base = expand_config_path(get_value(defaults, "pythonBase"))
|
|
515
|
+
venv_root = expand_config_path(get_value(defaults, "venvRoot"))
|
|
516
|
+
pipx_shim_path = expand_config_path(get_value(defaults, "pipxShimPath"))
|
|
517
|
+
winget_python_id = str(get_value(defaults, "wingetPythonId") or "")
|
|
518
|
+
|
|
519
|
+
resolved_project_dir = resolve_project_dir_from_repo_path(config, project_dir)
|
|
520
|
+
python_base = resolve_python_interpreter(configured_python_base, winget_python_id)
|
|
521
|
+
|
|
522
|
+
return {
|
|
523
|
+
"python_base": python_base,
|
|
524
|
+
"configured_python_base": configured_python_base,
|
|
525
|
+
"autoscripts_dir": resolved_project_dir,
|
|
526
|
+
"venv_root": venv_root,
|
|
527
|
+
"pipx_shim_path": pipx_shim_path,
|
|
528
|
+
"winget_python_id": winget_python_id,
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _runtime_python_path(root: Any, name: str, platform: str, portable: bool) -> str:
|
|
533
|
+
"""Format for the target OS, retaining a home placeholder when requested."""
|
|
534
|
+
path = ntpath if platform == "windows" else posixpath
|
|
535
|
+
raw_root = str(root)
|
|
536
|
+
normalized = raw_root.replace("\\", "/")
|
|
537
|
+
portable_root = None
|
|
538
|
+
if portable:
|
|
539
|
+
for prefix in ("{HOME}", "{USERPROFILE}", "~"):
|
|
540
|
+
if normalized == prefix or normalized.startswith(prefix + "/"):
|
|
541
|
+
portable_root = "{HOME}" + normalized[len(prefix):]
|
|
542
|
+
break
|
|
543
|
+
expanded = expand_config_path(raw_root)
|
|
544
|
+
if portable and portable_root is None:
|
|
545
|
+
# Only relativize paths inside this machine's home; unrelated absolute
|
|
546
|
+
# paths for a different target machine stay explicit.
|
|
547
|
+
home = path.normpath(str(Path.home()).replace("\\", "/"))
|
|
548
|
+
candidate = path.normpath(expanded.replace("\\", "/"))
|
|
549
|
+
try:
|
|
550
|
+
if path.commonpath((home, candidate)) == home:
|
|
551
|
+
relative = path.relpath(candidate, home)
|
|
552
|
+
portable_root = "{HOME}" if relative == "." else path.join("{HOME}", relative)
|
|
553
|
+
except ValueError:
|
|
554
|
+
pass # Different Windows drives or relative/absolute path mix.
|
|
555
|
+
root_path = (portable_root if portable_root is not None else expanded).replace("\\", "/")
|
|
556
|
+
suffix = ("Scripts", "python.exe") if platform == "windows" else ("bin", "python")
|
|
557
|
+
return path.normpath(path.join(root_path, name, *suffix))
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def resolve_python_runtime(
|
|
561
|
+
config_path: str,
|
|
562
|
+
project_dir: str,
|
|
563
|
+
module_name: str,
|
|
564
|
+
*,
|
|
565
|
+
target_platform: str | None = None,
|
|
566
|
+
portable: bool = False,
|
|
567
|
+
) -> dict[str, str]:
|
|
568
|
+
"""Resolve a module runtime, optionally for another OS or a portable runner.
|
|
569
|
+
|
|
570
|
+
``portable=True`` represents the home directory as a leading ``{HOME}``.
|
|
571
|
+
The caller must expand it on the target machine before executing Python.
|
|
572
|
+
Other environment variables are expanded on the generation machine.
|
|
573
|
+
"""
|
|
574
|
+
platform = _target_platform(target_platform)
|
|
575
|
+
config, defaults, profiles, modules = load_py_env_sections(config_path, target_platform=platform)
|
|
576
|
+
|
|
577
|
+
venv_root = expand_config_path(get_value(defaults, "venvRoot"))
|
|
578
|
+
selected_profile = str(get_value(defaults, "profile") or "")
|
|
579
|
+
module_config = get_value(modules, module_name, {})
|
|
580
|
+
configured_profile = get_value(module_config, "profile")
|
|
581
|
+
if configured_profile:
|
|
582
|
+
selected_profile = str(configured_profile)
|
|
583
|
+
|
|
584
|
+
if not venv_root or not selected_profile:
|
|
585
|
+
raise PyEnvError(f"Unable to resolve runtime profile from py_env config: {config_path}")
|
|
586
|
+
|
|
587
|
+
profile_config = get_value(profiles, selected_profile)
|
|
588
|
+
if not isinstance(profile_config, dict):
|
|
589
|
+
raise PyEnvError(f"Profile '{selected_profile}' from py_env config was not found: {config_path}")
|
|
590
|
+
|
|
591
|
+
venv_name = str(get_value(profile_config, "venvName") or selected_profile)
|
|
592
|
+
if target_platform is None and not portable:
|
|
593
|
+
python_executable = venv_python_path(os.path.join(venv_root, venv_name))
|
|
594
|
+
else:
|
|
595
|
+
python_executable = _runtime_python_path(get_value(defaults, "venvRoot"), venv_name, platform, portable)
|
|
596
|
+
return {
|
|
597
|
+
"selected_profile": selected_profile,
|
|
598
|
+
"python_executable": python_executable,
|
|
599
|
+
"project_dir": resolve_project_dir_from_repo_path(config, project_dir),
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def create_venvs(
|
|
604
|
+
config_path: str,
|
|
605
|
+
project_dir: str,
|
|
606
|
+
requested_profile: str = "",
|
|
607
|
+
all_profiles: bool = False,
|
|
608
|
+
) -> None:
|
|
609
|
+
_, defaults, profiles, _ = load_py_env_sections(config_path)
|
|
610
|
+
env_data = resolve_env_data(config_path, project_dir)
|
|
611
|
+
python_base = env_data["python_base"]
|
|
612
|
+
venv_root = env_data["venv_root"]
|
|
613
|
+
|
|
614
|
+
if not venv_root:
|
|
615
|
+
raise PyEnvError(f"Configured venvRoot is empty in py_env config: {config_path}")
|
|
616
|
+
if not python_base:
|
|
617
|
+
raise PyEnvError("Python interpreter not found. Run py_env write-env first or update py_env.json.")
|
|
618
|
+
|
|
619
|
+
ensure_python_venv_support(python_base)
|
|
620
|
+
profile_names = resolve_profile_names(defaults, profiles, requested_profile, all_profiles)
|
|
621
|
+
pip_install_option_args = get_pip_install_option_args(defaults)
|
|
622
|
+
|
|
623
|
+
os.makedirs(venv_root, exist_ok=True)
|
|
624
|
+
|
|
625
|
+
for profile_name in profile_names:
|
|
626
|
+
profile_config = get_value(profiles, profile_name)
|
|
627
|
+
if not isinstance(profile_config, dict):
|
|
628
|
+
raise PyEnvError(f"Profile '{profile_name}' was not found in py_env config.")
|
|
629
|
+
|
|
630
|
+
venv_name = str(get_value(profile_config, "venvName") or profile_name)
|
|
631
|
+
venv_path = os.path.join(venv_root, venv_name)
|
|
632
|
+
profile_python = venv_python_path(venv_path)
|
|
633
|
+
requirements_path = ""
|
|
634
|
+
requirements = get_value(profile_config, "requirements")
|
|
635
|
+
if requirements:
|
|
636
|
+
requirements_path = resolve_profile_requirements_path(config_path, str(requirements))
|
|
637
|
+
|
|
638
|
+
print(f"Creating virtual environment for profile '{profile_name}' at '{venv_path}'...")
|
|
639
|
+
run_command([python_base, "-m", "venv", venv_path])
|
|
640
|
+
run_pip(profile_python, ["install", *pip_install_option_args, "--upgrade", "pip"])
|
|
641
|
+
|
|
642
|
+
if requirements_path:
|
|
643
|
+
if not os.path.isfile(requirements_path):
|
|
644
|
+
raise PyEnvError(f"Requirements file not found for profile '{profile_name}': {requirements_path}")
|
|
645
|
+
run_pip(
|
|
646
|
+
profile_python,
|
|
647
|
+
["install", *pip_install_option_args, "-r", requirements_path],
|
|
648
|
+
cwd=str(Path(requirements_path).resolve().parent),
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def install_pipx(
|
|
653
|
+
config_path: str,
|
|
654
|
+
project_dir: str,
|
|
655
|
+
requested_python_base: str = "",
|
|
656
|
+
) -> dict[str, str]:
|
|
657
|
+
_, defaults, _, _ = load_py_env_sections(config_path)
|
|
658
|
+
env_data = resolve_env_data(config_path, project_dir)
|
|
659
|
+
configured_python_base = env_data["configured_python_base"]
|
|
660
|
+
python_base = resolve_python_interpreter(
|
|
661
|
+
configured_python_base,
|
|
662
|
+
env_data["winget_python_id"],
|
|
663
|
+
explicit_python_base=requested_python_base,
|
|
664
|
+
)
|
|
665
|
+
pipx_shim_path = env_data["pipx_shim_path"]
|
|
666
|
+
|
|
667
|
+
if not python_base:
|
|
668
|
+
raise PyEnvError("Python interpreter not found. Run py_env write-env first or update py_env.json.")
|
|
669
|
+
|
|
670
|
+
pip_install_option_args = get_pip_install_option_args(defaults)
|
|
671
|
+
print(f"Using Python interpreter: {python_base}")
|
|
672
|
+
run_pip(python_base, ["install", *pip_install_option_args, "--upgrade", "pip", "pipx"])
|
|
673
|
+
|
|
674
|
+
try:
|
|
675
|
+
completed = subprocess.run([python_base, "-m", "pipx", "ensurepath"], check=False)
|
|
676
|
+
except OSError as exc:
|
|
677
|
+
raise PyEnvError(f"Failed to run 'python -m pipx ensurepath' using '{python_base}'.") from exc
|
|
678
|
+
|
|
679
|
+
if completed.returncode != 0:
|
|
680
|
+
print("Falling back to invoking pipx directly because 'python -m pipx ensurepath' failed.", file=sys.stderr)
|
|
681
|
+
pipx_executable = find_pipx_executable(python_base, pipx_shim_path)
|
|
682
|
+
if not pipx_executable:
|
|
683
|
+
raise PyEnvError(
|
|
684
|
+
f"pipx executable not found after installation. Checked '{os.path.dirname(python_base)}' and '{pipx_shim_path or '<empty>'}'."
|
|
685
|
+
)
|
|
686
|
+
run_command([pipx_executable, "ensurepath"])
|
|
687
|
+
|
|
688
|
+
return {
|
|
689
|
+
"python_base": python_base,
|
|
690
|
+
"python_bin_dir": os.path.dirname(python_base),
|
|
691
|
+
"pipx_shim_path": pipx_shim_path,
|
|
692
|
+
}
|