Files
DeepTutor/.github/workflows/pypi-release.yml
2026-10-28 22:41:28 +08:00

231 lines
8.0 KiB
YAML

name: PyPI Release
# Triggered when a GitHub Release is published.
# Builds disjoint core, feature, server and Web wheels from one revision.
# Each distribution needs this workflow configured as its trusted publisher.
# The CLI compatibility distribution contains metadata only.
#
# Expected tag format: vMAJOR.MINOR.PATCH, with PEP 440-compatible suffixes allowed.
# Example: GitHub release tag v1.3.10 -> PyPI version 1.3.10.
#
# PyPI authentication uses Trusted Publishing. Configure the `deeptutor` PyPI
# project to trust this workflow file, then no API token secret is needed.
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: Existing release tag to publish
required: true
type: string
resume:
description: Skip files already uploaded by a partial release
default: false
type: boolean
bootstrap:
description: Wait for first-time module publishers to be registered in PyPI
default: false
type: boolean
env:
RELEASE_TAG: ${{ inputs.tag || github.event.release.tag_name }}
permissions:
contents: read
id-token: write
concurrency:
group: pypi-release-${{ inputs.tag || github.event.release.tag_name }}
cancel-in-progress: false
jobs:
validate-release-tag:
name: Validate release tag
if: startsWith(inputs.tag || github.event.release.tag_name, 'v')
runs-on: ubuntu-latest
steps:
- name: Require a package version tag
shell: python
run: |
import os
import re
tag = os.environ["RELEASE_TAG"]
pattern = (
r"^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
r"(?:(?:a|b|rc)(?:0|[1-9]\d*))?"
r"(?:\.post(?:0|[1-9]\d*))?"
r"(?:\.dev(?:0|[1-9]\d*))?"
r"(?:\+[0-9A-Za-z]+(?:[._-][0-9A-Za-z]+)*)?$"
)
if not re.fullmatch(pattern, tag):
raise SystemExit(
f"Release tag {tag!r} is not a package version tag "
"(expected vX.Y.Z with an optional suffix)."
)
build-and-publish:
name: Build and Publish PyPI Package
needs: validate-release-tag
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/project/deeptutor/
steps:
- name: Checkout release tag
uses: actions/checkout@v4
with:
ref: ${{ inputs.tag || github.event.release.tag_name }}
fetch-depth: 0
- name: Verify release tag is on main
shell: bash
run: |
set -euo pipefail
git fetch origin main:refs/remotes/origin/main --no-tags
tag="$RELEASE_TAG"
tag_commit="$(git rev-list -n 1 "$tag")"
if ! git merge-base --is-ancestor "$tag_commit" origin/main; then
echo "Release tag $tag ($tag_commit) is not on origin/main; refusing to publish to PyPI." >&2
exit 1
fi
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: web/package-lock.json
- name: Install build tools
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade build packaging twine setuptools wheel
- name: Verify release tag matches deeptutor/__version__.py
id: version
shell: bash
run: |
set -euo pipefail
python - <<'PY'
import os
import re
from pathlib import Path
from packaging.version import Version
tag = os.environ["RELEASE_TAG"]
tag_raw = tag[1:] if tag.startswith("v") else tag
tag_version = str(Version(tag_raw))
src = Path("deeptutor/__version__.py").read_text(encoding="utf-8")
match = re.search(r'^__version__\s*=\s*"([^"]+)"', src, re.MULTILINE)
if not match:
raise SystemExit(
"Could not find __version__ in deeptutor/__version__.py"
)
code_version = str(Version(match.group(1)))
if code_version != tag_version:
raise SystemExit(
f"Release tag {tag!r} (normalized {tag_version!r}) does not "
f"match deeptutor/__version__.py value {code_version!r}. "
"Bump __version__ before tagging."
)
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as handle:
handle.write(f"version={code_version}\n")
PY
- name: Install frontend dependencies
working-directory: web
run: npm ci --legacy-peer-deps
- name: Build packaged Web assets
run: python scripts/prepare_web_package.py
env:
NEXT_PUBLIC_API_BASE: __NEXT_PUBLIC_API_BASE_PLACEHOLDER__
NEXT_PUBLIC_AUTH_ENABLED: __NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__
- name: Build distributions
shell: bash
run: |
set -euo pipefail
mkdir -p dist/deeptutor
python scripts/build_modules.py --output dist/deeptutor
- name: Verify package metadata
run: |
python -m twine check dist/deeptutor/*
python - <<'PY'
from pathlib import Path
expected = "${{ steps.version.outputs.version }}"
files = {
"deeptutor": sorted(path.name for path in Path("dist/deeptutor").glob("*")),
}
for package, names in files.items():
print(package)
print("\n".join(f" {name}" for name in names))
required = [
("deeptutor", f"deeptutor-{expected}-py3-none-any.whl"),
]
missing = [name for package, name in required if name not in files[package]]
if missing:
raise SystemExit(f"Missing expected distributions: {missing}")
PY
- name: Publish module distributions to PyPI
if: ${{ !inputs.bootstrap }}
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: dist/deeptutor/
print-hash: true
skip-existing: ${{ inputs.resume || false }}
- name: Bootstrap new module projects with Trusted Publishing
if: ${{ inputs.bootstrap }}
timeout-minutes: 35
env:
TWINE_NON_INTERACTIVE: "1"
run: |
python -m pip install --upgrade pypi-attestations "twine>=6.1"
python -m pypi_attestations sign dist/deeptutor/*.whl
python - <<'PY'
from pathlib import Path
import re
import subprocess
import sys
import time
# PyPI permits one pending project per publisher configuration.
# Each new Twine process exchanges a fresh OIDC token, converting
# the next pending publisher without needing a long-lived API key.
files = sorted(str(path) for path in Path("dist/deeptutor").glob("*"))
deadline = time.monotonic() + 1800
while True:
result = subprocess.run(
[sys.executable, "-m", "twine", "upload", "--non-interactive",
"--verbose", "--skip-existing", "--attestations", *files],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
print(result.stdout, flush=True)
if result.returncode == 0:
break
output = " ".join(re.sub(r"\x1b\[[0-9;]*m", "", result.stdout).split())
waiting_for_publisher = (
"Non-user identities cannot create new projects" in output
or "isn't allowed to upload to project" in output
)
if not waiting_for_publisher or time.monotonic() >= deadline:
raise SystemExit(result.returncode)
print("Waiting for the next PyPI pending publisher; retrying in 10s.", flush=True)
time.sleep(10)
PY