From 008a5bd76b5b6500ed87e90a02d422e9c8971796 Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Thu, 12 Nov 2026 11:28:36 -0800 Subject: [PATCH 1/3] docs: maintain API versions through release PRs Remove automatic version-list commits and push-triggered deployment. Publish the reviewed list after release publication or manual dispatch. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/PULL_REQUEST_TEMPLATE | 1 + .github/workflows/publish-docs.yml | 34 +----------------------------- README.md | 3 ++- docs/project-contributions.md | 29 +++++++++++++++++-------- 4 files changed, 24 insertions(+), 43 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE b/.github/PULL_REQUEST_TEMPLATE index 823a017e..4b7383c2 100644 --- a/.github/PULL_REQUEST_TEMPLATE +++ b/.github/PULL_REQUEST_TEMPLATE @@ -4,4 +4,5 @@ _Give a narrative description of what has been changed._ ## Checklist - [ ] This PR represents a single feature, fix, or change. - [ ] All applicable changes have been documented. +- [ ] If this is a stable release introducing a new major/minor version line, its tag has been added to `api-docs/versions.json` (patch releases and prereleases do not add entries). - [ ] Any `TO DO` items (or similar) have been entered as GitHub issues and the link to that issue has been included in a comment. diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 0a5876c0..c59e039d 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -6,15 +6,6 @@ on: workflow_dispatch: - push: - branches: [main] - paths: - - 'api-docs/**' - - 'scripts/generate_api_docs.py' - - 'scripts/generate_versioned_api_docs.py' - - 'requirements-dev.txt' - - '.github/workflows/publish-docs.yml' - permissions: contents: read pages: write @@ -26,10 +17,6 @@ concurrency: jobs: deploy: - permissions: - contents: write - pages: write - id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} @@ -40,26 +27,7 @@ jobs: filter: tree:0 fetch-depth: 0 ref: main - - - name: Add release to versioned documentation - if: github.event_name == 'release' && !github.event.release.prerelease - env: - RELEASE_TAG: ${{ github.event.release.tag_name }} - run: | - if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then - echo "::error::Release tags must use the format vX.Y.Z with an optional prerelease suffix (e.g. v1.2.3-alpha)" - exit 1 - fi - jq --arg tag "$RELEASE_TAG" '.versions = [$tag] + (.versions - [$tag])' \ - api-docs/versions.json > api-docs/versions.json.tmp - mv api-docs/versions.json.tmp api-docs/versions.json - git add api-docs/versions.json - if ! git diff --cached --quiet; then - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git commit -m "docs: add $RELEASE_TAG to the versioned docs" - git push origin HEAD:main - fi + persist-credentials: false - name: Setup Pages uses: actions/configure-pages@v5 diff --git a/README.md b/README.md index 7407686e..862ac73d 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,8 @@ API documentation is published at [github.io/c2pa-python/api/c2pa](https://conte Use the documentation version dropdown to choose a published release. The versions are selected in `api-docs/versions.json`; the first entry is the default at the existing documentation URL. -Publishing a stable GitHub release automatically adds its tag as the default while retaining older versions. +For a stable release introducing a new major/minor version line, update this list in the release PR before tagging and publishing; patch releases and prereleases do not add entries. +Documentation is deployed when a GitHub release is published or when the documentation workflow is manually run, without committing or pushing to `main`. To build documentation locally, see [Contributing to the project](https://github.com/contentauth/c2pa-python/blob/main/docs/project-contributions.md#api-reference-documentation). diff --git a/docs/project-contributions.md b/docs/project-contributions.md index 45613332..26941bfb 100644 --- a/docs/project-contributions.md +++ b/docs/project-contributions.md @@ -161,9 +161,16 @@ This uses `sphinx-autoapi` to parse `src/c2pa` directly, avoiding imports of nat Edit [api-docs/versions.json](../api-docs/versions.json) to choose the exact GitHub release tags shown in the sidebar dropdown. Entries must be unique tags such as `v0.38.0`. The first entry is the default served at the existing -documentation URL. When a stable GitHub release is published, the publishing -workflow prepends its tag and commits the updated list to `main` before building -the site. Older entries are retained; pre-releases are not automatically added. +documentation URL. + +For a stable release introducing a new major/minor version line, include the +version-list update in the release PR alongside the package version bump. +For example, add `v0.39.0` after `v0.38.0`, or `v1.0.0` after `v0.39.0`; +patch releases such as `v0.38.1` and prereleases do not add entries. +Prepend a newer line to make it the default and retain older entries. +If adding an older maintenance line, place it after the newer default. +Merge the release PR through normal review and required checks, then tag the +merged release commit and publish the GitHub release. Fetch the release tags and build the complete site: @@ -192,9 +199,13 @@ The complete site is written to `api-docs/_build/versioned/`: The publishing workflow always checks out `main` for the release list and build tooling, including when triggered by a release. It rebuilds all selected -versions when a release is published, when relevant documentation files change -on `main`, or when manually dispatched. The workflow needs permission to push -the version-list commit to `main`, including under any branch protection rules. -The same release-triggered run builds and deploys the updated list; it does not -rely on the bot's push triggering another workflow. Publish manual changes to -the list on `main` to add, remove, or reorder dropdown entries. +versions when a GitHub release is published or when manually dispatched. +It reads the committed version list without changing it and requires only +read access to repository contents, plus GitHub Pages deployment permissions. +It does not run on pushes to `main`: a merged release PR can list a tag before +its GitHub release exists, and the builder intentionally rejects unpublished +releases. Do not manually dispatch a build while a listed release is unpublished. +Patch releases and prereleases rebuild the existing selection without adding +entries. For documentation-only changes or changes to existing dropdown entries, +merge a PR into `main`, then manually run **Build and publish docs** from the +Actions tab to deploy without waiting for another release. From e6c8fcd1f18c339c86384d285c083740556250ec Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Wed, 25 Nov 2026 09:42:23 -0800 Subject: [PATCH 2/3] docs: publish latest stable API patch per retained release line Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/deploy-docs.yml | 93 +++++++++++ .github/workflows/publish-docs.yml | 89 +++------- README.md | 8 +- api-docs/_templates/version-selector.html | 5 +- api-docs/conf.py | 8 +- api-docs/versions.json | 20 ++- docs/project-contributions.md | 86 ++++++++-- scripts/docs_versions.py | 88 ++++++++++ scripts/generate_versioned_api_docs.py | 49 ++++-- scripts/promote_docs_release.py | 95 +++++++++++ tests/test_docs_versions.py | 189 ++++++++++++++++++++++ tests/test_versioned_docs.py | 46 ++++-- 12 files changed, 658 insertions(+), 118 deletions(-) create mode 100644 .github/workflows/deploy-docs.yml create mode 100644 scripts/docs_versions.py create mode 100644 scripts/promote_docs_release.py create mode 100644 tests/test_docs_versions.py diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml new file mode 100644 index 00000000..7fbd316e --- /dev/null +++ b/.github/workflows/deploy-docs.yml @@ -0,0 +1,93 @@ +name: Deploy API docs + +on: + workflow_run: + workflows: ['Build and publish docs'] + types: [completed] + workflow_dispatch: + push: + branches: [main] + paths: + - 'api-docs/**' + - 'scripts/generate_api_docs.py' + - 'scripts/generate_versioned_api_docs.py' + - 'scripts/docs_versions.py' + - 'scripts/promote_docs_release.py' + - 'requirements-dev.txt' + - '.github/workflows/publish-docs.yml' + - '.github/workflows/deploy-docs.yml' + +permissions: + contents: read + +# Coalesce publications, not promotions. Every admitted run builds current main +# after entering this group, so replacement of pending events cannot lose state. +concurrency: + group: >- + ${{ (github.event_name != 'workflow_run' || + (github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.head_repository.full_name == github.repository)) && + 'github-pages' || format('docs-ignored-{0}', github.run_id) }} + cancel-in-progress: false + +jobs: + build: + if: >- + (github.event_name != 'workflow_run' || + (github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.head_repository.full_name == github.repository)) + runs-on: ubuntu-latest + outputs: + revision: ${{ steps.source.outputs.revision }} + steps: + - uses: actions/checkout@v4 + with: + filter: tree:0 + fetch-depth: 0 + ref: main + persist-credentials: false + - id: source + run: echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + - uses: actions/setup-python@v5 + with: + python-version: "3.10" + cache: pip + - name: Install documentation dependencies + run: python -m pip install -r requirements-dev.txt + - name: Build exact release sources with current tooling + env: + GITHUB_TOKEN: ${{ github.token }} + run: python scripts/generate_versioned_api_docs.py + - uses: actions/upload-pages-artifact@v3 + with: + path: api-docs/_build/versioned/ + + deploy: + needs: build + runs-on: ubuntu-latest + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Reject obsolete build + id: current + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + BUILT_REVISION: ${{ needs.build.outputs.revision }} + run: | + latest=$(gh api "repos/$REPOSITORY/commits/main" --jq .sha) + if [[ "$latest" == "$BUILT_REVISION" ]]; then + echo "publish=true" >> "$GITHUB_OUTPUT" + else + echo "::notice::Skipping obsolete build; a queued publication builds current main. Manually dispatch if only unrelated paths changed." + fi + - uses: actions/configure-pages@v5 + if: steps.current.outputs.publish == 'true' + - uses: actions/deploy-pages@v4 + if: steps.current.outputs.publish == 'true' + id: deployment diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index 0a5876c0..0d4588d7 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -6,83 +6,44 @@ on: workflow_dispatch: - push: - branches: [main] - paths: - - 'api-docs/**' - - 'scripts/generate_api_docs.py' - - 'scripts/generate_versioned_api_docs.py' - - 'requirements-dev.txt' - - '.github/workflows/publish-docs.yml' - permissions: contents: read - pages: write - id-token: write - -concurrency: - group: 'github-pages' - cancel-in-progress: false +# Do not queue promotions in a concurrency group: GitHub discards pending runs. jobs: - deploy: - permissions: - contents: write - pages: write - id-token: write - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} + promote: + if: github.event_name == 'release' && !github.event.release.prerelease && !github.event.release.draft runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: - filter: tree:0 - fetch-depth: 0 ref: main - - - name: Add release to versioned documentation - if: github.event_name == 'release' && !github.event.release.prerelease + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: "3.10" + - name: Require dedicated documentation App env: - RELEASE_TAG: ${{ github.event.release.tag_name }} + APP_ID: ${{ vars.C2PA_DOCS_APP_ID }} + APP_KEY: ${{ secrets.C2PA_DOCS_APP_PRIVATE_KEY }} run: | - if [[ ! "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then - echo "::error::Release tags must use the format vX.Y.Z with an optional prerelease suffix (e.g. v1.2.3-alpha)" + if [[ -z "$APP_ID" || -z "$APP_KEY" ]]; then + echo "::error::Configure C2PA_DOCS_APP_ID and C2PA_DOCS_APP_PRIVATE_KEY for the repository-scoped docs App; no workflow-token fallback is permitted." exit 1 fi - jq --arg tag "$RELEASE_TAG" '.versions = [$tag] + (.versions - [$tag])' \ - api-docs/versions.json > api-docs/versions.json.tmp - mv api-docs/versions.json.tmp api-docs/versions.json - git add api-docs/versions.json - if ! git diff --cached --quiet; then - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git commit -m "docs: add $RELEASE_TAG to the versioned docs" - git push origin HEAD:main - fi - - - name: Setup Pages - uses: actions/configure-pages@v5 - - - name: Set up Python - uses: actions/setup-python@v5 + - name: Mint manifest writer token + id: app + uses: actions/create-github-app-token@v2 with: - python-version: "3.10" - cache: "pip" - - - name: Install dev deps - run: python3 -m pip install -r requirements-dev.txt - - - name: Build docs + app-id: ${{ vars.C2PA_DOCS_APP_ID }} + private-key: ${{ secrets.C2PA_DOCS_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + - name: Verify and promote stable release env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_ID: ${{ github.event.release.id }} GITHUB_TOKEN: ${{ github.token }} - run: python3 scripts/generate_versioned_api_docs.py - - - name: Upload artifact - uses: actions/upload-pages-artifact@v3 - with: - path: 'api-docs/_build/versioned/' - - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v4 \ No newline at end of file + DOCS_WRITE_TOKEN: ${{ steps.app.outputs.token }} + run: python scripts/promote_docs_release.py diff --git a/README.md b/README.md index 7407686e..49daf638 100644 --- a/README.md +++ b/README.md @@ -100,9 +100,11 @@ See the [`examples` directory](https://github.com/contentauth/c2pa-python/tree/m API documentation is published at [github.io/c2pa-python/api/c2pa](https://contentauth.github.io/c2pa-python/api/c2pa/index.html). -Use the documentation version dropdown to choose a published release. -The versions are selected in `api-docs/versions.json`; the first entry is the default at the existing documentation URL. -Publishing a stable GitHub release automatically adds its tag as the default while retaining older versions. +Use the documentation version dropdown to choose a retained major/minor line. +`api-docs/versions.json` selects one exact stable patch per line, in numeric descending order; +the highest line is the default at the existing documentation URL. +Once the documentation App is configured, stable releases advance retained lines or +introduce newer lines automatically. Maintenance releases never displace a newer default. To build documentation locally, see [Contributing to the project](https://github.com/contentauth/c2pa-python/blob/main/docs/project-contributions.md#api-reference-documentation). diff --git a/api-docs/_templates/version-selector.html b/api-docs/_templates/version-selector.html index 95d438cb..f38b229a 100644 --- a/api-docs/_templates/version-selector.html +++ b/api-docs/_templates/version-selector.html @@ -1,14 +1,15 @@ diff --git a/api-docs/conf.py b/api-docs/conf.py index d66a8d12..1dc16eb9 100644 --- a/api-docs/conf.py +++ b/api-docs/conf.py @@ -61,7 +61,7 @@ docs_prefix = os.environ.get("C2PA_DOCS_PREFIX", "") if docs_versions: release = docs_tag - version = docs_tag + version = ".".join(docs_tag.removeprefix("v").split(".")[:2]) html_sidebars = { "**": [ "sidebar/brand.html", @@ -108,7 +108,11 @@ def _add_version_selector(app, pagename, templatename, context, doctree): context["docs_versions"] = [ { "tag": tag, - "url": posixpath.relpath(f"versions/{tag}/index.html", current_directory), + "line": ".".join(tag.removeprefix("v").split(".")[:2]), + "url": posixpath.relpath( + "versions/" + ".".join(tag.removeprefix("v").split(".")[:2]) + "/index.html", + current_directory, + ), } for tag in docs_versions ] diff --git a/api-docs/versions.json b/api-docs/versions.json index 2c4b9d6f..1b9ba53d 100644 --- a/api-docs/versions.json +++ b/api-docs/versions.json @@ -1,11 +1,17 @@ { "versions": [ - "v0.39.0", - "v0.38.4", - "v0.38.3", - "v0.38.2", - "v0.38.1", - "v0.38.0", + "v0.39.0", + "v0.38.4", "v0.37.12" - ] + ], + "retiredLines": [], + "aliases": { + "v0.39.0": "0.39", + "v0.38.4": "0.38", + "v0.38.3": "0.38", + "v0.38.2": "0.38", + "v0.38.1": "0.38", + "v0.38.0": "0.38", + "v0.37.12": "0.37" + } } diff --git a/docs/project-contributions.md b/docs/project-contributions.md index 45613332..0dccdb89 100644 --- a/docs/project-contributions.md +++ b/docs/project-contributions.md @@ -158,12 +158,27 @@ This uses `sphinx-autoapi` to parse `src/c2pa` directly, avoiding imports of nat ### Versioned release documentation -Edit [api-docs/versions.json](../api-docs/versions.json) to choose the exact -GitHub release tags shown in the sidebar dropdown. Entries must be unique -tags such as `v0.38.0`. The first entry is the default served at the existing -documentation URL. When a stable GitHub release is published, the publishing -workflow prepends its tag and commits the updated list to `main` before building -the site. Older entries are retained; pre-releases are not automatically added. +[api-docs/versions.json](../api-docs/versions.json) is the publication policy: +`versions` selects one exact stable `vX.Y.Z` tag per retained major/minor line, +sorted numerically descending. The highest line is the root default. `aliases` +maps historical exact tags to unprefixed `X.Y` lines; every selected tag must +have an alias. `retiredLines` records lines automation must never restore. +The validator rejects empty selections, duplicate lines, prereleases, invalid +aliases, and active/retired overlap. + +On stable release publication, the standard-library-only promoter verifies +the release tag, event release ID, published timestamp and stable/draft flags. +It reconciles all published stable releases: retained lines advance to their +highest patch, and new lines are admitted only above every active or retired +line. It never backfills unlisted historical lines or regresses a patch/default. +Migration consolidates only the previously listed lines and preserves their +exact-tag aliases; it does not discover additional historical lines. + +To retire a line, submit a human PR removing its selected tag and every alias +targeting it, and add its unprefixed `X.Y` to `retiredLines`. Keep at least one +active line. To deliberately restore or backfill a historical line, use a human +PR with an exact published tag and matching aliases (remove its retirement +entry if applicable). Do not manually add a future, unpublished release tag. Fetch the release tags and build the complete site: @@ -186,15 +201,54 @@ API pages untouched. The complete site is written to `api-docs/_build/versioned/`: - The default version is also served at the root, preserving existing API URLs. -- Each selected release has a stable URL under `versions//`. -- Switching versions opens that release's documentation home page. +- Each line has a canonical URL under `versions/X.Y/`; the sidebar displays + `X.Y` and the page identifies its exact source patch. +- Historical `versions/vX.Y.Z/` HTML URLs redirect to equivalent canonical + pages, preserving nested suffixes, query strings and fragments. Removed pages + without an equivalent are not redirected to an unrelated API. +- Switching lines opens that line's documentation home page. - A regular `make docs` build remains an unversioned working-tree preview. -The publishing workflow always checks out `main` for the release list and -build tooling, including when triggered by a release. It rebuilds all selected -versions when a release is published, when relevant documentation files change -on `main`, or when manually dispatched. The workflow needs permission to push -the version-list commit to `main`, including under any branch protection rules. -The same release-triggered run builds and deploys the updated list; it does not -rely on the bot's push triggering another workflow. Publish manual changes to -the list on `main` to add, remove, or reorder dropdown entries. +The workflow uses current `main` tooling, never release-supplied scripts. +Promotion is an isolated job with no dependency installation or docs build. +Its only remote write is a Contents API compare-and-swap on the exact allowlisted +path `api-docs/versions.json` on `main`. Five bounded retries reread and recompute +against concurrent edits, without force pushes or lost unrelated main changes. +There is no promotion concurrency group to silently discard burst events; +release reconciliation also converges when releases arrive out of order. + +Organization administrators can share the documentation App across the SDK +repositories using the Actions organization variable `C2PA_DOCS_APP_ID` and +organization secret `C2PA_DOCS_APP_PRIVATE_KEY`. Grant both selected-repository +access to this repository; workflows read them as `vars.C2PA_DOCS_APP_ID` and +`secrets.C2PA_DOCS_APP_PRIVATE_KEY`. Repository-level values override organization +values, so remove stale repository overrides when adopting the shared credentials. +Install the App on each participating repository with Contents write permission, +and separately authorize it under each repository's applicable main +protection/ruleset. Configuring credentials alone does not grant installation +access or protection bypass. The workflow mints a short-lived, +repository-scoped installation token and fails explicitly if setup is absent. +It never falls back to the ordinary workflow token for protected-branch writes. +App permissions are repository-level, not path-level; the writer's fixed API +endpoint enforces its manifest-only allowlist. Do not expose this credential to +builds, dependency installation, pull requests or release source code. + +The separate `Deploy API docs` workflow starts explicitly on successful +completion of `Build and publish docs` (`workflow_run`); it does not depend on +the App push retriggering workflows. Relevant pushes to `main` and manual dispatch +still publish; App-push and workflow-completion publications may coalesce. +The complete build/deploy workflow is serialized, but checks out current `main` +only after admission, so coalescing pending publication events cannot discard +manifest updates. Failed upstream runs use isolated concurrency groups so they +cannot displace successful pending publications. Publishing never writes to the +repository, so it cannot create a push loop. The build remains read-only; only the separate deployment +job gets Pages write and OIDC permissions. Deployment rejects artifacts whose +source SHA no longer matches current `main`; rerun publication manually if an +unrelated main change superseded the latest build. No live deployment or +App/protection provisioning is part of local validation. + +Run the policy, promotion and generator tests with: + +```sh +python -m unittest tests.test_docs_versions tests.test_versioned_docs -v +``` diff --git a/scripts/docs_versions.py b/scripts/docs_versions.py new file mode 100644 index 00000000..df1694ae --- /dev/null +++ b/scripts/docs_versions.py @@ -0,0 +1,88 @@ +"""Stable release-line manifest policy (standard library only).""" + +import json +from pathlib import Path +import re + + +TAG_PATTERN = re.compile(r"v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") +LINE_PATTERN = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") + + +def version_key(tag: str) -> tuple[int, ...]: + if not isinstance(tag, str) or not TAG_PATTERN.fullmatch(tag): + raise ValueError(f"Expected an exact stable vX.Y.Z tag: {tag!r}") + return tuple(map(int, tag[1:].split("."))) + + +def release_line(tag: str) -> str: + major, minor, _ = version_key(tag) + return f"{major}.{minor}" + + +def validate_manifest(config: dict) -> dict: + if not isinstance(config, dict) or set(config) != {"versions", "retiredLines", "aliases"}: + raise ValueError("Manifest requires versions, retiredLines and aliases.") + versions, retired, aliases = ( + config["versions"], config["retiredLines"], config["aliases"] + ) + if not isinstance(versions, list) or not versions: + raise ValueError("Documentation versions must be a non-empty list.") + keys = [version_key(tag) for tag in versions] + lines = [release_line(tag) for tag in versions] + if len(set(lines)) != len(lines) or keys != sorted(keys, reverse=True): + raise ValueError("Select one patch per line in numeric descending order.") + if ( + not isinstance(retired, list) + or any(not isinstance(line, str) or not LINE_PATTERN.fullmatch(line) for line in retired) + or len(set(retired)) != len(retired) + or set(lines).intersection(retired) + ): + raise ValueError("Retired lines must be unique X.Y lines, disjoint from active lines.") + if not isinstance(aliases, dict): + raise ValueError("Aliases must map historical stable tags to active lines.") + for tag, line in aliases.items(): + if release_line(tag) != line or line not in lines: + raise ValueError(f"Invalid historical alias: {tag!r}: {line!r}") + selected = versions[lines.index(line)] + if version_key(tag) > version_key(selected): + raise ValueError("An alias cannot be newer than its selected release.") + if any(aliases.get(tag) != release_line(tag) for tag in versions): + raise ValueError("Every selected tag must also have a historical alias.") + return config + + +def load_manifest(path: Path) -> dict: + return validate_manifest(json.loads(path.read_text(encoding="utf-8"))) + + +def promote(config: dict, tag: str) -> dict: + """Advance a line, never regress it, resurrect it, or displace a newer default.""" + validate_manifest(config) + line = release_line(tag) + result = { + "versions": list(config["versions"]), + "retiredLines": list(config["retiredLines"]), + "aliases": dict(config["aliases"]), + } + if line in result["retiredLines"]: + return result + selected = next((item for item in result["versions"] if release_line(item) == line), None) + if selected is None: + known = [release_line(item) for item in result["versions"]] + result["retiredLines"] + if tuple(map(int, line.split("."))) <= max( + tuple(map(int, item.split("."))) for item in known + ): + return result + if selected and version_key(tag) <= version_key(selected): + return result + if selected: + result["versions"].remove(selected) + result["versions"].append(tag) + result["versions"].sort(key=version_key, reverse=True) + result["aliases"][tag] = line + return validate_manifest(result) + + +def serialize(config: dict) -> str: + return json.dumps(validate_manifest(config), indent=2) + "\n" diff --git a/scripts/generate_versioned_api_docs.py b/scripts/generate_versioned_api_docs.py index db2c4118..5cc34d6f 100644 --- a/scripts/generate_versioned_api_docs.py +++ b/scripts/generate_versioned_api_docs.py @@ -2,10 +2,11 @@ """Build a GitHub Pages site from the explicitly selected GitHub releases.""" import io +import html import json import os from pathlib import Path, PurePosixPath -import re +import posixpath import shutil import stat import subprocess @@ -15,23 +16,18 @@ import requests +if __package__: + from .docs_versions import load_manifest, release_line +else: + from docs_versions import load_manifest, release_line + ROOT = Path(__file__).resolve().parents[1] RELEASES_URL = "https://api.github.com/repos/contentauth/c2pa-python/releases/tags" -TAG_PATTERN = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9][A-Za-z0-9.-]*)?") def load_versions(path: Path) -> list[str]: - config = json.loads(path.read_text(encoding="utf-8")) - versions = config.get("versions") if isinstance(config, dict) else None - if not isinstance(versions, list) or not versions: - raise ValueError("Documentation versions must be a non-empty list.") - for tag in versions: - if not isinstance(tag, str) or not TAG_PATTERN.fullmatch(tag): - raise ValueError("Documentation versions must be release tags such as v0.38.0.") - if len(set(versions)) != len(versions): - raise ValueError("Documentation versions must not contain duplicate tags.") - return versions + return load_manifest(path)["versions"] def verify_release(tag: str) -> None: @@ -51,6 +47,8 @@ def verify_release(tag: str) -> None: not isinstance(release, dict) or release.get("tag_name") != tag or release.get("draft") is not False + or release.get("prerelease") is not False + or not release.get("published_at") ): raise ValueError(f"{tag} is not a published GitHub release.") @@ -90,9 +88,29 @@ def export_sources(root: Path, tag: str, destination: Path) -> None: raise ValueError(f"Release {tag} contains no Python API sources.") +def write_aliases(site: Path, aliases: dict[str, str]) -> None: + for alias, line in aliases.items(): + target = site / "versions" / line + for page in target.rglob("*.html"): + suffix = page.relative_to(target) + legacy = site / "versions" / alias / suffix + legacy.parent.mkdir(parents=True, exist_ok=True) + url = posixpath.relpath(page.as_posix(), legacy.parent.as_posix()) + legacy.write_text( + 'Documentation moved' + f'' + f'Continue to {line}' + '', + encoding="utf-8", + ) + + def build_site() -> Path: docs = ROOT / "api-docs" - versions = load_versions(docs / "versions.json") + manifest = load_manifest(docs / "versions.json") + versions = manifest["versions"] for tag in versions: verify_release(tag) @@ -119,14 +137,14 @@ def build_site() -> Path: environment.update( C2PA_DOCS_TAG=tag, C2PA_DOCS_VERSIONS=json.dumps(versions), - C2PA_DOCS_PREFIX=f"versions/{tag}", + C2PA_DOCS_PREFIX=f"versions/{release_line(tag)}", ) subprocess.run( [sys.executable, str(scripts / "generate_api_docs.py")], cwd=stage, env=environment, check=True, ) html = stage / "api-docs" / "_build" / "html" - shutil.copytree(html, site / "versions" / tag) + shutil.copytree(html, site / "versions" / release_line(tag)) # Rebuild the default at the root so all switcher links remain relative. default = workspace / versions[0] @@ -139,6 +157,7 @@ def build_site() -> Path: shutil.copytree( default / "api-docs" / "_build" / "html", site, dirs_exist_ok=True ) + write_aliases(site, manifest["aliases"]) (site / ".nojekyll").touch() if output.exists(): shutil.rmtree(output) diff --git a/scripts/promote_docs_release.py b/scripts/promote_docs_release.py new file mode 100644 index 00000000..dc7480af --- /dev/null +++ b/scripts/promote_docs_release.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Promote a published release through an optimistic, manifest-only Contents PUT.""" + +import base64 +import json +import os +import time +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import Request, urlopen + +if __package__: + from .docs_versions import TAG_PATTERN, promote, serialize, validate_manifest, version_key +else: + from docs_versions import TAG_PATTERN, promote, serialize, validate_manifest, version_key + + +MANIFEST_PATH = "api-docs/versions.json" + + +def api(method: str, path: str, token: str, data=None): + request = Request( + f"https://api.github.com/repos/contentauth/c2pa-python/{path}", + data=None if data is None else json.dumps(data).encode(), + headers={ + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + method=method, + ) + with urlopen(request, timeout=30) as response: + return json.load(response) + + +def promote_release(tag: str, release_id: str, read_token: str, write_token: str) -> None: + version_key(tag) + release = api("GET", f"releases/tags/{quote(tag, safe='')}", read_token) + if ( + release.get("tag_name") != tag + or str(release.get("id")) != release_id + or release.get("draft") is not False + or release.get("prerelease") is not False + or not release.get("published_at") + ): + raise ValueError("Release metadata does not identify a published stable release.") + tags = {tag} + page = 1 + while True: + releases = api("GET", f"releases?per_page=100&page={page}", read_token) + if not isinstance(releases, list): + raise ValueError("GitHub releases response must be a list.") + for item in releases: + candidate = item.get("tag_name") + if ( + isinstance(candidate, str) + and TAG_PATTERN.fullmatch(candidate) + and item.get("draft") is False + and item.get("prerelease") is False + and item.get("published_at") + ): + tags.add(candidate) + if len(releases) < 100: + break + page += 1 + for attempt in range(5): + current = api("GET", f"contents/{MANIFEST_PATH}?ref=main", read_token) + config = validate_manifest(json.loads(base64.b64decode(current["content"]))) + updated = config + for candidate in sorted(tags, key=version_key): + updated = promote(updated, candidate) + if updated == config: + print(f"No promotion needed for {tag} or other published stable releases.") + return + try: + api("PUT", f"contents/{MANIFEST_PATH}", write_token, { + "branch": "main", + "sha": current["sha"], + "message": f"docs: promote {tag} [docs-promotion]", + "content": base64.b64encode(serialize(updated).encode()).decode(), + }) + return + except HTTPError as error: + if error.code not in (409, 422) or attempt == 4: + raise + time.sleep(attempt + 1) + raise RuntimeError("Manifest promotion exhausted concurrent-update retries.") + + +if __name__ == "__main__": + promote_release( + os.environ["RELEASE_TAG"], os.environ["RELEASE_ID"], + os.environ["GITHUB_TOKEN"], os.environ["DOCS_WRITE_TOKEN"], + ) diff --git a/tests/test_docs_versions.py b/tests/test_docs_versions.py new file mode 100644 index 00000000..ba39a4c7 --- /dev/null +++ b/tests/test_docs_versions.py @@ -0,0 +1,189 @@ +import base64 +import copy +import json +import unittest +from unittest.mock import patch +from urllib.error import HTTPError + +from scripts.docs_versions import promote, validate_manifest +from scripts import promote_docs_release as writer + + +def selection(): + return { + "versions": ["v1.10.2", "v1.9.4"], + "retiredLines": ["0.38"], + "aliases": {"v1.10.2": "1.10", "v1.9.4": "1.9", "v1.9.0": "1.9"}, + } + + +class DocsVersionTests(unittest.TestCase): + def test_patch_promotion_is_idempotent_and_preserves_aliases(self): + original = selection() + updated = promote(original, "v1.9.5") + self.assertEqual(updated["versions"], ["v1.10.2", "v1.9.5"]) + self.assertEqual(updated["aliases"]["v1.9.4"], "1.9") + self.assertEqual(updated["aliases"]["v1.9.5"], "1.9") + self.assertEqual(promote(updated, "v1.9.5"), updated) + self.assertEqual(promote(updated, "v1.9.3"), updated) + self.assertEqual(original, selection()) + + def test_new_lines_sort_numerically_without_resurrecting_retired_lines(self): + self.assertEqual(promote(selection(), "v0.38.99"), selection()) + self.assertEqual( + promote(selection(), "v2.0.0")["versions"], + ["v2.0.0", "v1.10.2", "v1.9.4"], + ) + self.assertEqual(promote(selection(), "v1.8.9"), selection()) + retired_future = selection() + retired_future["retiredLines"].append("3.0") + self.assertEqual(promote(retired_future, "v2.0.0"), retired_future) + + def test_invalid_manifests_and_release_tags_fail(self): + bad = [] + for versions in [ + [], ["v1.9.4", "v1.10.2"], ["v1.10.2", "v1.10.1"], + ["v1.0.0-rc.1"], ["v01.0.0"], ["1.0.0"], [None], + ]: + config = selection() + config["versions"] = versions + bad.append(config) + for field, value in [ + ("retiredLines", ["1.10"]), ("retiredLines", ["0.38", "0.38"]), + ("retiredLines", ["v0.38"]), ("retiredLines", "0.38"), + ("aliases", []), ("aliases", {"../escape": "1.9"}), + ("aliases", {"v1.9.4": "1.10"}), ("aliases", {"v0.38.0": "0.38"}), + ("aliases", {"v1.9.5": "1.9"}), ("aliases", {}), + ]: + config = selection() + config[field] = value + bad.append(config) + for config in bad: + with self.subTest(config=config), self.assertRaises(ValueError): + validate_manifest(config) + for tag in ["v2.0.0-rc.1", "v2.0.0+build", "../main"]: + with self.subTest(tag=tag), self.assertRaises(ValueError): + promote(selection(), tag) + + @patch.object(writer, "api") + @patch.object(writer.time, "sleep") + def test_conflict_recomputes_from_live_manifest_and_only_writes_allowlisted_file(self, sleep, api): + concurrent = promote(selection(), "v2.0.0") + + def encoded(config, sha): + return {"content": base64.b64encode(json.dumps(config).encode()).decode(), "sha": sha} + + conflict = HTTPError("url", 409, "conflict", {}, None) + self.addCleanup(conflict.close) + api.side_effect = [ + {"id": 123, "tag_name": "v1.9.5", "draft": False, + "prerelease": False, "published_at": "2026-01-01"}, + [], + encoded(selection(), "first"), + conflict, + encoded(concurrent, "second"), + {"commit": {"sha": "committed"}}, + ] + writer.promote_release("v1.9.5", "123", "read", "write") + writes = [call for call in api.call_args_list if call.args[0] == "PUT"] + self.assertEqual(len(writes), 2) + for call in writes: + self.assertEqual(call.args[1:3], ("contents/api-docs/versions.json", "write")) + payload = writes[-1].args[3] + self.assertEqual(payload["sha"], "second") + self.assertEqual(payload["branch"], "main") + updated = json.loads(base64.b64decode(payload["content"])) + self.assertEqual(updated["versions"], ["v2.0.0", "v1.10.2", "v1.9.5"]) + + @patch.object(writer, "api") + def test_release_metadata_must_match_event_before_any_manifest_access(self, api): + valid = {"id": 123, "tag_name": "v1.9.5", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + for key, value in [ + ("id", 456), ("tag_name", "v1.9.4"), ("draft", True), + ("prerelease", True), ("published_at", None), + ]: + release = copy.deepcopy(valid) + release[key] = value + api.reset_mock() + api.return_value = release + with self.subTest(key=key), self.assertRaises(ValueError): + writer.promote_release("v1.9.5", "123", "read", "write") + self.assertEqual(api.call_count, 1) + + @patch.object(writer, "api") + @patch.object(writer.time, "sleep") + def test_retries_are_bounded_and_permission_errors_fail_immediately(self, sleep, api): + release = {"id": 123, "tag_name": "v1.9.5", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + current = {"content": base64.b64encode(json.dumps(selection()).encode()).decode(), "sha": "sha"} + for code, attempts in [(403, 1), (409, 5)]: + api.reset_mock() + error = HTTPError("url", code, "failure", {}, None) + self.addCleanup(error.close) + api.side_effect = [release, []] + [item for _ in range(attempts) for item in (current, error)] + with self.subTest(code=code), self.assertRaises(HTTPError): + writer.promote_release("v1.9.5", "123", "read", "write") + self.assertEqual(api.call_count, 2 + attempts * 2) + + @patch.object(writer, "api") + def test_release_burst_reconciliation_preserves_selection_and_ignores_historical_lines(self, api): + release = {"id": 123, "tag_name": "v1.9.5", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + releases = [ + dict(release, tag_name=tag) for tag in + ["v1.9.6", "v2.0.0", "v2.0.1", "v1.8.7", "v0.38.99", "v3.0.0-rc.1"] + ] + releases.append(dict(release, tag_name="v4.0.0", prerelease=True)) + current = {"content": base64.b64encode(json.dumps(selection()).encode()).decode(), "sha": "sha"} + api.side_effect = [release, releases, current, {}] + writer.promote_release("v1.9.5", "123", "read", "write") + payload = api.call_args_list[-1].args[3] + updated = json.loads(base64.b64decode(payload["content"])) + self.assertEqual(updated["versions"], ["v2.0.1", "v1.10.2", "v1.9.6"]) + self.assertNotIn("v1.8.7", updated["aliases"]) + + @patch.object(writer, "api") + def test_unchanged_reconciliation_never_writes(self, api): + release = {"id": 123, "tag_name": "v1.9.4", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + current = {"content": base64.b64encode(json.dumps(selection()).encode()).decode(), "sha": "sha"} + api.side_effect = [release, [], current] + writer.promote_release("v1.9.4", "123", "read", "write") + self.assertEqual(api.call_count, 3) + + @patch.object(writer, "api") + def test_release_reconciliation_reads_all_pages(self, api): + release = {"id": 123, "tag_name": "v1.9.4", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + current = {"content": base64.b64encode(json.dumps(selection()).encode()).decode(), "sha": "sha"} + api.side_effect = [ + release, [release] * 100, [dict(release, tag_name="v2.0.0")], current, {}, + ] + writer.promote_release("v1.9.4", "123", "read", "write") + self.assertEqual(api.call_args_list[2].args[1], "releases?per_page=100&page=2") + updated = json.loads(base64.b64decode(api.call_args_list[-1].args[3]["content"])) + self.assertEqual(updated["versions"][0], "v2.0.0") + + @patch.object(writer, "api") + @patch.object(writer.time, "sleep") + def test_concurrent_human_retirement_is_not_reversed(self, sleep, api): + release = {"id": 123, "tag_name": "v1.9.5", "draft": False, + "prerelease": False, "published_at": "2026-01-01"} + retired = selection() + retired["versions"].remove("v1.9.4") + retired["retiredLines"].append("1.9") + retired["aliases"] = {"v1.10.2": "1.10"} + + def encoded(config): + return {"content": base64.b64encode(json.dumps(config).encode()).decode(), "sha": "sha"} + + conflict = HTTPError("url", 409, "conflict", {}, None) + self.addCleanup(conflict.close) + api.side_effect = [release, [], encoded(selection()), conflict, encoded(retired)] + writer.promote_release("v1.9.5", "123", "read", "write") + self.assertEqual(sum(call.args[0] == "PUT" for call in api.call_args_list), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_versioned_docs.py b/tests/test_versioned_docs.py index abff04af..b2529d5d 100644 --- a/tests/test_versioned_docs.py +++ b/tests/test_versioned_docs.py @@ -12,13 +12,21 @@ import zipfile from scripts import generate_versioned_api_docs as docs +from scripts.docs_versions import release_line + + +def manifest(versions): + return { + "versions": versions, "retiredLines": [], + "aliases": {tag: release_line(tag) for tag in versions}, + } class VersionedDocsTests(unittest.TestCase): def test_version_list_preserves_default_and_order(self): with tempfile.TemporaryDirectory() as directory: config = Path(directory) / "versions.json" - config.write_text('{"versions": ["v0.38.0", "v0.37.0"]}') + config.write_text(json.dumps(manifest(["v0.38.0", "v0.37.0"]))) self.assertEqual(docs.load_versions(config), ["v0.38.0", "v0.37.0"]) def test_invalid_versions_are_rejected(self): @@ -30,7 +38,9 @@ def test_invalid_versions_are_rejected(self): config = Path(directory) / "versions.json" for versions in invalid: with self.subTest(versions=versions): - config.write_text(json.dumps({"versions": versions})) + config.write_text(json.dumps({ + "versions": versions, "retiredLines": [], "aliases": {}, + })) with self.assertRaises(ValueError): docs.load_versions(config) for value in [[], {}, {"versions": "v0.38.0"}]: @@ -43,7 +53,10 @@ def test_invalid_versions_are_rejected(self): def test_published_release_is_verified(self, get): get.return_value = Mock( status_code=200, - json=Mock(return_value={"tag_name": "v0.38.0", "draft": False}), + json=Mock(return_value={ + "tag_name": "v0.38.0", "draft": False, "prerelease": False, + "published_at": "2026-01-01T00:00:00Z", + }), ) docs.verify_release("v0.38.0") get.assert_called_once_with( @@ -123,7 +136,7 @@ def test_unsafe_or_empty_source_archives_fail(self, run): def test_switcher_links_resolve_from_root_and_nested_version_pages(self): versions = ["v0.38.0", "v0.37.0"] - for prefix in ["", "versions/v0.38.0", "versions/v0.37.0"]: + for prefix in ["", "versions/0.38", "versions/0.37"]: with self.subTest(prefix=prefix), patch.dict( os.environ, { @@ -140,7 +153,7 @@ def test_switcher_links_resolve_from_root_and_nested_version_pages(self): for item in context["docs_versions"]: self.assertEqual( posixpath.normpath(posixpath.join(parent, item["url"])), - f"versions/{item['tag']}/index.html", + f"versions/{item['line']}/index.html", ) @patch.dict(os.environ, {}, clear=True) @@ -167,7 +180,7 @@ def build(*args, cwd, env, **kwargs): root = Path(directory) (root / "api-docs").mkdir() (root / "api-docs/versions.json").write_text( - '{"versions": ["v0.38.0", "v0.37.0"]}' + json.dumps(manifest(["v0.38.0", "v0.37.0"])) ) (root / "scripts").mkdir() (root / "scripts/generate_api_docs.py").touch() @@ -176,8 +189,8 @@ def build(*args, cwd, env, **kwargs): self.assertEqual((site / "index.html").read_text(), "v0.38.0:") for tag in ["v0.38.0", "v0.37.0"]: self.assertEqual( - (site / "versions" / tag / "index.html").read_text(), - f"{tag}:versions/{tag}", + (site / "versions" / release_line(tag) / "index.html").read_text(), + f"{tag}:versions/{release_line(tag)}", ) self.assertTrue((site / ".nojekyll").is_file()) self.assertEqual(list((root / "api-docs/_build").iterdir()), [site]) @@ -195,7 +208,9 @@ def test_failed_build_leaves_previous_site_intact(self, run, export, verify): site = root / "api-docs/_build/versioned" site.mkdir(parents=True) (site / "index.html").write_text("previous site") - (root / "api-docs/versions.json").write_text('{"versions": ["v0.38.0"]}') + (root / "api-docs/versions.json").write_text( + json.dumps(manifest(["v0.38.0"])) + ) (root / "scripts").mkdir() (root / "scripts/generate_api_docs.py").touch() with patch.object(docs, "ROOT", root): @@ -204,6 +219,19 @@ def test_failed_build_leaves_previous_site_intact(self, run, export, verify): self.assertEqual((site / "index.html").read_text(), "previous site") self.assertEqual(list((root / "api-docs/_build").iterdir()), [site]) + def test_legacy_html_redirects_preserve_equivalent_suffix_and_fragment(self): + with tempfile.TemporaryDirectory() as directory: + site = Path(directory) + page = site / "versions/0.38/api/c2pa/index.html" + page.parent.mkdir(parents=True) + page.write_text("current") + docs.write_aliases(site, {"v0.38.1": "0.38"}) + redirect = site / "versions/v0.38.1/api/c2pa/index.html" + text = redirect.read_text() + self.assertIn("../../../0.38/api/c2pa/index.html", text) + self.assertIn("+location.search+location.hash", text) + self.assertFalse((redirect.parent / "removed.html").exists()) + if __name__ == "__main__": unittest.main() From a1c588c17c63a19c613a98d625ca652a77f28304 Mon Sep 17 00:00:00 2001 From: Rand McKinney Date: Mon, 30 Nov 2026 13:04:02 -0800 Subject: [PATCH 3/3] chore: refresh PR comparison Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>