Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 189 additions & 0 deletions .github/scripts/python_versions.py
Original file line number Diff line number Diff line change
@@ -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())
6 changes: 4 additions & 2 deletions .github/workflows/pypi-build-test-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down Expand Up @@ -60,4 +62,4 @@ jobs:
with:
user: __token__
password: ${{ secrets.PYPI_SECRET }}
packages_dir: dist/
packages-dir: dist/
59 changes: 52 additions & 7 deletions .github/workflows/pypi-build-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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: |
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
4 changes: 2 additions & 2 deletions .readthedocs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 7 additions & 5 deletions docs/dev/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,16 @@ Run unit tests on multiple versions of python (Advanced)
First, set up and install `pyenv <https://github.com/pyenv/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.
Expand Down
6 changes: 3 additions & 3 deletions recipe/meta.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand All @@ -21,7 +21,7 @@ build:
requirements:
host:
- pip
- python >=3.9
- python >=3.11
- setuptools >=46
- setuptools_scm[toml] >=3.4
- wheel
Expand All @@ -34,7 +34,7 @@ requirements:
- numpy >=1.21
- pydantic
- rich
- python >=3.9
- python >=3.11
- scipy
- tomli-w

Expand Down
Loading
Loading