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
106 changes: 106 additions & 0 deletions .github/workflows/pypi.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# The package on PyPI: what a pushed vX.Y.Z tag turns into, as tenish-stack.
#
# 1. the tag names the version pyproject.toml declares, and points at a commit on main
# 2. the sdist and wheel, built at the tag with SOURCE_DATE_EPOCH set to the commit time
# (a re-run with the same setuptools builds the same wheel; the sdist keeps file
# mtimes), checked with `twine check --strict`
# 3. both published to PyPI by Trusted Publishing
#
# This workflow does not run the tests: a tag is cut from a main commit whose CI passed,
# and step 1 refuses a tag that isn't on main.
#
# Two jobs, as pypa's publish action asks. `build` checks, builds and runs twine with only
# `contents: read`: `uv build` and `twine` fetch unpinned packages from PyPI, and none of
# that code may run where an upload token can be minted. `pypi` holds `id-token: write`,
# runs in the `pypi` environment, and only downloads `build`'s files and publishes them,
# on a tag only. The upload needs a trusted publisher on pypi.org for tenish-stack (owner
# tenishai, repository stack, workflow pypi.yml, environment pypi); until the project's
# first upload that is a pending publisher. No PyPI token is stored here. skip-existing lets a re-run of a published tag pass. A dry run from a
# branch builds and checks only:
# gh workflow run pypi.yml --ref main
name: pypi
on:
push:
tags: ["v*"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: pypi-${{ github.ref_name }}
cancel-in-progress: false
jobs:
build:
name: PyPI build
runs-on: ubuntu-24.04
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false

- uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3

- name: The tag names the version pyproject.toml declares (a branch is a dry run)
run: |
set -euo pipefail
declared="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
echo "pyproject.toml declares $declared"
if [ "$GITHUB_REF_TYPE" = tag ]; then
case "$GITHUB_REF_NAME" in v[0-9]*.[0-9]*.[0-9]*) ;; *) echo "::error::$GITHUB_REF_NAME is not a vX.Y.Z tag"; exit 1;; esac
[ "${GITHUB_REF_NAME#v}" = "$declared" ] || { echo "::error::tag $GITHUB_REF_NAME but pyproject.toml declares $declared"; exit 1; }
else
echo "::notice::dry run from $GITHUB_REF_NAME: build and check only; nothing is published"
fi
echo "VERSION=$declared" >> "$GITHUB_ENV"

- name: A tag points at a commit on main
if: github.ref_type == 'tag'
run: |
set -euo pipefail
git merge-base --is-ancestor HEAD origin/main \
|| { echo "::error::$GITHUB_REF_NAME is not on main; tag a merged main commit"; exit 1; }

