diff --git a/.github/scripts/deploy_docs.py b/.github/scripts/deploy_docs.py new file mode 100644 index 000000000..e0c66603d --- /dev/null +++ b/.github/scripts/deploy_docs.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Publish release docs without downgrading a minor version or the latest alias.""" + +import argparse +from dataclasses import dataclass +import json +from pathlib import Path +import re +import subprocess + + +NUMBER = r"(?:0|[1-9][0-9]*)" +STABLE = re.compile(rf"({NUMBER})\.({NUMBER})\.({NUMBER})") +MINOR = re.compile(rf"({NUMBER})\.({NUMBER})") +PRERELEASE_ID = rf"(?:{NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)" +PRERELEASE = re.compile( + rf"{NUMBER}\.{NUMBER}\.{NUMBER}-{PRERELEASE_ID}(?:\.{PRERELEASE_ID})*" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" +) + + +@dataclass(frozen=True) +class Deployment: + version: str + latest: bool + + +def stable_version(tag): + match = STABLE.fullmatch(tag) + if match is None: + raise ValueError(f"expected a stable major.minor.patch release, got {tag!r}") + return tuple(map(int, match.groups())) + + +def published_releases(versions): + if not isinstance(versions, list): + raise ValueError("versions.json must contain a list") + releases = [] + latest_count = 0 + for entry in versions: + version = entry["version"] + if STABLE.fullmatch(version): + # Existing patch snapshots predate the release property. + release = stable_version(version) + elif MINOR.fullmatch(version): + tag = entry.get("properties", {}).get("release") + if not isinstance(tag, str): + raise ValueError(f"minor snapshot {version!r} has no release property") + release = stable_version(tag) + if version != f"{release[0]}.{release[1]}": + raise ValueError(f"minor snapshot {version!r} has mismatched release {tag!r}") + else: + release = None + if "latest" in entry["aliases"]: + latest_count += 1 + if release is None: + raise ValueError("latest must point to stable release documentation") + if release is not None: + releases.append(release) + if latest_count > 1: + raise ValueError("versions.json has multiple latest aliases") + return releases + + +def plan_deployment(tag, prerelease, versions): + releases = published_releases(versions) + if prerelease: + if PRERELEASE.fullmatch(tag) is None: + raise ValueError("prerelease tags must use major.minor.patch-prerelease") + return Deployment(tag, False) + + release = stable_version(tag) + if any(other[:2] == release[:2] and other > release for other in releases): + return None + return Deployment( + f"{release[0]}.{release[1]}", + not releases or release >= max(releases), + ) + + +def stamp_docs(version, docs=Path("docs/operator-public-documentation")): + if not (STABLE.fullmatch(version) or PRERELEASE.fullmatch(version)): + raise ValueError(f"expected a full release version, got {version!r}") + for path in docs.rglob("*.md"): + text = path.read_text(encoding="utf-8") + if "" in text: + path.write_text(text.replace("", version), encoding="utf-8") + + +def deploy(tag, prerelease): + # Read state after acquiring the workflow's shared Pages deployment lock. + subprocess.run(["git", "fetch", "origin", "gh-pages"], check=True) + versions = json.loads( + subprocess.check_output( + ["git", "show", "origin/gh-pages:versions.json"], text=True + ) + ) + plan = plan_deployment(tag, prerelease, versions) + if plan is None: + print(f"Skipping {tag}: a newer patch is already published for this minor.") + return + command = [ + "mike", "deploy", plan.version, "--title", plan.version, + "--prop-set-string", f"release={tag}", + ] + if plan.latest: + command.extend(["latest", "--update-aliases"]) + subprocess.run(command, check=True) + if plan.latest: + subprocess.run(["mike", "set-default", "latest"], check=True) + # Publish content, provenance, aliases and the default redirect together. + subprocess.run(["git", "push", "origin", "gh-pages"], check=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + stamp = commands.add_parser("stamp", help="Stamp full installation versions") + stamp.add_argument("--version", required=True) + publish = commands.add_parser("deploy", help="Publish release documentation") + publish.add_argument("--tag", required=True) + publish.add_argument("--prerelease", required=True, choices=("true", "false")) + args = parser.parse_args() + try: + if args.command == "stamp": + stamp_docs(args.version) + else: + deploy(args.tag, args.prerelease == "true") + except ValueError as error: + parser.error(str(error)) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/deploy_docs_test.py b/.github/scripts/deploy_docs_test.py new file mode 100644 index 000000000..5baa34f08 --- /dev/null +++ b/.github/scripts/deploy_docs_test.py @@ -0,0 +1,224 @@ +from contextlib import chdir, redirect_stdout +from io import StringIO +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +from deploy_docs import Deployment, deploy, main, plan_deployment, stamp_docs + + +def snapshot(version, release=None, aliases=()): + entry = {"version": version, "title": version, "aliases": list(aliases)} + if release is not None: + entry["properties"] = {"release": release} + return entry + + +class DeploymentPolicyTests(unittest.TestCase): + def test_stable_minor_path_and_numeric_ordering(self): + versions = [snapshot("1.1", "1.1.9", ("latest",))] + self.assertEqual( + plan_deployment("1.1.10", False, versions), Deployment("1.1", True) + ) + self.assertEqual( + plan_deployment("1.10.0", False, versions), Deployment("1.10", True) + ) + + def test_old_patch_skipped_and_equal_patch_can_be_repaired(self): + for entry in (snapshot("1.1", "1.1.10"), snapshot("1.1.10")): + with self.subTest(entry=entry): + self.assertIsNone(plan_deployment("1.1.2", False, [entry])) + self.assertEqual( + plan_deployment("1.1.10", False, [entry]), + Deployment("1.1", True), + ) + + def test_older_minor_cannot_take_latest_even_without_an_alias(self): + for entry in (snapshot("1.2", "1.2.0"), snapshot("1.2.0")): + with self.subTest(entry=entry): + self.assertEqual( + plan_deployment("1.1.12", False, [entry]), + Deployment("1.1", False), + ) + + def test_prereleases_remain_separate_and_do_not_affect_stable_ordering(self): + versions = [ + snapshot("dev"), + snapshot("1.0-rc1"), + snapshot("2.0.0-rc.1", "2.0.0-rc.1"), + ] + self.assertEqual( + plan_deployment("2.0.0-rc.2", True, versions), + Deployment("2.0.0-rc.2", False), + ) + self.assertEqual( + plan_deployment("1.1.2", False, versions), Deployment("1.1", True) + ) + + def test_rejects_bad_tags_and_mislabeled_prereleases(self): + for tag, prerelease in ( + ("", False), ("1.1", False), ("v1.1.2", False), + ("01.1.2", False), ("1.1.2-rc.1", False), + ("1.1.2+build", False), ("1.1.2", True), + ("dev", True), ("1.1.2-01", True), + ): + with self.subTest(tag=tag, prerelease=prerelease): + with self.assertRaises(ValueError): + plan_deployment(tag, prerelease, []) + + def test_unknown_or_inconsistent_minor_provenance_fails_closed(self): + for entry in ( + snapshot("1.1"), snapshot("1.1", "1.2.0"), + snapshot("1.1", "1.1.2-rc.1"), + ): + with self.subTest(entry=entry): + with self.assertRaises(ValueError): + plan_deployment("1.1.2", False, [entry]) + + def test_invalid_latest_state_fails_closed(self): + for versions in ( + [snapshot("dev", aliases=("latest",))], + [snapshot("2.0.0-rc.1", aliases=("latest",))], + [snapshot("1.1.1", aliases=("latest",)), + snapshot("1.2.0", aliases=("latest",))], + ): + with self.subTest(versions=versions): + with self.assertRaises(ValueError): + plan_deployment("1.1.2", False, versions) + + def test_bad_prerelease_flag_fails_before_accessing_published_state(self): + with ( + patch("sys.argv", [ + "deploy_docs.py", "deploy", "--tag", "1.1.2", "--prerelease", "yes", + ]), + patch("sys.stderr", new=StringIO()), + patch("deploy_docs.subprocess.run") as run, + ): + with self.assertRaises(SystemExit) as error: + main() + self.assertEqual(error.exception.code, 2) + run.assert_not_called() + + def test_stamp_preserves_full_release_for_install_and_crd_urls(self): + with tempfile.TemporaryDirectory() as directory: + docs = Path(directory) + page = docs / "install.md" + template = ( + "helm install documentdb --version \n" + "https://raw.githubusercontent.com/documentdb/" + "documentdb-kubernetes-operator//" + "operator/documentdb-helm-chart/crds/documentdb.io_documentdbs.yaml\n" + ) + for version in ("1.1.2", "1.2.0-rc.1"): + page.write_text(template, encoding="utf-8") + stamp_docs(version, docs) + self.assertEqual( + page.read_text(encoding="utf-8"), + template.replace("", version), + ) + with self.assertRaises(ValueError): + stamp_docs("1.1", docs) + + +class MikeDeploymentTests(unittest.TestCase): + """Exercise the real mike CLI against a disposable local remote, never GitHub.""" + + def run_command(self, *command): + result = subprocess.run( + command, cwd=self.repo, env=self.env, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ) + if result.returncode: + self.fail(f"{command!r} failed:\n{result.stdout}") + return result.stdout.strip() + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + self.repo = root / "repo" + self.repo.mkdir() + self.env = { + **os.environ, + "GIT_AUTHOR_NAME": "Docs test", + "GIT_AUTHOR_EMAIL": "docs@example.invalid", + "GIT_COMMITTER_NAME": "Docs test", + "GIT_COMMITTER_EMAIL": "docs@example.invalid", + } + self.run_command("git", "init", "--bare", str(root / "remote.git")) + self.run_command("git", "init", "-b", "main") + self.run_command("git", "remote", "add", "origin", str(root / "remote.git")) + (self.repo / "mkdocs.yml").write_text( + "site_name: Test\nextra:\n version:\n provider: mike\n", + encoding="utf-8", + ) + self.docs = self.repo / "docs" + self.docs.mkdir() + self.page = self.docs / "index.md" + self.page.write_text("# Legacy patch snapshot\n", encoding="utf-8") + self.run_command("git", "add", ".") + self.run_command("git", "commit", "-m", "Test fixture") + self.run_command("mike", "deploy", "1.1.1", "latest", "--push") + self.run_command("mike", "set-default", "latest", "--push") + + def versions(self): + return json.loads( + self.run_command("git", "show", "origin/gh-pages:versions.json") + ) + + def publish(self, tag, prerelease=False): + self.page.write_text( + "# Release docs\n\nhelm install documentdb --version \n", + encoding="utf-8", + ) + stamp_docs(tag, self.docs) + with chdir(self.repo), patch.dict(os.environ, self.env): + with redirect_stdout(StringIO()): + deploy(tag, prerelease) + + def test_publication_order_aliases_and_legacy_urls(self): + legacy = self.run_command("git", "rev-parse", "origin/gh-pages:1.1.1") + self.publish("1.1.2") + self.assertIn(snapshot("1.1", "1.1.2", ("latest",)), self.versions()) + html = self.run_command("git", "show", "origin/gh-pages:1.1/index.html") + self.assertIn("--version 1.1.2", html) + + self.publish("1.1.10") + newest = self.run_command("git", "rev-parse", "origin/gh-pages") + self.publish("1.1.3") + self.assertEqual( + self.run_command("git", "rev-parse", "origin/gh-pages"), newest + ) + latest_redirect = self.run_command("git", "show", "origin/gh-pages:index.html") + self.publish("2.0.0-rc.1", prerelease=True) + self.publish("1.0.5") + self.assertIn(snapshot("1.1", "1.1.10", ("latest",)), self.versions()) + self.assertIn(snapshot("1.0", "1.0.5"), self.versions()) + self.assertIn(snapshot("2.0.0-rc.1", "2.0.0-rc.1"), self.versions()) + self.assertEqual( + self.run_command("git", "show", "origin/gh-pages:index.html"), + latest_redirect, + ) + + self.publish("1.2.0") + self.publish("1.1.11") + self.run_command("mike", "deploy", "dev", "--push") + versions = self.versions() + self.assertIn(snapshot("1.2", "1.2.0", ("latest",)), versions) + self.assertIn(snapshot("1.1", "1.1.11"), versions) + self.assertIn(snapshot("dev"), versions) + self.assertIn(snapshot("1.1.1"), versions) + self.assertEqual( + self.run_command("git", "rev-parse", "origin/gh-pages:1.1.1"), legacy + ) + self.assertEqual( + self.run_command("git", "show", "origin/gh-pages:latest"), "1.2" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/deploy_docs.yml b/.github/workflows/deploy_docs.yml index d72b80a50..4f0bc9175 100644 --- a/.github/workflows/deploy_docs.yml +++ b/.github/workflows/deploy_docs.yml @@ -1,45 +1,48 @@ -name: Deploy Versioned Docs -on: - workflow_dispatch: - push: - branches: - - main - paths: - - 'docs/**' - - 'mkdocs.yml' - release: - types: [published, released] - -permissions: - contents: write - -jobs: - deploy-docs: - # A full release fires "published" and "released" and only "released" deploys it. Skipping the - # other run keeps it out of the queue, where it would replace a pending deploy. - if: github.event_name != 'release' || github.event.action == 'released' || github.event.release.prerelease - # Allow only one concurrent deployment - concurrency: - group: "pages" - cancel-in-progress: false - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - uses: actions/setup-python@v5 - with: - python-version: 3.x - - - name: Install dependencies - run: pip install "mkdocs-material==9.5.19" "mike==2.1.3" "mkdocs-redirects==1.2.2" - - - name: Configure Git for mike - run: | - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - +name: Deploy Versioned Docs +on: + workflow_dispatch: + push: + branches: + - main + paths: + - 'docs/**' + - 'mkdocs.yml' + - '.github/scripts/*docs*.py' + - '.github/workflows/deploy_docs.yml' + release: + types: [published, released] + +permissions: + contents: write + +jobs: + deploy-docs: + # A full release fires "published" and "released" and only "released" deploys it. Skipping the + # other run keeps it out of the queue, where it would replace a pending deploy. + if: github.event_name != 'release' || github.event.action == 'released' || github.event.release.prerelease + # Serialize reads of published release metadata with all Pages writes. + # The release helper also guards against out-of-order runs; this is not a FIFO queue. + concurrency: + group: "pages" + cancel-in-progress: false + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: 3.x + + - name: Install dependencies + run: pip install "mkdocs-material==9.5.19" "mike==2.1.3" "mkdocs-redirects==1.2.2" + + - name: Configure Git for mike + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + # Release tags must be chart versions: the docs stamp the tag into `helm --version` and CRD URLs. - name: Check release tag matches chart version if: github.event_name == 'release' @@ -57,43 +60,38 @@ jobs: if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') run: | CHART_VERSION=$(sed -nE 's/^version:[[:space:]]*"?([^"[:space:]]+)"?.*/\1/p' operator/documentdb-helm-chart/Chart.yaml) - find docs/operator-public-documentation -name '*.md' -exec sed -i "s||${CHART_VERSION}|g" {} + + python .github/scripts/deploy_docs.py stamp --version "$CHART_VERSION" - name: Stamp release version into docs if: github.event_name == 'release' + env: + VERSION: ${{ github.event.release.tag_name }} + run: | + python .github/scripts/deploy_docs.py stamp --version "$VERSION" + + - name: Check documentation entrypoints before publishing run: | - VERSION=${{ github.event.release.tag_name }} - find docs/operator-public-documentation -name '*.md' -exec sed -i "s||${VERSION}|g" {} + + python -m unittest discover -s .github/scripts -p '*_test.py' + mkdocs build + python .github/scripts/check_doc_links.py --site-dir site - - name: Check documentation entrypoints before publishing - run: | - python -m unittest discover -s .github/scripts -p '*_test.py' - mkdocs build - python .github/scripts/check_doc_links.py --site-dir site - - # On push to main: deploy as "dev" version - - name: Deploy dev docs - if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') - run: mike deploy dev --push --update-aliases - - # On release: deploy versioned docs and update "latest" alias - # "released" also fires when a prerelease is later marked as a release. + # On push to main: deploy as "dev" version + - name: Deploy dev docs + if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + run: mike deploy dev --push --update-aliases + + # Stable releases update /major.minor/; install commands retain the full tag above. + # Prereleases use their full tag, never the stable minor or latest. + # "released" also fires on promotion, but a prerelease tag is not a stable chart version. - name: Deploy release docs if: github.event_name == 'release' env: - ACTION: ${{ github.event.action }} + TAG: ${{ github.event.release.tag_name }} PRERELEASE: ${{ github.event.release.prerelease }} run: | - VERSION=${{ github.event.release.tag_name }} - # A prerelease must not take over the "latest" docs that external links point at. - if [[ "$ACTION" == "published" && "$PRERELEASE" == "true" ]]; then - mike deploy ${VERSION} --push - elif [[ "$ACTION" == "released" ]]; then - mike deploy ${VERSION} latest --push --update-aliases - mike set-default latest --push - fi - - - name: Verify published stable documentation links - if: github.event_name == 'release' && github.event.action == 'released' && !github.event.release.prerelease - timeout-minutes: 5 - run: python .github/scripts/check_doc_links.py --attempts 12 + python .github/scripts/deploy_docs.py deploy --tag "$TAG" --prerelease "$PRERELEASE" + + - name: Verify published stable documentation links + if: github.event_name == 'release' && github.event.action == 'released' && !github.event.release.prerelease + timeout-minutes: 5 + run: python .github/scripts/check_doc_links.py --attempts 12 diff --git a/.github/workflows/test-docs.yml b/.github/workflows/test-docs.yml index 0bbbddfd5..85a1db85b 100644 --- a/.github/workflows/test-docs.yml +++ b/.github/workflows/test-docs.yml @@ -7,6 +7,7 @@ on: - mkdocs.yml - 'docs/operator-public-documentation/**' - '.github/scripts/check_doc_links*.py' + - '.github/scripts/deploy_docs*.py' - '.github/workflows/*docs.yml' push: branches: [main] @@ -15,6 +16,7 @@ on: - mkdocs.yml - 'docs/operator-public-documentation/**' - '.github/scripts/check_doc_links*.py' + - '.github/scripts/deploy_docs*.py' - '.github/workflows/*docs.yml' workflow_dispatch: @@ -34,7 +36,7 @@ jobs: python-version: 3.x - name: Install documentation dependencies run: pip install "mkdocs-material==9.5.19" "mike==2.1.3" "mkdocs-redirects==1.2.2" - - name: Test link checker + - name: Test documentation helpers run: python -m unittest discover -s .github/scripts -p '*_test.py' - name: Build and check candidate entrypoints run: | diff --git a/docs/developer-guides/documentation-publishing.md b/docs/developer-guides/documentation-publishing.md new file mode 100644 index 000000000..4972f9d41 --- /dev/null +++ b/docs/developer-guides/documentation-publishing.md @@ -0,0 +1,57 @@ +# Documentation publishing + +Stable release `1.1.2` publishes to `/1.1/`, titled `1.1` in the version +selector. A later patch updates that same minor entry. The full release tag is +still substituted for `` in installation commands and CRD URLs, +and must match the release's `Chart.yaml` version. + +The deployment helper records the full tag as the minor entry's `release` +property in `gh-pages:versions.json`. Under the shared Pages deployment lock, +it fetches published metadata before deciding whether to publish: + +- A lower patch cannot replace newer docs in the same minor. An equal version + can be redeployed to repair documentation. +- A patch for an older minor may update that minor, but cannot take `latest` + from a higher stable release. Comparisons are numeric, not lexicographic. +- Existing full patch entries count toward both ordering guards. A minor entry + with missing or inconsistent provenance fails rather than risking a downgrade. +- Prereleases require a `major.minor.patch-prerelease` tag and publish only to + their full-tag path. They never update a stable minor, `latest`, or the root + redirect. Marking a prerelease tag as stable does not make it a stable chart + version: publish a matching `major.minor.patch` chart/tag instead. +- Main publishes only `/dev/`, stamped with main's full chart version. + +The helper pushes the release content, provenance, aliases and root redirect +together. Existing patch snapshot directories are not rebuilt, renamed, deleted, +or converted to aliases. They remain in the selector until a separate migration. +This policy applies to releases containing the updated workflow and helper; +older release branches must receive the publishing changes before tagging. +Rerunning a historical workflow does not adopt the new policy. + +## Proposed one-time migration (requires approval) + +Do not run a cleanup automatically during deployment. Before any migration, +inventory `gh-pages` (including `versions.json`, aliases, root redirect and +snapshot directory tree IDs) and retain its commit SHA for rollback. Pause docs +deployments while preparing and reviewing a single migration commit. + +1. Select the highest stable patch snapshot for each existing minor. Confirm + that its installation commands and CRD URLs use that snapshot's full release. + Seed the missing minor path from that snapshot without rebuilding historical + source; add a minor selector entry titled `major.minor` and a matching full + `release` property. Never replace a newer minor entry already deployed. +2. Move `latest` to the minor with the highest stable release and keep the root + redirect targeting `latest`. Confirm that all aliases still resolve. +3. After every stable patch is represented in minor provenance, propose removing + the legacy patch entries **only from `versions.json`** to simplify the + selector. Leave every old patch directory byte-for-byte intact, so bookmarked + deep links and exact-version snapshots retain their original meaning. Do not + use `mike delete`, or turn frozen patch URLs into moving minor aliases. +4. Preview the migration, compare old snapshot tree IDs, and check minor/latest, + old patch deep links, `preview/` redirects and installation pins. Review and + approve the diff before pushing. If needed, revert only the migration commit, + coordinating with any subsequent deployments. + +Merging the workflow change does not backfill minors, remove old selector +entries, or migrate existing snapshots. The next eligible stable release +creates/updates its own minor and advances `latest` only if ordering allows it. diff --git a/mkdocs.yml b/mkdocs.yml index 5de95e555..f3bd89c1f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -18,9 +18,10 @@ theme: - search.highlight # mike (https://github.com/jimporter/mike) enables versioned docs on GitHub Pages. -# Each release gets a frozen snapshot (e.g., /0.2.0/), and "latest" always points -# to the most recent release. Unreleased changes on main deploy to /dev/ only. -# See .github/workflows/deploy_docs.yml for the deployment logic. +# Stable docs use /major.minor/ (e.g., /1.1/), updated by the newest published patch. +# "latest" tracks the highest stable release; main uses /dev/ and prereleases +# use their full tag. Existing patch snapshots remain available at their old URLs. +# See docs/developer-guides/documentation-publishing.md for policy and migration. extra: version: provider: mike