This commit is contained in:
lemke_h committed 2026-08-25 21:39:29 +02:00
1 parent 09fc748261
commit 1f7647cad4
1 file changed
+206
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env python
"""Derive a pixi ``[dependencies]`` (conda) block from eco's own
``pyproject.toml`` dependency lists, instead of hand-duplicating them.
Why this exists
----------------
A pixi environment that installs eco via ``[pypi-dependencies]`` (git source)
works best when eco's real runtime dependencies are *already* satisfied by
conda before ``uv`` resolves eco's own dependency tree - otherwise packages
like ``pyepics`` can end up pulled from a plain PyPI wheel instead of
conda-forge's build (which bundles the EPICS ``libca`` library the PyPI wheel
does not). Hand-copying eco's dependency list into a pixi manifest works, but
silently drifts out of sync whenever ``pyproject.toml`` changes. This script
derives that list mechanically instead, so the two can never disagree.
Each dependency is checked against the conda-forge API (unless ``--no-verify``
is passed): a package with no conda-forge build is deliberately kept as a
comment in the generated conda block rather than written as an active entry
(which would make ``pixi install`` fail outright, since the conda solver could
never find it).
Packages unavailable on conda-forge are left as comments in the generated
block, so they do not break the conda solver but the gap remains visible.
They are also reported on stderr for easy review (e.g. ``diffcalc-core``,
which is PyPI-only). Git-style requirements are handled the same way because
they cannot be represented as conda entries.
Usage
-----
python scripts/sync_pixi_deps.py # print the block
python scripts/sync_pixi_deps.py --write pixi.toml # patch it in place
python scripts/sync_pixi_deps.py --no-verify # skip the conda-forge
# check (offline use;
# simple requirements
# are included)
--write requires the target file to already contain the marker comments
(see MARKER_BEGIN/MARKER_END below); it refuses to guess where to insert into
an unfamiliar file rather than risk corrupting a hand-written manifest.
"""
from __future__ import annotations
import argparse
import re
import sys
import urllib.error
import urllib.request
from pathlib import Path
try:
import tomllib # Python >= 3.11
except ModuleNotFoundError: # pragma: no cover - older interpreters
import tomli as tomllib # type: ignore[no-redef]
ECO_PYPROJECT = Path(__file__).resolve().parent.parent / "pyproject.toml"
# PyPI distribution name -> conda-forge package name, for the handful of
# cases where they differ. Everything else is used as-is (lowercased, since
# conda-forge names are conventionally lowercase while PyPI allows mixed
# case) - add to this dict if `--verify` reports a false negative.
NAME_OVERRIDES = {
"IPython": "ipython",
}
MARKER_BEGIN = "# BEGIN eco-conda-deps (auto-generated by eco/scripts/sync_pixi_deps.py - do not edit by hand)"
MARKER_END = "# END eco-conda-deps"
_REQ_RE = re.compile(r"^\s*([A-Za-z0-9._-]+)(\[[^]]+\])?\s*(.*?)\s*$")
def _parse_requirement(req: str) -> tuple[str, str]:
"""Split a simple PEP 508 requirement string into (name, specifier).
Handles the plain ``name`` / ``name>=1.0,<2`` shapes eco's core
dependency list actually uses. Does not attempt extras (``pkg[extra]``)
or environment markers (``; sys_platform == ...``) - eco's core tier has
none of those, and this script is meant to fail loudly (KeyError/assert)
rather than silently mishandle something it wasn't written for.
"""
req = req.split(";", 1)[0].strip() # drop any environment marker, unused today
m = _REQ_RE.match(req)
assert m, f"unparseable requirement: {req!r}"
name, extras, specifier = m.group(1), m.group(2), m.group(3)
if extras:
specifier = extras + specifier
return name, specifier
def _conda_name(pypi_name: str) -> str:
return NAME_OVERRIDES.get(pypi_name, pypi_name.lower())
def _on_conda_forge(conda_name: str, timeout: float = 8.0) -> bool:
url = f"https://api.anaconda.org/package/conda-forge/{conda_name}"
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
return resp.status == 200
except urllib.error.HTTPError as e:
if e.code == 404:
return False
raise
except urllib.error.URLError:
raise RuntimeError(
f"could not reach conda-forge API to verify {conda_name!r} "
"(offline? pass --no-verify to skip this check)"
)
def load_dependencies() -> list[tuple[str, str]]:
with open(ECO_PYPROJECT, "rb") as f:
data = tomllib.load(f)
dependencies: list[tuple[str, str]] = [
("core", req) for req in data["project"]["dependencies"]
]
optional = data["project"].get("optional-dependencies", {})
seen = {req for _, req in dependencies}
def add_optional_group(group: str, active_groups: set[str]) -> None:
if group in active_groups:
raise ValueError(f"cyclic optional dependency group: {group}")
for req in optional.get(group, []):
reference = re.fullmatch(r"eco\[([A-Za-z0-9_-]+)\]", req.strip())
if reference:
add_optional_group(reference.group(1), active_groups | {group})
elif req not in seen:
dependencies.append((group, req))
seen.add(req)
for group in optional:
add_optional_group(group, set())
return dependencies
def build_conda_block(verify: bool) -> tuple[str, list[str]]:
"""Return (toml_block, skipped_names)."""
lines = [MARKER_BEGIN]
skipped = []
for group, req in load_dependencies():
pypi_name, specifier = _parse_requirement(req)
conda_name = _conda_name(pypi_name)
if "[" in specifier or "@" in specifier:
skipped.append(f"{group}: {req}")
lines.append(f"# NOT A CONDA REQUIREMENT ({group}): {req}")
continue
if verify and not _on_conda_forge(conda_name):
skipped.append(f"{group}: {pypi_name}")
lines.append(
f"# NOT ON CONDA-FORGE ({group}): {conda_name} = {specifier or '*'}"
)
continue
value = specifier if specifier else "*"
lines.append(f'{conda_name} = "{value}"')
lines.append(MARKER_END)
return "\n".join(lines) + "\n", skipped
def write_in_place(target: Path, block: str) -> None:
text = target.read_text()
if MARKER_BEGIN not in text or MARKER_END not in text:
sys.exit(
f"error: {target} has no eco-conda-deps marker block yet.\n"
f"Add these two lines (with a [dependencies] table around them) "
f"once, then re-run with --write:\n\n{MARKER_BEGIN}\n{MARKER_END}\n"
)
pattern = re.compile(
re.escape(MARKER_BEGIN) + r".*?" + re.escape(MARKER_END), re.DOTALL
)
new_text = pattern.sub(block.rstrip("\n"), text, count=1)
target.write_text(new_text)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument(
"--write", metavar="PIXI_MANIFEST",
help="patch the marker block in this file instead of printing to stdout",
)
parser.add_argument(
"--no-verify", action="store_true",
help="skip the conda-forge availability check (offline use); "
"everything is included as-is",
)
args = parser.parse_args()
block, skipped = build_conda_block(verify=not args.no_verify)
if skipped:
print(
"eco dependencies not represented as conda entries (left for "
f"[pypi-dependencies] or another installer): {', '.join(skipped)}",
file=sys.stderr,
)
if args.write:
write_in_place(Path(args.write), block)
print(f"updated {args.write}", file=sys.stderr)
else:
print(block, end="")
if __name__ == "__main__":
main()