diff --git a/.github/scripts/python_versions.py b/.github/scripts/python_versions.py new file mode 100644 index 00000000..0f550e8c --- /dev/null +++ b/.github/scripts/python_versions.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Compute the window of Python versions CI should test. + +The window is every CPython minor release that is + +* released and not past its end-of-life date (per https://endoflife.date), +* installable by ``actions/setup-python`` (per actions/python-versions), and +* allowed by ``python_requires`` in setup.cfg. + +so CI follows the upstream support window instead of a hard-coded list that +breaks when runners drop an end-of-life interpreter (see issue #132). + +When run under GitHub Actions the results are written to ``$GITHUB_OUTPUT`` +as ``matrix`` (a JSON list), ``oldest`` and ``newest``. A ``::warning::`` is +emitted when the declared minimum in setup.cfg has reached end-of-life, as a +reminder to raise ``python_requires``. + +Usage: python_versions.py [path/to/setup.cfg] [--today YYYY-MM-DD] +""" + +from __future__ import annotations + +import argparse +import configparser +import datetime as dt +import json +import operator +import os +import re +import sys +import time +import urllib.request + +EOL_URL = "https://endoflife.date/api/python.json" +MANIFEST_URL = ( + "https://raw.githubusercontent.com/actions/python-versions/main/" + "versions-manifest.json" +) + +Version = tuple[int, int] + +_OPS = { + ">=": operator.ge, + "<=": operator.le, + ">": operator.gt, + "<": operator.lt, + "==": operator.eq, + "!=": operator.ne, +} + + +def parse_version(text: str) -> Version: + major, minor = text.strip().split(".")[:2] + return int(major), int(minor) + + +def fmt(v: Version) -> str: + return f"{v[0]}.{v[1]}" + + +def parse_requires(spec: str) -> list[tuple[str, Version]]: + """Parse a python_requires string such as ``>=3.11, <4`` into clauses. + + Only minor-version granularity matters for choosing interpreters, so patch + components are dropped. ``<4`` is treated as ``<4.0``. + """ + clauses = [] + for part in spec.split(","): + part = part.strip() + if not part: + continue + m = re.fullmatch(r"(>=|<=|==|!=|>|<)\s*(\d+)(?:\.(\d+))?(?:\.\d+)*", part) + if not m: + raise ValueError(f"unsupported python_requires clause: {part!r}") + op, major, minor = m.groups() + clauses.append((op, (int(major), int(minor or 0)))) + return clauses + + +def satisfies(v: Version, clauses: list[tuple[str, Version]]) -> bool: + return all(_OPS[op](v, bound) for op, bound in clauses) + + +def read_requires(setup_cfg: str) -> str: + cfg = configparser.ConfigParser() + if not cfg.read(setup_cfg): + raise FileNotFoundError(setup_cfg) + return cfg["options"]["python_requires"] + + +def fetch_json(url: str, attempts: int = 3): + for i in range(attempts): + try: + req = urllib.request.Request(url, headers={"User-Agent": "nuspacesim-ci"}) + with urllib.request.urlopen(req, timeout=30) as resp: + return json.load(resp) + except OSError as exc: + if i == attempts - 1: + raise RuntimeError(f"could not fetch {url}: {exc}") from exc + time.sleep(2**i) + + +def supported_cycles(eol_data, today: dt.date) -> list[Version]: + """Minor releases that are out (released) and not yet end-of-life.""" + out = [] + for row in eol_data: + try: + v = parse_version(row["cycle"]) + except ValueError: + continue + if v[0] != 3: + continue + released = row.get("releaseDate") + if released and dt.date.fromisoformat(released) > today: + continue + eol = row.get("eol") + # endoflife.date gives either a date string or a boolean. + if eol is True or ( + isinstance(eol, str) and dt.date.fromisoformat(eol) <= today + ): + continue + out.append(v) + return sorted(out) + + +def available_cycles(manifest) -> set[Version]: + """Minor releases with at least one stable build in setup-python.""" + return {parse_version(r["version"]) for r in manifest if r.get("stable")} + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("setup_cfg", nargs="?", default="setup.cfg") + ap.add_argument("--today", type=dt.date.fromisoformat, default=dt.date.today()) + args = ap.parse_args(argv) + + requires = read_requires(args.setup_cfg) + clauses = parse_requires(requires) + + supported = supported_cycles(fetch_json(EOL_URL), args.today) + available = available_cycles(fetch_json(MANIFEST_URL)) + + window = [] + for v in supported: + if not satisfies(v, clauses): + continue + if v not in available: + print( + f"::warning title=Python {fmt(v)} not yet in setup-python::" + f"Python {fmt(v)} is supported upstream but actions/setup-python " + "has no stable build yet; skipping it." + ) + continue + window.append(v) + + if not window: + print( + f"::error::No supported Python version satisfies " + f"python_requires = {requires!r}." + ) + return 1 + + # Warn when setup.cfg still admits an end-of-life minor release. + minimums = [b for op, b in clauses if op in (">=", ">")] + if minimums and supported: + declared_min = max(minimums) + if declared_min < supported[0]: + print( + f"::warning title=python_requires admits end-of-life Python::" + f"setup.cfg declares python_requires = {requires!r}, but Python " + f"{fmt(declared_min)} is end-of-life. The oldest supported release " + f"is {fmt(supported[0])}; consider raising python_requires." + ) + + matrix = [fmt(v) for v in window] + result = {"matrix": json.dumps(matrix), "oldest": matrix[0], "newest": matrix[-1]} + for key, value in result.items(): + print(f"{key}={value}") + + gh_out = os.environ.get("GITHUB_OUTPUT") + if gh_out: + with open(gh_out, "a") as f: + for key, value in result.items(): + f.write(f"{key}={value}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/pypi-build-test-publish.yml b/.github/workflows/pypi-build-test-publish.yml index cdb31a46..c0e90e5f 100644 --- a/.github/workflows/pypi-build-test-publish.yml +++ b/.github/workflows/pypi-build-test-publish.yml @@ -20,7 +20,9 @@ jobs: - uses: actions/setup-python@v7 with: - python-version: "3.12" + # Latest stable CPython; the wheel is pure Python, so the build + # interpreter only needs to be a supported one. + python-version: "3.x" - name: Build sdist and wheel run: | @@ -60,4 +62,4 @@ jobs: with: user: __token__ password: ${{ secrets.PYPI_SECRET }} - packages_dir: dist/ + packages-dir: dist/ diff --git a/.github/workflows/pypi-build-test.yml b/.github/workflows/pypi-build-test.yml index f0fd2baf..f5cf296f 100644 --- a/.github/workflows/pypi-build-test.yml +++ b/.github/workflows/pypi-build-test.yml @@ -11,24 +11,53 @@ on: - setup.cfg - pyproject.toml - '.github/workflows/**' + - '.github/scripts/**' pull_request: branches: [ main ] workflow_dispatch: jobs: + versions: + name: Resolve supported Python versions + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.resolve.outputs.matrix }} + oldest: ${{ steps.resolve.outputs.oldest }} + newest: ${{ steps.resolve.outputs.newest }} + + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + + # Test every CPython release that is not end-of-life, is available to + # setup-python, and is allowed by python_requires in setup.cfg. Versions + # enter and leave the matrix on their own as upstream support changes; + # see .github/scripts/python_versions.py and issue #132. + - id: resolve + run: python .github/scripts/python_versions.py setup.cfg + test: name: Test py${{ matrix.python }} on ${{ matrix.os }} runs-on: ${{ matrix.os }} + needs: versions strategy: fail-fast: false matrix: - # Matches the support declared in setup.cfg (python_requires + the - # Programming Language classifiers). Add a version here and there - # together. - os: [ubuntu-latest, macos-latest] - python: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] + # Every supported version on Linux. Hosted macOS runners are scarce + # (jobs often time out waiting to be picked up), so macOS covers + # only the two ends of the window. + os: [ubuntu-latest] + python: ${{ fromJSON(needs.versions.outputs.matrix) }} + include: + - os: macos-latest + python: ${{ needs.versions.outputs.oldest }} + - os: macos-latest + python: ${{ needs.versions.outputs.newest }} steps: - uses: actions/checkout@v7 @@ -40,6 +69,22 @@ jobs: with: python-version: ${{ matrix.python }} + # A newly released Python usually ships before compiled dependencies + # publish wheels for it, so pip builds them from source. h5py needs the + # HDF5 C library for that; with a wheel available this is unused. + - name: Install HDF5 (Linux) + if: runner.os == 'Linux' + run: | + sudo apt-get update -q + sudo apt-get install -y -q libhdf5-dev pkg-config + echo "HDF5_DIR=/usr/lib/x86_64-linux-gnu/hdf5/serial" >> "$GITHUB_ENV" + + - name: Install HDF5 (macOS) + if: runner.os == 'macOS' + run: | + brew install hdf5 + echo "HDF5_DIR=$(brew --prefix hdf5)" >> "$GITHUB_ENV" + - name: Install package and test dependencies run: | python -m pip install --upgrade pip @@ -55,7 +100,7 @@ jobs: build: name: Build pure-Python distribution runs-on: ubuntu-latest - needs: test + needs: [versions, test] steps: - uses: actions/checkout@v7 @@ -64,7 +109,7 @@ jobs: - uses: actions/setup-python@v7 with: - python-version: "3.12" + python-version: ${{ needs.versions.outputs.newest }} - name: Build sdist and wheel run: | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5a9f648d..b1dbf391 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,4 +28,4 @@ repos: rev: v2.7.0 hooks: - id: setup-cfg-fmt - args: ["--include-version-classifiers", "--max-py-version=3.14"] + args: ["--include-version-classifiers", "--max-py-version=3.15"] diff --git a/.readthedocs.yaml b/.readthedocs.yaml index d9317ed9..33495a4c 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -3,9 +3,9 @@ version: 2 build: - os: ubuntu-20.04 + os: ubuntu-24.04 tools: - python: "3.9" + python: "3.13" sphinx: builder: html diff --git a/docs/dev/index.rst b/docs/dev/index.rst index 2b244241..d012a01a 100644 --- a/docs/dev/index.rst +++ b/docs/dev/index.rst @@ -150,14 +150,16 @@ Run unit tests on multiple versions of python (Advanced) First, set up and install `pyenv `_, which will require altering your default shell environment. -Then use pyenv to install multiple versions of python. I specifically use -``3.7.11, 3.8.11, 3.9.7, 3.10.0``. Then set all of the desired versions as your "local" -pyenv python, and check that they're properly set. +Then use pyenv to install the versions of python you want to test. CI tests every +CPython release that is not end-of-life and is allowed by ``python_requires`` in +``setup.cfg``; run ``python .github/scripts/python_versions.py`` to print the current +list. Then set all of the desired versions as your "local" pyenv python, and check +that they're properly set. :: - pyenv install 3.7.11 3.8.11 3.9.7 3.10.0 - pyenv local 3.7.11 3.8.11 3.9.7 3.10.0 + pyenv install 3.11 3.12 3.13 3.14 3.15 + pyenv local 3.11 3.12 3.13 3.14 3.15 pyenv versions Finally run the test suite against all versions in parallel with tox. diff --git a/recipe/meta.yaml b/recipe/meta.yaml index 5cef475a..7f196a59 100644 --- a/recipe/meta.yaml +++ b/recipe/meta.yaml @@ -10,7 +10,7 @@ source: git_url: {{ environ.get('FEEDSTOCK_ROOT', '..') }} build: - skip: true # [py<39] + skip: true # [py<311] skip: true # [win] number: {{ build_number }} @@ -21,7 +21,7 @@ build: requirements: host: - pip - - python >=3.9 + - python >=3.11 - setuptools >=46 - setuptools_scm[toml] >=3.4 - wheel @@ -34,7 +34,7 @@ requirements: - numpy >=1.21 - pydantic - rich - - python >=3.9 + - python >=3.11 - scipy - tomli-w diff --git a/setup.cfg b/setup.cfg index fe7b6aa3..deb490ff 100644 --- a/setup.cfg +++ b/setup.cfg @@ -12,12 +12,11 @@ classifiers = License :: OSI Approved :: BSD License Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only - Programming Language :: Python :: 3.9 - Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 Programming Language :: Python :: 3.13 Programming Language :: Python :: 3.14 + Programming Language :: Python :: 3.15 keywords = NASA neutrinos @@ -38,8 +37,7 @@ install_requires = rich scipy tomli-w - tomli;python_version<"3.11" -python_requires = >=3.9 +python_requires = >=3.11 package_dir = = src zip_safe = False @@ -91,14 +89,12 @@ universal = 0 [tox:tox] envlist = - py{39,310,311,312,313,314,315} + py{311,312,313,314,315} docs isolated_build = True [gh-actions] python = - 3.9: py39 - 3.10: py310 3.11: py311 3.12: py312 3.13: py313 @@ -113,7 +109,7 @@ commands = [testenv:docs] description = invoke sphinx-build to build HTML docs -basepython = python3.10 +basepython = python3.13 deps = sphinx sphinx-panels diff --git a/src/nuspacesim/config.py b/src/nuspacesim/config.py index ef023722..e4ed3458 100644 --- a/src/nuspacesim/config.py +++ b/src/nuspacesim/config.py @@ -36,10 +36,12 @@ from __future__ import annotations +import tomllib from datetime import datetime from typing import Annotated, Literal, Optional, Union import numpy as np +import tomli_w from astropy import units as u from astropy.io import fits from astropy.units import Quantity @@ -55,13 +57,6 @@ from .utils.misc import unflatten_dict -try: - import tomllib -except ModuleNotFoundError: - import tomli as tomllib - -import tomli_w - __all__ = [ "NssConfig", "Detector",