- name: Build the sdist and wheel, and check them
run: |
set -euo pipefail
SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" uv build --out-dir dist
ls dist
for f in "dist/tenish_stack-$VERSION-py3-none-any.whl" "dist/tenish_stack-$VERSION.tar.gz"; do
[ -f "$f" ] || { echo "::error::expected $f"; exit 1; }
done
[ "$(ls dist | wc -l)" -eq 2 ] || { echo "::error::dist holds more than the sdist and wheel"; exit 1; }
uvx twine check --strict dist/*
(cd dist && sha256sum -- *) | tee -a "$GITHUB_STEP_SUMMARY"

- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: python-dist
path: dist/
if-no-files-found: error
retention-days: 7

pypi:
name: PyPI
needs: [build]
if: github.ref_type == 'tag'
runs-on: ubuntu-24.04
timeout-minutes: 15
environment:
name: pypi
url: https://pypi.org/p/tenish-stack
permissions:
id-token: write
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: python-dist
path: dist/

- name: Publish to PyPI (a tag only)
if: github.ref_type == 'tag'
uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
with:
skip-existing: true
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ releases yet; everything is under Unreleased.

### Added

- **A release tag publishes the package to PyPI.** A new `.github/workflows/pypi.yml` runs on a pushed `vX.Y.Z` tag: it checks the tag against `pyproject.toml`, refuses a tag that isn't on main, builds the sdist and wheel with `SOURCE_DATE_EPOCH` at the commit time and runs `twine check --strict` in a `build` job with no upload token, and a `pypi` job that only downloads those files publishes them to `tenish-stack` by Trusted Publishing.

- **The add-profile form asks a name.** The stranger run (2026-11-30) met twelve boxes labelled
with flag names and placeholders that were our own paths, and nothing on the page said what
a stack file, a kubeconfig or a repo clone was. The form now asks a name and offers a
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[project]
name = "tenish-stack"
version = "0.1.0"
readme = "README.md"
description = "Install the tenish stack on a Gojira: one file, one command, the merges stay with a person."
requires-python = ">=3.12"
license = "MIT"
Expand Down
100 changes: 100 additions & 0 deletions tests/test_ci_workflow.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"""The repo's own CI: GitHub-hosted runners only, and one `ci` summary job that
is green only when every other job is (agora discussion 71, rule 4)."""

import os
import re
import shutil
import subprocess
from pathlib import Path

import pytest
import yaml

WORKFLOW = Path(__file__).parent.parent / ".github" / "workflows" / "ci.yml"
Expand Down Expand Up @@ -39,3 +43,99 @@ def test_every_action_is_pinned_to_a_commit_sha():
if "uses" in step and not pinned.match(step["uses"])
]
assert not unpinned, f"pin these to a full commit SHA: {unpinned}"


PYPI = WORKFLOW.parent / "pypi.yml"


def test_pypi_publishes_only_a_tag_by_trusted_publishing():
"""Each guard pypi.yml's header promises, pinned so deleting it fails here."""
doc = yaml.safe_load(PYPI.read_text())
default = doc.get("permissions")
assert default == {"contents": "read"}, "the workflow default mints no OIDC token"
jobs = doc["jobs"]
oidc = [name for name, job in jobs.items() if job.get("permissions", {}).get("id-token")]
assert oidc == ["pypi"], f"only the pypi job may mint an OIDC token, not {oidc}"
build, pypi = jobs["build"], jobs["pypi"]
assert build["permissions"] == {"contents": "read"}, "the build runs unpinned code: no token"
assert pypi["needs"] == ["build"]
assert pypi["permissions"] == {"id-token": "write"}, "the token, and nothing beside it"
assert pypi.get("if") == "github.ref_type == 'tag'", "a dry run never asks for the token"
# The publishing job runs no script of its own, so no build dependency runs where the
# OIDC token can be minted (pypa/gh-action-pypi-publish's README).
assert [s for s in pypi["steps"] if "run" in s] == []
used = [s.get("uses", "").split("@")[0] for s in pypi["steps"]]
assert used == ["actions/download-artifact", "pypa/gh-action-pypi-publish"], (
f"the token job fetches the built files and publishes them, nothing else: {used}"
)
assert pypi["environment"]["name"] == "pypi", "the trusted publisher names this environment"
action = "pypa/gh-action-pypi-publish@"
publish = [s for s in pypi["steps"] if s.get("uses", "").startswith(action)]
assert len(publish) == 1
step = publish[0]
assert step.get("if") == "github.ref_type == 'tag'", "a dry run never uploads"
assert re.fullmatch(r"pypa/gh-action-pypi-publish@[0-9a-f]{40}", step["uses"]), "pinned by sha"
assert not {"password", "user"} & set(step.get("with", {})), "Trusted Publishing takes no token"
names = [s.get("name", s.get("uses", "")) for s in pypi["steps"]]
assert names.index(step["name"]) == len(names) - 1, "publishing is the last step"


def _pypi_version_step() -> str:
return _pypi_build_step("The tag names the version")


def _pypi_build_step(prefix: str) -> str:
[step] = [s for s in yaml.safe_load(PYPI.read_text())["jobs"]["build"]["steps"]
if s.get("name", "").startswith(prefix)]
return step["run"]


@pytest.mark.parametrize(
("ref_type", "ref_name", "ok"),
[
("tag", "v1.2.3", True),
("tag", "v1.2.4", False), # pyproject.toml declares another version
("tag", "release-1.2.3", False), # not a vX.Y.Z tag
("tag", "1.2.3", False), # the declared version, but no v: only the format check stops it
("branch", "main", True), # a dry run checks no tag
],
)
def test_pypi_refuses_a_tag_pyproject_toml_does_not_declare(tmp_path, ref_type, ref_name, ok):
pyproject = '[project]\nname = "tenish-stack"\nversion = "1.2.3"\n'
(tmp_path / "pyproject.toml").write_text(pyproject)
env_file = tmp_path / "github_env"
proc = subprocess.run(
["bash", "-e", "-c", _pypi_version_step()], cwd=tmp_path, capture_output=True, text=True,
env={"PATH": os.environ["PATH"], "GITHUB_REF_TYPE": ref_type, "GITHUB_REF_NAME": ref_name,
"GITHUB_ENV": str(env_file)},
)
assert (proc.returncode == 0) is ok, proc.stdout + proc.stderr
if ok:
assert env_file.read_text() == "VERSION=1.2.3\n"


@pytest.mark.parametrize(("tag_main", "ok"), [(True, True), (False, False)])
def test_pypi_refuses_a_tag_that_is_not_on_main(tmp_path, tag_main, ok):
"""A tag on a commit main doesn't contain would publish code CI never ran."""
if not shutil.which("git"):
pytest.skip("needs git")

def git(*args):
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args],
cwd=tmp_path, check=True, capture_output=True)

git("init", "-q", "-b", "main")
git("commit", "-q", "--allow-empty", "-m", "on main")
git("update-ref", "refs/remotes/origin/main", "HEAD")
if not tag_main:
git("checkout", "-q", "-b", "side")
git("commit", "-q", "--allow-empty", "-m", "never merged")
[step] = [s for s in yaml.safe_load(PYPI.read_text())["jobs"]["build"]["steps"]
if s.get("name", "").startswith("A tag points at a commit on main")]
assert step.get("if") == "github.ref_type == 'tag'", "a dry run from a branch isn't on main"
proc = subprocess.run(
["bash", "-e", "-c", step["run"]],
cwd=tmp_path, capture_output=True, text=True,
env={"PATH": os.environ["PATH"], "GITHUB_REF_NAME": "v1.2.3"},
)
assert (proc.returncode == 0) is ok, proc.stdout + proc.stderr
Loading