This is an automated email from the ASF dual-hosted git repository.
villebro pushed a commit to branch main
in repository
https://gitbox.apache.org/repos/asf/superset-kubernetes-operator.git
The following commit(s) were added to refs/heads/main by this push:
new 07201c1 ci(docs-versioning): update docs workflow to support
versioning (#489)
07201c1 is described below
commit 07201c1f85f91177a38c487296b73bdec966f52e
Author: Jeremy Chong <[email protected]>
AuthorDate: Tue Nov 17 16:32:50 2026 -0500
ci(docs-versioning): update docs workflow to support versioning (#489)
* docs(config): split config into versioned/unversioned
fix(docs-config): update extra css and js with new versioning js and css
docs(config): split docs config into versioned/unversioned
revert(docs-config): revert zensical toml back to full tree version
docs(config): add a separate unversioned zensical file
docs(config): split docs config into versioned/unversioned
fix(docs): persist theme between versions and other dirs
* docs(versioning): add versioning assets (switcher js/css)
docs(versioning): add versioning assets
fix(docs-versioning): only match ascii
* ci(docs-versioning): add version manifest and link preparation scripts
with tests
fix(docs-versioning): add in depth tests and more guard rails
test(docs-config): add test to check for matching scopes for all zensical
configs
fix(docs-versioning): only allow ascii numbers and allow query params in md
links
tests(docs-versioning): add more cases for updates
* ci(docs-versioning): update the docs workflow for versioned publishing
and backfill
fix(docs-versioning): fix naming
fix(ci): broadly allow tags starting with a v*
fix(docs-versioning): explicitly fetch tags
* fix(pr): address ci failures
remove unnecessary make command
* fix(pr): add ref to concurrency group
Co-authored-by: Younsung Lee <[email protected]>
fix(ci): ensure backfills are separate group
fix(ci): fix group naming if input ref
allows manual backfills to queue behind regular refs if they are the same
version
* fix(pr): update setup-python version
Co-authored-by: Younsung Lee <[email protected]>
* fix(pr): fix possible 404 on legacy urls and make nav into full path
use constants
add missing import
add guards
* ci(docs): add local script and make targets for testing before a deploy
only copy necessary scripts
fix spacing
---------
Co-authored-by: Mathan Thatpar <[email protected]>
Co-authored-by: Akshat Patel <[email protected]>
Co-authored-by: Younsung Lee <[email protected]>
---
.github/workflows/docs.yml | 91 +++++---
Makefile | 11 +-
README.md | 6 +-
docs/contributing/development-setup.md | 18 +-
docs/javascripts/version-switcher.js | 324 ++++++++++++++++++++++++++++
docs/stylesheets/version-banner.css | 47 ++++
scripts/build-docs-local.sh | 87 ++++++++
scripts/docs_versions.py | 336 +++++++++++++++++++++++++++++
scripts/prepare_docs_links.py | 178 +++++++++++++++
scripts/publish-docs.sh | 136 ++++++++++++
scripts/run-docs-ci.sh | 118 ++++++++++
scripts/test_docs_scripts.py | 302 ++++++++++++++++++++++++++
zensical.toml => zensical-unversioned.toml | 50 +++--
zensical.toml => zensical-versioned.toml | 33 ++-
zensical.toml | 2 +
15 files changed, 1682 insertions(+), 57 deletions(-)
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index e20f771..8b9df1b 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -18,18 +18,52 @@ name: Docs
on:
push:
branches: [main]
+ # Match version tags broadly; the build job skips prereleases and
validates X.Y.Z.
+ tags: ["v*"]
paths:
- "docs/**"
- "zensical.toml"
+ - "zensical-unversioned.toml"
+ - "zensical-versioned.toml"
+ - "scripts/publish-docs.sh"
+ - "scripts/run-docs-ci.sh"
+ - "scripts/docs_versions.py"
+ - "scripts/prepare_docs_links.py"
+ - "scripts/test_docs_scripts.py"
+ - "docs/stylesheets/version-banner.css"
- "docs-requirements.in"
- "docs-requirements.txt"
- "Makefile"
- ".github/workflows/docs.yml"
+ workflow_dispatch:
+ inputs:
+ ref:
+ description: "Final release tag to backfill (for example v0.3.1)"
+ required: true
+ type: string
+ dry_run:
+ description: "Build against gh-pages and show the diff without
committing or pushing"
+ required: true
+ default: true
+ type: boolean
+ force:
+ description: "Allow replacing a minor's docs with an older patch
release"
+ required: true
+ default: false
+ type: boolean
pull_request:
branches: [main]
paths:
- "docs/**"
- "zensical.toml"
+ - "zensical-unversioned.toml"
+ - "zensical-versioned.toml"
+ - "scripts/publish-docs.sh"
+ - "scripts/run-docs-ci.sh"
+ - "scripts/docs_versions.py"
+ - "scripts/prepare_docs_links.py"
+ - "scripts/test_docs_scripts.py"
+ - "docs/stylesheets/version-banner.css"
- "docs-requirements.in"
- "docs-requirements.txt"
- "Makefile"
@@ -41,31 +75,44 @@ permissions:
jobs:
build:
name: Build docs
+ # The broad v* tag filter includes prereleases; skip hyphenated tags
before X.Y.Z validation.
+ if: github.event_name != 'push' || github.ref_type != 'tag' ||
!contains(github.ref_name, '-')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #
v7.0.1
with:
persist-credentials: false
+ - name: Set docs ref, dry-run, and force
+ run: bash scripts/run-docs-ci.sh env >> "$GITHUB_ENV"
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 #
v7.1.0
with:
python-version: "3.15"
- name: Install dependencies
run: python -m pip install --require-hashes -r docs-requirements.txt
+ - name: Test documentation versioning and links
+ run: python scripts/test_docs_scripts.py
+ - name: Prepare documentation source and links
+ run: bash scripts/run-docs-ci.sh prepare
+ - name: Build complete documentation tree
+ if: github.event_name != 'workflow_dispatch'
+ run: zensical build --clean --strict
- name: Build docs
- run: make docs-build
+ run: bash scripts/run-docs-ci.sh publish "$RUNNER_TEMP/docs-build"
deploy:
name: Deploy docs
needs: build
- if: github.event_name == 'push'
+ if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
concurrency:
- group: docs-deploy
+ group: docs-deploy-${{ github.event_name == 'workflow_dispatch' &&
format('refs/tags/{0}', inputs.ref) || github.ref }}
cancel-in-progress: false
permissions:
contents: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #
v7.0.1
+ - name: Set docs ref, dry-run, and force env variables
+ run: bash scripts/run-docs-ci.sh env >> "$GITHUB_ENV"
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 #
v7.1.0
with:
python-version: "3.15"
@@ -82,26 +129,29 @@ jobs:
run: |
git -C "$PUBLISH_DIR" config user.name "github-actions[bot]"
git -C "$PUBLISH_DIR" config user.email
"41898282+github-actions[bot]@users.noreply.github.com"
+ - name: Prepare documentation source and links
+ run: bash scripts/run-docs-ci.sh prepare
- name: Build docs
- run: |
- set -euo pipefail
- make docs-build
- - name: Copy generated site
- run: |
- set -euo pipefail
- rsync -a --delete --exclude='.git' site/ "$PUBLISH_DIR/"
- - name: Preserve GitHub Pages static serving
- run: touch "$PUBLISH_DIR/.nojekyll"
+ run: bash scripts/run-docs-ci.sh publish "$PUBLISH_DIR"
- name: Commit and push docs
run: |
set -euo pipefail
git -C "$PUBLISH_DIR" add -A
- if git -C "$PUBLISH_DIR" diff --cached --quiet; then
- echo "No documentation changes to deploy"
+ if [[ "$DRY_RUN" == "true" ]]; then
+ echo "Dry run: assembled the backfill against the existing
gh-pages tree; no commit or push will be made."
+ git -C "$PUBLISH_DIR" diff --cached --stat
+ git -C "$PUBLISH_DIR" diff --cached --name-status
+ git -C "$PUBLISH_DIR" diff --cached -- versions.json
exit 0
fi
- git -C "$PUBLISH_DIR" commit -m "docs: deploy ${GITHUB_SHA}"
+
for attempt in 1 2 3 4 5; do
+ git -C "$PUBLISH_DIR" add -A
+ if git -C "$PUBLISH_DIR" diff --cached --quiet; then
+ echo "No documentation changes to deploy"
+ exit 0
+ fi
+ git -C "$PUBLISH_DIR" commit -q -m "docs: deploy ${GITHUB_SHA}"
if git -C "$PUBLISH_DIR" push origin HEAD:gh-pages; then
exit 0
fi
@@ -112,15 +162,8 @@ jobs:
echo "gh-pages changed while deploying; resetting and retrying"
git -C "$PUBLISH_DIR" fetch origin gh-pages
git -C "$PUBLISH_DIR" reset --hard origin/gh-pages
- rsync -a --delete --exclude='.git' site/ "$PUBLISH_DIR/"
- touch "$PUBLISH_DIR/.nojekyll"
- git -C "$PUBLISH_DIR" add -A
- if git -C "$PUBLISH_DIR" diff --cached --quiet; then
- echo "Documentation is already up to date"
- exit 0
- fi
- git -C "$PUBLISH_DIR" commit -m "docs: deploy ${GITHUB_SHA}"
+ bash scripts/run-docs-ci.sh publish "$PUBLISH_DIR"
done
- name: Clean up gh-pages worktree
if: always()
- run: git worktree remove --force "$PUBLISH_DIR" || true
+ run: git worktree remove --force "$PUBLISH_DIR" || true
\ No newline at end of file
diff --git a/Makefile b/Makefile
index 725674c..42b7cf3 100644
--- a/Makefile
+++ b/Makefile
@@ -126,9 +126,18 @@ docs-serve: ## Serve documentation locally with live
reload.
$(ZENSICAL) serve
.PHONY: docs-build
-docs-build: ## Build documentation site.
+docs-build: ## Build the standalone documentation preview.
$(ZENSICAL) build --strict
+.PHONY: docs-build-ci
+docs-build-ci: ## Assemble the root and versioned docs like CI; set
DOCS_SERVE=true to serve.
+ ./scripts/build-docs-local.sh $(if $(filter true 1
yes,$(DOCS_SERVE)),--serve,)
+
+.PHONY: docs-build-versioned
+docs-build-versioned: ## Assemble docs under a minor version path; set
DOCS_VERSION=X.Y and DOCS_SERVE=true to serve.
+ @test -n "$(DOCS_VERSION)" || { echo "Usage: make docs-build-versioned
DOCS_VERSION=0.3" >&2; exit 2; }
+ ./scripts/build-docs-local.sh --version-path "$(DOCS_VERSION)" $(if
$(filter true 1 yes,$(DOCS_SERVE)),--serve,)
+
.PHONY: docs-api
docs-api: crd-ref-docs ## Generate API reference documentation from Go types.
$(CRD_REF_DOCS) --source-path=api/v1alpha1
--config=hack/api-ref-config.yaml --renderer=markdown --max-depth=15
--output-path=docs/reference/api-reference.md
diff --git a/README.md b/README.md
index 8af5441..3272887 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,7 @@ Read the
[documentation](https://apache.github.io/superset-kubernetes-operator/)
- **Safe upgrades** — components drain, lifecycle tasks run, and traffic
returns only once the new version is healthy, with an optional maintenance page
for the window.
- **Batteries included, never locked in** — tuned defaults and presets for
Gunicorn, Celery, the metastore, and Valkey, with a raw Python escape hatch for
anything not surfaced as a typed field.
- **Production operations built in** — autoscaling, PodDisruptionBudgets,
NetworkPolicies, Gateway API / Ingress routing, and a Prometheus ServiceMonitor.
-- **Fits your cluster** — cluster-scoped or namespace-scoped installs; the
namespace-scoped Helm install renders no manager `ClusterRole` (CRD
installation and, unless disabled, secure metrics auth still need
cluster-scoped RBAC — see
[installation](https://apache.github.io/superset-kubernetes-operator/user-guide/installation/#namespace-scoped-install)).
+- **Fits your cluster** — cluster-scoped or namespace-scoped installs; the
namespace-scoped Helm install renders no manager `ClusterRole` (CRD
installation and, unless disabled, secure metrics auth still need
cluster-scoped RBAC — see
[installation](https://apache.github.io/superset-kubernetes-operator/latest/user-guide/installation/#namespace-scoped-install)).
→ See the [full feature
overview](https://apache.github.io/superset-kubernetes-operator/) in the docs.
@@ -83,7 +83,7 @@ spec:
webServer: {}
```
-> **Note**: The example above uses `environment: Development` for simplicity.
In production (the default), use `secretKeyFrom` and `metastore.passwordFrom`
to reference Kubernetes Secrets. See the [User
Guide](https://apache.github.io/superset-kubernetes-operator/user-guide/configuration/)
and the [sample manifests](config/samples/) for production examples.
+> **Note**: The example above uses `environment: Development` for simplicity.
In production (the default), use `secretKeyFrom` and `metastore.passwordFrom`
to reference Kubernetes Secrets. See the [User
Guide](https://apache.github.io/superset-kubernetes-operator/latest/user-guide/configuration/)
and the [sample manifests](config/samples/) for production examples.
## Under the hood
@@ -92,7 +92,7 @@ For the plumbing-curious:
- **Language & framework** — written in Go, scaffolded with the [Operator
SDK](https://sdk.operatorframework.io/) and built on
[controller-runtime](https://github.com/kubernetes-sigs/controller-runtime).
Validation is CEL-based on the CRD — no admission webhooks to operate.
- **Kubernetes APIs** — tracks the current `k8s.io` client libraries and
[Gateway API](https://gateway-api.sigs.k8s.io/); exact pinned versions live in
[`go.mod`](go.mod).
- **Image & supply chain** — distroless, multi-architecture (amd64/arm64)
container; releases are [Cosign](https://github.com/sigstore/cosign)-signed;
dependencies are kept current via [Renovate](https://docs.renovatebot.com/)
with a minimum release age.
-- **Design & internals** — a single public CRD reconciled into parent-owned
resources. See the [architecture
overview](https://apache.github.io/superset-kubernetes-operator/architecture/overview/)
and the [security & supply-chain
notes](https://apache.github.io/superset-kubernetes-operator/reference/security/).
+- **Design & internals** — a single public CRD reconciled into parent-owned
resources. See the [architecture
overview](https://apache.github.io/superset-kubernetes-operator/latest/architecture/overview/)
and the [security & supply-chain
notes](https://apache.github.io/superset-kubernetes-operator/reference/security/).
## Contributing
diff --git a/docs/contributing/development-setup.md
b/docs/contributing/development-setup.md
index 9f67855..283d43c 100644
--- a/docs/contributing/development-setup.md
+++ b/docs/contributing/development-setup.md
@@ -126,7 +126,9 @@ kind delete cluster --name superset
|---|---|
| `make docs-lock` | Regenerate hash-pinned Python dependencies for
documentation. |
| `make docs-serve` | Serve documentation locally with live reload. |
-| `make docs-build` | Build documentation site. |
+| `make docs-build` | Build the standalone documentation preview. |
+| `make docs-build-ci` | Assemble the root and versioned docs like CI; set
DOCS_SERVE=true to serve. |
+| `make docs-build-versioned` | Assemble docs under a minor version path; set
DOCS_VERSION=X.Y and DOCS_SERVE=true to serve. |
| `make docs-api` | Generate API reference documentation from Go types. |
| `make supported-versions` | Regenerate the supported-Kubernetes-versions
table in README.md and docs. |
| `make make-commands` | Regenerate the make-commands tables in the
contributing docs. |
@@ -235,12 +237,24 @@ This starts a live-reloading server at
`http://localhost:8000`. Edit Markdown fi
The documentation dependency lock is generated from `docs-requirements.in`.
After changing documentation dependencies, run `make docs-lock` and commit the
updated `docs-requirements.txt`.
-To verify the docs build cleanly (same check that runs in CI):
+To build the standalone local preview:
```sh
make docs-build
```
+To assemble the root and versioned pages using the same link preparation and
publishing flow as CI:
+
+```sh
+make docs-build-ci
+```
+
+`make docs-build-ci` builds into a temporary directory, then removes it when
the command exits. It does not rewrite files in the working tree. To build and
serve the assembled site in one command, use `make docs-build-ci
DOCS_SERVE=true` and open
<http://localhost:8000/superset-kubernetes-operator/>. Press Ctrl-C to stop the
server and remove the temporary build.
+
+The local CI assembly already includes the `main` docs slice. To check how the
current docs render under a release-style minor path, run `make
docs-build-versioned DOCS_VERSION=0.3`. Add `DOCS_SERVE=true` to serve it
locally. This uses current docs content; it does not fetch historical docs for
that release.
+
+Docs CI uses two Zensical configs: `zensical-unversioned.toml` builds shared
project pages at the site root, while `zensical-versioned.toml` builds
version-sensitive docs under `/main/` or a release path. Add new pages to the
appropriate navigation. Links to shared and versioned pages include
`/superset-kubernetes-operator/`, the repository's GitHub Pages project path.
+
### Diagrams
Use Mermaid for flow diagrams. Keep them compact with the following
conventions:
diff --git a/docs/javascripts/version-switcher.js
b/docs/javascripts/version-switcher.js
new file mode 100644
index 0000000..8932a0d
--- /dev/null
+++ b/docs/javascripts/version-switcher.js
@@ -0,0 +1,324 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Version selector and "not the latest version" banner for the multi-version
docs site.
+ *
+ * Layout: shared pages at /, one directory per version (/0.3/, /main/),
/latest/
+ * redirect stubs, and /versions.json (schema in scripts/docs_versions.py).
+ */
+(function () {
+ "use strict";
+
+ // Keep in sync with scripts/docs_versions.py.
+ const VERSION_SEGMENT = /^(?:main|latest|[0-9]+\.[0-9]+)$/;
+ const LATEST = "latest";
+ const SWITCHER_CLASS = "docs-version-switcher";
+ const BANNER_ID = "docs-version-banner";
+ // Namespaced because GitHub Pages projects share one origin.
+ const VERSION_STORAGE_PREFIX = "superset-kubernetes-operator-docs-version:";
+
+ // ---- paths ----
+
+ function pathParts(pathname) {
+ return pathname.split("/").filter(Boolean);
+ }
+
+ function toDirPath(parts) {
+ return parts.length ? `/${parts.join("/")}/` : "/";
+ }
+
+ /** Everything before the version segment. Not assumed to be "/": the site
may live under a subpath. */
+ function resolveSiteRoot() {
+ const parts = pathParts(window.location.pathname);
+ const index = parts.findIndex((part) => VERSION_SEGMENT.test(part));
+ if (index !== -1) {
+ return toDirPath(parts.slice(0, index));
+ }
+ // Shared pages have no version segment; use the theme's scope instead.
+ const scope = window.__md_scope;
+ return scope instanceof URL ? toDirPath(pathParts(scope.pathname)) : "/";
+ }
+
+ function detectVersionSegment(root) {
+ const first = pathParts(window.location.pathname.slice(root.length))[0];
+ return first && VERSION_SEGMENT.test(first) ? first : null;
+ }
+
+ /** Same page in another version. Path only; callers add search/hash. */
+ function buildVersionPath(root, targetSegment, currentSegment) {
+ const parts = pathParts(window.location.pathname.slice(root.length));
+ if (currentSegment && parts[0] === currentSegment) {
+ parts.shift();
+ }
+ const trailingSlash = parts.length > 0 &&
window.location.pathname.endsWith("/");
+ return `${root}${targetSegment}/${parts.join("/")}${trailingSlash ? "/" :
""}`;
+ }
+
+ // ---- versions ----
+
+ const isLatest = (entry) => entry.aliases.includes(LATEST);
+ const segmentFor = (entry) => (isLatest(entry) ? LATEST : entry.version);
+
+ function findEntry(versions, segment) {
+ if (!segment) return undefined;
+ if (segment === LATEST) return versions.find(isLatest);
+ return versions.find((entry) => entry.version === segment);
+ }
+
+ // Shared pages belong to no version, so without a remembered choice a
reader on
+ // 0.1 who visits one and goes back would land on /latest/. Per tab on
purpose.
+ function getPreferredVersion(root, versions) {
+ try {
+ const preferred =
window.sessionStorage.getItem(`${VERSION_STORAGE_PREFIX}${root}`);
+ return versions.find((entry) => entry.version === preferred);
+ } catch (error) {
+ console.warn("version-switcher: could not read the saved documentation
version", error);
+ return undefined;
+ }
+ }
+
+ function savePreferredVersion(root, version) {
+ try {
+ window.sessionStorage.setItem(`${VERSION_STORAGE_PREFIX}${root}`,
version);
+ } catch (error) {
+ console.warn("version-switcher: could not save the selected
documentation version", error);
+ }
+ }
+
+ /** Assigning link.pathname rewrites href as an absolute URL; set the
attribute instead. */
+ function setLinkPath(link, pathname) {
+ link.setAttribute("href", `${pathname}${link.search}${link.hash}`);
+ }
+
+ // Shared pages link to /latest/...; point them at the reader's version
instead.
+ function rewriteRootVersionLinks(root, version) {
+ document.querySelectorAll("a[href]").forEach((link) => {
+ if (
+ link.origin !== window.location.origin ||
+ link.hasAttribute("data-version-link") ||
+ link.closest(`.${SWITCHER_CLASS}`)
+ ) {
+ return;
+ }
+ const path = link.pathname.slice(root.length);
+ const firstSegment = pathParts(path)[0];
+ if (firstSegment && VERSION_SEGMENT.test(firstSegment)) {
+ setLinkPath(link, `${root}${version}/${path.slice(firstSegment.length
+ 1)}`);
+ }
+ });
+ }
+
+ function normalizeVersions(raw) {
+ if (!Array.isArray(raw)) return [];
+ return raw
+ .filter((entry) => entry && typeof entry.version === "string")
+ .map((entry) => ({
+ version: entry.version,
+ title: entry.title || entry.version,
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ }));
+ }
+
+ /**
+ * Only the fetch/parse is guarded so rendering bugs stay visible. The
fallback
+ * keeps the selector working without a manifest (e.g. a plain `zensical
serve`).
+ */
+ function loadVersions(root) {
+ const fallback = [{ version: "main", title: "main (unreleased)", aliases:
[] }];
+ return fetch(`${root}versions.json`)
+ .then((response) => (response.ok ? response.json() : fallback))
+ .then((raw) => {
+ const versions = normalizeVersions(raw);
+ return versions.length ? versions : fallback;
+ })
+ .catch((error) => {
+ console.warn("version-switcher: could not load versions.json", error);
+ return fallback;
+ });
+ }
+
+ // ---- navigation ----
+
+ // The target version may not have this page.
+ function pageExists(url) {
+ return fetch(url, { method: "HEAD" })
+ .then((response) => response.ok)
+ .catch(() => true); // offline or blocked HEAD: just navigate
+ }
+
+ /** Keeps ?query and #hash, records the choice, and avoids a 404 when the
page is missing in the target version. */
+ async function onVersionLinkClick(event) {
+ const link = event.target.closest("a[data-version-link]");
+ const modified = event.metaKey || event.ctrlKey || event.shiftKey ||
event.altKey;
+ if (!link || event.defaultPrevented || event.button !== 0 || modified)
return;
+
+ event.preventDefault();
+ const exact = link.getAttribute("href");
+ if (link.dataset.versionPreference) {
+ const root = resolveSiteRoot();
+ savePreferredVersion(root, link.dataset.versionPreference);
+ // A shared page has no versioned twin: stay here and retarget its links.
+ if (!detectVersionSegment(root)) {
+ rewriteRootVersionLinks(root, link.dataset.versionPreference);
+ render(await versionsPromise);
+ return;
+ }
+ }
+ const destination = (await pageExists(exact))
+ ? exact + window.location.search + window.location.hash
+ : link.dataset.fallback;
+ window.location.assign(destination);
+ }
+
+ function makeVersionLink(root, entryOrSegment, currentSegment) {
+ const segment = typeof entryOrSegment === "string" ? entryOrSegment :
segmentFor(entryOrSegment);
+ const link = document.createElement("a");
+ // Shared pages have no counterpart in other versions, so link to the
version's landing page.
+ link.href = currentSegment
+ ? buildVersionPath(root, segment, currentSegment)
+ : `${root}${segment}/`;
+ link.dataset.versionLink = "";
+ link.dataset.fallback = `${root}${segment}/`;
+ if (typeof entryOrSegment !== "string") {
+ link.dataset.versionPreference = entryOrSegment.version;
+ }
+ return link;
+ }
+
+ // ---- selector ----
+
+ function createSelector() {
+ const nav = document.createElement("nav");
+ nav.className = `md-version ${SWITCHER_CLASS}`;
+ nav.setAttribute("aria-label", "Documentation version");
+
+ const toggle = document.createElement("a");
+ toggle.className = "md-version__current";
+ toggle.href = "#";
+ toggle.setAttribute("aria-label", "Select documentation version");
+ const label = document.createElement("span");
+ label.className = `${SWITCHER_CLASS}__label`;
+ toggle.appendChild(label);
+
+ const list = document.createElement("ul");
+ list.className = "md-version__list";
+ list.addEventListener("click", onVersionLinkClick);
+
+ nav.append(toggle, list);
+ const header = document.querySelector(".md-header__inner");
+ const title = header?.querySelector('[data-md-component="header-title"]');
+ if (header) {
+ header.insertBefore(nav, title?.nextSibling || null);
+ }
+ return nav;
+ }
+
+ function renderSelector(ctx) {
+ const { versions, root, segment, current, latest, preferred } = ctx;
+ const nav = document.querySelector(`.${SWITCHER_CLASS}`) ||
createSelector();
+ // On a shared page, show the last-viewed version rather than latest.
+ const selected = current || preferred || latest || versions[0];
+
+ nav.querySelector(`.${SWITCHER_CLASS}__label`).textContent =
selected.title;
+
+ const items = versions.map((entry) => {
+ const link = makeVersionLink(root, entry, segment);
+ link.className = "md-version__link";
+ link.textContent = isLatest(entry) ? `${entry.title} (latest)` :
entry.title;
+ link.setAttribute("aria-current", entry === selected ? "true" : "false");
+ const item = document.createElement("li");
+ item.className = "md-version__item";
+ item.appendChild(link);
+ return item;
+ });
+ nav.querySelector(".md-version__list").replaceChildren(...items);
+ }
+
+ // ---- banner ----
+
+ // Rendered at runtime: a published 0.3 can't know 0.4 exists, but
versions.json can.
+ function renderBanner(ctx) {
+ const { root, segment, current, latest } = ctx;
+ document.getElementById(BANNER_ID)?.remove();
+ if (!current || !latest || current === latest) return;
+
+ const message =
+ current.version === "main"
+ ? "This is the development version of the documentation and may
describe unreleased features. "
+ : `You are viewing the documentation for version ${current.title},
which is not the latest release. `;
+
+ const link = makeVersionLink(root, latest, segment);
+ link.textContent = `Switch to the latest version (${latest.title}).`;
+
+ const banner = document.createElement("div");
+ banner.id = BANNER_ID;
+ banner.className = "docs-version-banner";
+ banner.setAttribute("role", "note");
+ banner.append(message, link);
+ banner.addEventListener("click", onVersionLinkClick);
+
+ document.querySelector(".md-main")?.before(banner);
+ }
+
+ // ---- main ----
+
+ // Runs on every page view, so it must be idempotent.
+ function render(versions) {
+ if (versions.length === 0) return;
+ const root = resolveSiteRoot();
+ const segment = detectVersionSegment(root);
+ const latest = versions.find(isLatest);
+ const preferred = getPreferredVersion(root, versions);
+ if (!segment) {
+ rewriteRootVersionLinks(root, preferred?.version || latest?.version ||
"main");
+ }
+ const ctx = {
+ versions,
+ root,
+ segment,
+ current: findEntry(versions, segment),
+ latest,
+ preferred,
+ };
+ if (ctx.current) {
+ savePreferredVersion(root, ctx.current.version);
+ }
+ renderSelector(ctx);
+ renderBanner(ctx);
+ }
+
+ function onPageReady(callback) {
+ // Material-style instant navigation exposes document$, which emits on
every page view.
+ if (window.document$ && typeof window.document$.subscribe === "function") {
+ window.document$.subscribe(callback);
+ return;
+ }
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", callback);
+ } else {
+ callback();
+ }
+ // Without document$, re-render if the theme swaps the header out.
+ new MutationObserver(() => {
+ if (!document.querySelector(`.${SWITCHER_CLASS}`)) callback();
+ }).observe(document.body, { childList: true, subtree: true });
+ }
+
+ const versionsPromise = loadVersions(resolveSiteRoot());
+ onPageReady(() => versionsPromise.then(render));
+})();
diff --git a/docs/stylesheets/version-banner.css
b/docs/stylesheets/version-banner.css
new file mode 100644
index 0000000..3f28656
--- /dev/null
+++ b/docs/stylesheets/version-banner.css
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+.docs-version-switcher {
+ align-self: center;
+ display: flex;
+ align-items: center;
+ height: 2.4rem;
+ position: relative;
+ z-index: 3;
+}
+
+.docs-version-switcher .md-version__current {
+ top: 0;
+}
+
+.docs-version-switcher .md-version__list {
+ top: 100%;
+}
+
+.docs-version-banner {
+ padding: 0.6rem 1rem;
+ font-size: 0.7rem;
+ text-align: center;
+ color: var(--md-default-fg-color);
+ background: var(--md-code-bg-color);
+ border-bottom: 2px solid var(--md-accent-fg-color);
+}
+
+.docs-version-banner a {
+ font-weight: 700;
+ text-decoration: underline;
+}
diff --git a/scripts/build-docs-local.sh b/scripts/build-docs-local.sh
new file mode 100755
index 0000000..9bb9438
--- /dev/null
+++ b/scripts/build-docs-local.sh
@@ -0,0 +1,87 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Build the root and versioned documentation site in a temporary directory.
+# Usage:
+# ./scripts/build-docs-local.sh [--serve] [--version-path X.Y]
+# --serve serve the assembled site at
http://localhost:8000/superset-kubernetes-operator/
+# --version-path X.Y also publish the current docs under a minor-version
path such as 0.3
+# (the default build already includes the main slice)
+set -euo pipefail
+
+ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/superset-operator-docs.XXXXXX")"
+trap 'rm -rf "$WORK_DIR"' EXIT
+SERVE=0
+TARGET=main
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --serve) SERVE=1; shift ;;
+ --version-path)
+ [[ $# -ge 2 ]] || { echo "usage: $0 [--serve] [--version-path X.Y]" >&2;
exit 2; }
+ TARGET="$2"
+ shift 2
+ ;;
+ *) echo "usage: $0 [--serve] [--version-path X.Y]" >&2; exit 2 ;;
+ esac
+done
+[[ "$TARGET" == main || "$TARGET" =~ ^[0-9]+\.[0-9]+$ ]] || {
+ echo "error: version path must be a minor version such as 0.3" >&2
+ exit 2
+}
+
+cp -R "$ROOT_DIR/docs" "$WORK_DIR/docs"
+mkdir "$WORK_DIR/scripts"
+cp "$ROOT_DIR/scripts/run-docs-ci.sh" \
+ "$ROOT_DIR/scripts/publish-docs.sh" \
+ "$ROOT_DIR/scripts/docs_versions.py" \
+ "$ROOT_DIR/scripts/prepare_docs_links.py" \
+ "$WORK_DIR/scripts/"
+cp "$ROOT_DIR/zensical-unversioned.toml" "$ROOT_DIR/zensical-versioned.toml"
"$WORK_DIR/"
+cd "$WORK_DIR"
+
+# The publishing script runs from this temporary copy, so pass through the
+# executable selected from the original checkout/environment.
+if [[ -x "$ROOT_DIR/venv/bin/zensical" ]]; then
+ export ZENSICAL="$ROOT_DIR/venv/bin/zensical"
+elif [[ -x "$ROOT_DIR/.venv/bin/zensical" ]]; then
+ export ZENSICAL="$ROOT_DIR/.venv/bin/zensical"
+elif command -v zensical >/dev/null 2>&1; then
+ export ZENSICAL="$(command -v zensical)"
+fi
+
+export GITHUB_ACTIONS=true
+export GITHUB_EVENT_NAME=push
+export GITHUB_REF_TYPE=branch
+export DOC_REF=main
+bash scripts/run-docs-ci.sh prepare
+bash scripts/run-docs-ci.sh publish "$WORK_DIR/assembled"
+if [[ "$TARGET" != main ]]; then
+ bash scripts/publish-docs.sh \
+ --config zensical-versioned.toml \
+ --target "$TARGET" \
+ --publish-dir "$WORK_DIR/assembled"
+fi
+if [[ "$SERVE" == 1 ]]; then
+ mkdir "$WORK_DIR/public"
+ ln -s "$WORK_DIR/assembled" "$WORK_DIR/public/superset-kubernetes-operator"
+ echo "==> Serving assembled documentation at
http://localhost:8000/superset-kubernetes-operator/"
+ echo "==> Press Ctrl-C to stop serving; the temporary build will then be
removed"
+ python3 -m http.server 8000 --directory "$WORK_DIR/public"
+else
+ echo "==> Assembled docs checked; temporary build will be removed when this
command exits"
+ echo "==> Use DOCS_SERVE=true with the make target to serve the temporary
build"
+fi
diff --git a/scripts/docs_versions.py b/scripts/docs_versions.py
new file mode 100644
index 0000000..284e4ae
--- /dev/null
+++ b/scripts/docs_versions.py
@@ -0,0 +1,336 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Version bookkeeping for the multi-version documentation site.
+
+Layout under the publish directory::
+
+ / shared pages (built from ``main``), including Home
+ /main/ unreleased versioned docs
+ /0.3/, /0.4/ ... one directory per minor release; patches overwrite their
minor
+ /latest/ redirect pages into the newest minor (into ``main``
before the first release)
+ /versions.json manifest read by docs/javascripts/version-switcher.js
+
+Versioned builds have no Home page, so each version root redirects to
``LANDING_PAGE``.
+
+versions.json is newest minor first, ``main`` last. Before the first release,
+``main`` carries the ``latest`` alias::
+
+ [{"version": "0.4", "title": "0.4", "aliases": ["latest"], "release":
"0.4.1"},
+ {"version": "0.3", "title": "0.3", "aliases": []},
+ {"version": "main", "title": "main (unreleased)", "aliases": []}]
+
+The version grammar is duplicated in version-switcher.js; this file is the
source of truth.
+
+Usage (normally run by publish-docs.sh, not by hand)::
+
+ docs_versions.py check --publish-dir DIR --target TARGET [--release
X.Y.Z] [--force]
+ docs_versions.py finalize --publish-dir DIR --target TARGET [--release
X.Y.Z]
+
+ check validate target/release and refuse patch downgrades; run before
building
+ finalize update versions.json, write the version landing page, regenerate
latest/
+ redirects; run after the site is synced into DIR
+
+TARGET is ``root``, ``main`` or a minor such as ``0.3``; ``--release`` is only
valid
+for a minor and must be a final X.Y.Z of that minor. Example::
+
+ python3 scripts/docs_versions.py finalize --publish-dir /tmp/site --target
0.3 --release 0.3.1
+"""
+
+from __future__ import annotations
+
+import argparse
+import html
+import json
+import posixpath
+import re
+import shutil
+import sys
+from pathlib import Path
+
+from prepare_docs_links import SHARED_PAGES, SITE_PATH_PREFIX
+
+ROOT = "root"
+MAIN = "main"
+LATEST = "latest"
+MAIN_TITLE = "main (unreleased)"
+MANIFEST = "versions.json"
+LANDING_PAGE = "getting-started"
+LEGACY_REDIRECT_MARKER = "<!-- superset-operator-generated-legacy-redirect -->"
+
+MINOR_RE = re.compile(r"^[0-9]+\.[0-9]+$")
+FINAL_RELEASE_RE = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$") # no pre-release
suffix: RCs are never published
+
+
+class DocsVersionError(Exception):
+ """A user-facing error (bad arguments, refused downgrade, corrupt
manifest)."""
+
+
+def version_key(version: str) -> tuple[int, ...]:
+ """Numeric sort key, so 0.10 sorts after 0.9."""
+ return tuple(int(part) for part in version.split("."))
+
+
+def validate_args(target: str, release: str | None = None) -> None:
+ if target not in (ROOT, MAIN) and not MINOR_RE.fullmatch(target):
+ raise DocsVersionError(f"invalid target {target!r}: expected 'root',
'main' or a minor like '0.3'")
+ if release is None:
+ return
+ if target in (ROOT, MAIN):
+ raise DocsVersionError("--release is only valid for minor-version
targets")
+ if not FINAL_RELEASE_RE.fullmatch(release):
+ raise DocsVersionError(
+ f"--release must be a final X.Y.Z version, got {release!r}
(release candidates are never published)"
+ )
+ if release.rsplit(".", 1)[0] != target:
+ raise DocsVersionError(f"--release {release} does not belong to target
{target}")
+
+
+def load_manifest(publish_dir: Path) -> list[dict]:
+ path = publish_dir / MANIFEST
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return []
+ except json.JSONDecodeError as exc:
+ raise DocsVersionError(f"{path} is not valid JSON: {exc}") from exc
+ if not isinstance(data, list):
+ raise DocsVersionError(f"{path} must contain a JSON array")
+ for index, entry in enumerate(data):
+ if not isinstance(entry, dict) or not isinstance(entry.get("version"),
str):
+ raise DocsVersionError(f"{path} entry {index} must be an object
with a string 'version'")
+ return data
+
+
+def check_not_downgrade(entries: list[dict], target: str, release: str | None,
force: bool = False) -> None:
+ """``0.3.1`` overwrites ``0.3``, so publishing ``0.3.0`` afterwards would
silently roll it back."""
+ if release is None or force:
+ return
+ existing = next((e.get("release") for e in entries if e["version"] ==
target), None)
+ if existing and version_key(release) < version_key(existing):
+ raise DocsVersionError(
+ f"{target}/ already contains {existing}; refusing to overwrite it
with older {release} (use --force)"
+ )
+
+
+def build_manifest(entries: list[dict], target: str, release: str | None =
None) -> list[dict]:
+ """Minors newest-first; the newest gets ``latest``, or ``main`` when there
are none."""
+ by_version = {e["version"]: dict(e) for e in entries}
+ by_version[MAIN] = {**by_version.get(MAIN, {}), "version": MAIN, "title":
MAIN_TITLE, "aliases": []}
+
+ if target not in (ROOT, MAIN):
+ entry = by_version.get(target, {})
+ entry.update(version=target, title=target, aliases=[])
+ if release:
+ entry["release"] = release
+ by_version[target] = entry
+
+ minors = sorted((v for v in by_version if MINOR_RE.fullmatch(v)),
key=version_key, reverse=True)
+ for index, version in enumerate(minors):
+ by_version[version]["aliases"] = [LATEST] if index == 0 else []
+ by_version[MAIN]["aliases"] = [] if minors else [LATEST]
+ return [by_version[v] for v in minors] + [by_version[MAIN]]
+
+
+def write_manifest(publish_dir: Path, entries: list[dict]) -> None:
+ (publish_dir / MANIFEST).write_text(json.dumps(entries, indent=2) + "\n",
encoding="utf-8")
+
+
+def latest_version(entries: list[dict]) -> str | None:
+ """The version carrying the ``latest`` alias (``main`` before the first
release)."""
+ return next(
+ (e["version"] for e in entries if LATEST in e.get("aliases", [])),
+ None,
+ )
+
+
+def redirect_page(relative_url: str, label: str) -> str:
+ """A redirect that keeps ``?query`` and ``#hash``, which a bare meta
refresh drops.
+
+ The meta refresh sits in <noscript> so it cannot race the script.
+ """
+ rel_attr = html.escape(relative_url, quote=True)
+ label_html = html.escape(label)
+ return (
+ "<!doctype html>\n"
+ '<meta charset="utf-8">\n'
+ f"<title>Redirecting to {label_html}</title>\n"
+ f'<noscript><meta http-equiv="refresh" content="0;
url={rel_attr}"></noscript>\n'
+ f"<script>location.replace(new URL({json.dumps(relative_url)},
location.href).href"
+ " + location.search + location.hash)</script>\n"
+ f'<p>Redirecting to <a href="{rel_attr}">{label_html}</a>…</p>\n'
+ )
+
+
+def write_version_landing(publish_dir: Path, version: str) -> None:
+ """Versioned builds have no Home page, so the version root redirects to
LANDING_PAGE."""
+ version_root = publish_dir / version
+ version_root.mkdir(parents=True, exist_ok=True)
+ (version_root / "index.html").write_text(
+ redirect_page(f"{LANDING_PAGE}/", f"the {version} documentation"),
encoding="utf-8"
+ )
+
+
+def write_latest_redirects(publish_dir: Path, latest: str) -> int:
+ """Mirror ``<latest>/`` as redirect pages under ``latest/``; returns the
page count."""
+ alias_root = publish_dir / LATEST
+ source_root = publish_dir / latest
+ shutil.rmtree(alias_root, ignore_errors=True)
+
+ count = 0
+ for source in redirectable_pages(source_root):
+ relative = source.relative_to(source_root)
+ if relative.as_posix() == "404.html":
+ continue
+ parent = relative.parent.as_posix()
+ if relative.as_posix() == "index.html":
+ # The version root is itself a redirect; skip that hop.
+ real, suffix = f"{latest}/{LANDING_PAGE}", "/"
+ elif relative.name == "index.html":
+ real, suffix = posixpath.normpath(f"{latest}/{parent}"), "/"
+ else:
+ real, suffix = f"{latest}/{relative.as_posix()}", ""
+ start = posixpath.normpath(f"{LATEST}/{parent}")
+ relative_url = posixpath.relpath(real, start) + suffix
+
+ out = alias_root / relative
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(redirect_page(relative_url, "the latest
documentation"), encoding="utf-8")
+ count += 1
+ return count
+
+
+def write_legacy_redirects(publish_dir: Path) -> int:
+ """Keep former root URLs working after versioned docs move under
/latest/."""
+ alias_root = publish_dir / LATEST
+ if not alias_root.is_dir():
+ return 0
+ shared = {markdown_page_output(page) for page in SHARED_PAGES}
+ count = 0
+ for source in redirectable_pages(alias_root):
+ relative = source.relative_to(alias_root)
+ if relative in shared:
+ continue
+ destination = publish_dir / relative
+ if destination.exists() and not is_legacy_redirect(destination):
+ print(f"warning: not overwriting real page {destination}",
file=sys.stderr)
+ continue
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ target = f"{SITE_PATH_PREFIX}/{LATEST}/{relative.as_posix()}"
+ if relative.name == "index.html":
+ target = target.removesuffix("index.html")
+ destination.write_text(
+ redirect_page(target, "the latest documentation") +
f"{LEGACY_REDIRECT_MARKER}\n",
+ encoding="utf-8",
+ )
+ count += 1
+ return count
+
+
+def is_legacy_redirect(path: Path) -> bool:
+ """Recognize redirect stubs generated by this script, including pre-marker
stubs."""
+ try:
+ content = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return False
+ legacy_target = f'new URL("{SITE_PATH_PREFIX}/{LATEST}/'
+ return LEGACY_REDIRECT_MARKER in content or legacy_target in content
+
+
+def markdown_page_output(page: str) -> Path:
+ """Map a docs Markdown source path to its generated HTML page path."""
+ if page == "index.md":
+ return Path("index.html")
+ if page.endswith("/index.md"):
+ return Path(page[: -len("index.md")]) / "index.html"
+ return Path(page.removesuffix(".md")) / "index.html"
+
+
+def redirectable_pages(source_root: Path) -> list[Path]:
+ """List generated pages eligible for version/legacy redirects."""
+ return [
+ source
+ for source in sorted(source_root.rglob("*.html"))
+ if source.relative_to(source_root).as_posix() != "404.html"
+ ]
+
+
+def cmd_check(args: argparse.Namespace) -> None:
+ validate_args(args.target, args.release)
+ check_not_downgrade(load_manifest(args.publish_dir), args.target,
args.release, args.force)
+
+
+def cmd_finalize(args: argparse.Namespace) -> None:
+ validate_args(args.target, args.release)
+ publish_dir: Path = args.publish_dir
+
+ if args.target == ROOT:
+ latest = latest_version(load_manifest(publish_dir))
+ if latest and (publish_dir / LATEST).is_dir():
+ legacy_pages = write_legacy_redirects(publish_dir)
+ print(f"==> root legacy URLs -> latest ({legacy_pages} redirect
pages)")
+ return
+
+ # Without this page the version root and latest/ would redirect to a 404.
+ if not (publish_dir / args.target / LANDING_PAGE / "index.html").is_file():
+ raise DocsVersionError(
+ f"{args.target}/ has no {LANDING_PAGE}/ page; its root would
redirect to a 404"
+ )
+ write_version_landing(publish_dir, args.target)
+ entries = build_manifest(load_manifest(publish_dir), args.target,
args.release)
+ write_manifest(publish_dir, entries)
+ latest = latest_version(entries)
+ if latest and (publish_dir / latest).is_dir():
+ pages = write_latest_redirects(publish_dir, latest)
+ print(f"==> latest -> {latest} ({pages} redirect pages)")
+ legacy_pages = write_legacy_redirects(publish_dir)
+ print(f"==> root legacy URLs -> latest ({legacy_pages} redirect
pages)")
+ else:
+ shutil.rmtree(publish_dir / LATEST, ignore_errors=True)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ def common(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--publish-dir", type=Path, required=True)
+ p.add_argument("--target", required=True)
+ p.add_argument("--release")
+
+ check = sub.add_parser("check", help="validate arguments before building")
+ common(check)
+ check.add_argument("--force", action="store_true", help="allow overwriting
a minor with an older patch")
+ check.set_defaults(func=cmd_check)
+
+ finalize = sub.add_parser("finalize", help="update manifest and redirects
after syncing")
+ common(finalize)
+ finalize.set_defaults(func=cmd_finalize)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ try:
+ args.func(args)
+ except DocsVersionError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/prepare_docs_links.py b/scripts/prepare_docs_links.py
new file mode 100644
index 0000000..ccb92fc
--- /dev/null
+++ b/scripts/prepare_docs_links.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Rewrite relative documentation links for the assembled multi-version site.
+
+Docs are written with plain relative .md links; this makes them work across
sections:
+ * any page -> shared page absolute URL under SITE_PATH_PREFIX
+ * shared page -> versioned page absolute URL under /<prefix>/ (for example
latest)
+ * versioned -> versioned left relative, so each version stays
self-contained
+
+Only inline markdown links are handled (not reference-style, raw HTML, or code
+fences), and doc file names must not contain spaces or parentheses. Files are
+rewritten in place: run it in CI or on a throwaway copy of docs/. Query strings
+and fragments are preserved when a local page link is rewritten.
+
+Usage::
+
+ prepare_docs_links.py --docs-dir DIR [--versioned-prefix PREFIX]
+
+ --docs-dir the docs/ tree to rewrite
+ --versioned-prefix also rewrite shared -> versioned links under /PREFIX/
(use
+ ``latest`` for normal builds; omit for historical
backfills,
+ where shared pages are not built)
+
+Locally, always work on a copy::
+
+ cp -r docs /tmp/docs-links
+ python3 scripts/prepare_docs_links.py --docs-dir /tmp/docs-links
--versioned-prefix latest
+
+SHARED_PAGES must match ``exclude_docs`` in zensical-versioned.toml and the
+pages built by zensical-unversioned.toml; test_docs_scripts.py checks both
ways.
+"""
+
+from __future__ import annotations
+
+import argparse
+import posixpath
+import re
+from pathlib import Path, PurePosixPath
+
+# GitHub Pages serves this project under its repository name (must match
site_url).
+SITE_PATH_PREFIX = "/superset-kubernetes-operator"
+
+# Pages built at the site root, as paths relative to docs/
+SHARED_PAGES = frozenset(
+ {
+ "index.md",
+ "reference/downloads.md",
+ "reference/releases.md",
+ "reference/security.md",
+ "contributing/development-setup.md",
+ "contributing/development-guidelines.md",
+ "contributing/releasing.md",
+ }
+)
+# [text](target) or [text](target "title")
+MARKDOWN_LINK =
re.compile(r"\]\((?P<target>[^)\s]+)(?P<title>\s+(?:\"[^\"]*\"|'[^']*'))?\)")
+FENCE_START = re.compile(r"^ {0,3}(`{3,}|~{3,})")
+FENCE_END = re.compile(r"^ {0,3}(`+|~+)[ \t]*(?:\r?\n)?$")
+
+
+def rewrite_outside_fenced_code(text: str, replace) -> str:
+ """Rewrite links in Markdown text while preserving fenced code examples."""
+ output = []
+ fence_char = None
+ fence_length = 0
+ for line in text.splitlines(keepends=True):
+ if fence_char is None:
+ opening = FENCE_START.match(line)
+ if opening:
+ fence_char = opening.group(1)[0]
+ fence_length = len(opening.group(1))
+ output.append(line)
+ else:
+ output.append(MARKDOWN_LINK.sub(replace, line))
+ continue
+
+ output.append(line)
+ closing = FENCE_END.match(line)
+ if closing and closing.group(1)[0] == fence_char and
len(closing.group(1)) >= fence_length:
+ fence_char = None
+ fence_length = 0
+ return "".join(output)
+
+
+def page_url(relative: str, prefix: str = "") -> str:
+ """URL path of a docs page, e.g. reference/security.md ->
/reference/security/."""
+ if relative == "index.md" or relative.endswith("/index.md"):
+ page = relative[: -len("index.md")]
+ else:
+ page = relative[: -len(".md")] + "/"
+ return f"/{prefix}/{page}" if prefix else f"/{page}"
+
+
+def versioned_page_urls(docs_dir: Path, prefix: str) -> dict[str, str]:
+ return {
+ relative: page_url(relative, prefix)
+ for relative in (path.relative_to(docs_dir).as_posix() for path in
docs_dir.rglob("*.md"))
+ if relative not in SHARED_PAGES
+ }
+
+
+def rewrite_file(
+ path: Path,
+ docs_dir: Path,
+ versioned_pages: dict[str, str] | None = None,
+) -> bool:
+ relative = PurePosixPath(path.relative_to(docs_dir).as_posix())
+ # Only shared pages point at versioned pages by URL. A versioned page's
links to
+ # other versioned pages must stay relative or they would jump to another
version.
+ link_to_versioned = versioned_pages if relative.as_posix() in SHARED_PAGES
else None
+ original = path.read_text()
+
+ def replace(match: re.Match[str]) -> str:
+ target = match.group("target")
+ path_and_query, fragment_separator, fragment = target.partition("#")
+ link_path, query_separator, query = path_and_query.partition("?")
+ if not link_path or link_path.startswith(("/", "#")) or "://" in
link_path:
+ return match.group(0)
+ resolved = posixpath.normpath(posixpath.join(str(relative.parent),
link_path))
+ if resolved in SHARED_PAGES:
+ page = page_url(resolved)
+ elif link_to_versioned is not None:
+ page = link_to_versioned.get(resolved)
+ else:
+ page = None
+ if page is None:
+ return match.group(0)
+ rewritten_target = f"{SITE_PATH_PREFIX}{page}"
+ if query_separator:
+ rewritten_target += f"?{query}"
+ if fragment_separator:
+ rewritten_target += f"#{fragment}"
+ return f"]({rewritten_target}{match.group('title') or ''})"
+
+ rewritten = rewrite_outside_fenced_code(original, replace)
+ if rewritten == original:
+ return False
+ path.write_text(rewritten)
+ return True
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ parser.add_argument("--docs-dir", type=Path, required=True)
+ parser.add_argument(
+ "--versioned-prefix",
+ help="rewrite links from shared pages to versioned pages under this
URL prefix (for example, latest)",
+ )
+ args = parser.parse_args()
+ prefix = args.versioned_prefix.strip("/") if args.versioned_prefix else
None
+ if args.versioned_prefix is not None and not prefix:
+ parser.error("--versioned-prefix must contain a path segment")
+ versioned_pages = versioned_page_urls(args.docs_dir, prefix) if prefix
else None
+ count = sum(
+ rewrite_file(path, args.docs_dir, versioned_pages)
+ for path in args.docs_dir.rglob("*.md")
+ if not path.is_symlink() # backfills extract old tags; never write
through a link
+ )
+ print(f"==> Rewrote links in {count} documentation files")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/publish-docs.sh b/scripts/publish-docs.sh
new file mode 100644
index 0000000..b230a42
--- /dev/null
+++ b/scripts/publish-docs.sh
@@ -0,0 +1,136 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Build one slice of the docs site and merge it into a publish directory.
+#
+# root unversioned pages, built from main -> <publish-dir>/
+# main unreleased docs -> <publish-dir>/main/
+# X.Y a minor release (patches overwrite it) -> <publish-dir>/X.Y/
+#
+# Versioned targets also refresh versions.json and the latest/ redirect tree;
+# the site root remains the unversioned main-branch site.
+# All version logic lives in docs_versions.py; this script only orchestrates.
+#
+# Only run with --release for final tags after the release vote, never for RCs.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
+VERSIONS_PY="$SCRIPT_DIR/docs_versions.py"
+
+usage() {
+ cat >&2 <<'EOF'
+Usage: publish-docs.sh --config FILE --target TARGET --publish-dir DIR
[options]
+
+ --config FILE Zensical config for this target (one per build)
+ --target TARGET root, main, or a minor version such as 0.3
+ --publish-dir DIR directory that holds the assembled site
+ --release X.Y.Z final release being published (versioned targets only)
+ --site-dir DIR build output dir; must match site_dir in the config
+ (default: $ROOT_DIR/site, or $SITE_DIR)
+ --force allow overwriting a minor with an older patch
+EOF
+}
+
+die() { echo "error: $*" >&2; exit 2; }
+log() { echo "==> $*"; }
+
+CONFIG="" TARGET="" PUBLISH_DIR="" RELEASE="" FORCE=""
+SITE_DIR="${SITE_DIR:-$ROOT_DIR/site}"
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --help|-h) usage; exit 0 ;;
+ --force) FORCE=1; shift ;;
+ --config|--target|--publish-dir|--release|--site-dir)
+ [[ $# -ge 2 ]] || { usage; die "$1 requires a value"; }
+ case "$1" in
+ --config) CONFIG="$2" ;;
+ --target) TARGET="$2" ;;
+ --publish-dir) PUBLISH_DIR="$2" ;;
+ --release) RELEASE="$2" ;;
+ --site-dir) SITE_DIR="$2" ;;
+ esac
+ shift 2 ;;
+ *) usage; die "unknown argument: $1" ;;
+ esac
+done
+
+[[ -n "$CONFIG" && -n "$TARGET" && -n "$PUBLISH_DIR" ]] || { usage; die
"missing required argument"; }
+[[ -f "$CONFIG" ]] || die "config does not exist: $CONFIG"
+
+for tool in python3 rsync; do
+ command -v "$tool" >/dev/null 2>&1 || die "required tool not found: $tool"
+done
+if [[ -z "${ZENSICAL:-}" ]]; then
+ if [[ -x "$ROOT_DIR/venv/bin/zensical" ]]; then
+ ZENSICAL="$ROOT_DIR/venv/bin/zensical"
+ elif [[ -x "$ROOT_DIR/.venv/bin/zensical" ]]; then
+ ZENSICAL="$ROOT_DIR/.venv/bin/zensical"
+ else
+ ZENSICAL="zensical"
+ fi
+fi
+command -v "$ZENSICAL" >/dev/null 2>&1 || { echo "zensical executable not
found: $ZENSICAL" >&2; exit 127; }
+
+CONFIG="$(cd "$(dirname "$CONFIG")" && pwd)/$(basename "$CONFIG")"
+mkdir -p "$PUBLISH_DIR"
+PUBLISH_DIR="$(cd "$PUBLISH_DIR" && pwd)"
+
+# Shared arguments for docs_versions.py. The "${arr[@]+...}" form keeps empty
+# arrays safe under `set -u` on older bash.
+common=(--publish-dir "$PUBLISH_DIR" --target "$TARGET")
+[[ -z "$RELEASE" ]] || common+=(--release "$RELEASE")
+check_args=("${common[@]}")
+[[ -z "$FORCE" ]] || check_args+=(--force)
+finalize_args=("${common[@]}")
+
+# Fail fast, before the (slow) build, on bad targets, RC versions, or
downgrades.
+python3 "$VERSIONS_PY" check "${check_args[@]}"
+
+BUILD_CONFIG="$CONFIG"
+if [[ "$TARGET" != root ]]; then
+ # Canonical URLs and sitemap entries must include the output version
directory.
+ BUILD_CONFIG="$(mktemp "$(dirname
"$CONFIG")/.zensical-versioned.XXXXXX.toml")"
+ trap 'rm -f "$BUILD_CONFIG"' EXIT
+ sed "s|^site_url =
\"https://apache.github.io/superset-kubernetes-operator/\"|site_url =
\"https://apache.github.io/superset-kubernetes-operator/$TARGET/\"|" \
+ "$CONFIG" > "$BUILD_CONFIG"
+fi
+
+log "Building '$TARGET' with $(basename "$CONFIG")"
+"$ZENSICAL" build --clean --strict --config-file "$BUILD_CONFIG"
+[[ -d "$SITE_DIR" ]] || die "build output not found: $SITE_DIR (does site_dir
in the config match --site-dir?)"
+
+if [[ "$TARGET" == root ]]; then
+ log "Syncing root site into $PUBLISH_DIR"
+ # Anchored excludes protect only the top-level versioned output from
--delete;
+ # they do not skip same-named files elsewhere in the source tree.
+ rsync -a --delete \
+ --exclude='/.git' \
+ --exclude='/main/' \
+ --exclude='/[0-9]*.[0-9]*/' \
+ --exclude='/latest/' \
+ --exclude='/versions.json' \
+ "$SITE_DIR/" "$PUBLISH_DIR/"
+else
+ log "Syncing into $PUBLISH_DIR/$TARGET/"
+ mkdir -p "$PUBLISH_DIR/$TARGET"
+ rsync -a --delete "$SITE_DIR/" "$PUBLISH_DIR/$TARGET/"
+fi
+
+touch "$PUBLISH_DIR/.nojekyll"
+python3 "$VERSIONS_PY" finalize "${finalize_args[@]}"
+log "Done"
diff --git a/scripts/run-docs-ci.sh b/scripts/run-docs-ci.sh
new file mode 100644
index 0000000..0246385
--- /dev/null
+++ b/scripts/run-docs-ci.sh
@@ -0,0 +1,118 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# CI glue for .github/workflows/docs.yml.
+#
+# run-docs-ci.sh env print DOC_REF and DRY_RUN for >>
"$GITHUB_ENV"
+# run-docs-ci.sh prepare prepare current docs links or load backfill
docs
+# run-docs-ci.sh publish DIR build the right slice(s) of the site into DIR
+#
+# `prepare` and `publish` read GITHUB_EVENT_NAME, GITHUB_REF_TYPE and DOC_REF
+# (the release tag for tag pushes and backfills, otherwise the branch name).
+# Requires jq (preinstalled on GitHub-hosted runners).
+set -euo pipefail
+
+cd "$(dirname "${BASH_SOURCE[0]}")/.."
+
+# Release builds are tag pushes and backfills; branch builds are main pushes
and PRs.
+is_release() { [[ "$GITHUB_EVENT_NAME" == workflow_dispatch ||
"$GITHUB_REF_TYPE" == tag ]]; }
+
+# Sets VERSION (X.Y.Z) and MINOR (X.Y) from DOC_REF, or exits. Final tags
only, never RCs.
+release_vars() {
+ [[ "$DOC_REF" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]] || {
+ echo "not a final release tag: $DOC_REF" >&2
+ exit 1
+ }
+ VERSION="${BASH_REMATCH[1]}"
+ MINOR="${VERSION%.*}"
+}
+
+# Workflow inputs come from the event payload instead of a ${{ }} expression,
so
+# user-supplied text never becomes shell source. GITHUB_ENV is line-based, so a
+# release ref is validated BEFORE it is printed: a crafted value cannot add
variables.
+emit_env() {
+ local ref dry_run force
+ ref="$(jq -r '.inputs.ref // empty' "$GITHUB_EVENT_PATH")"
+ dry_run="$(jq -r '.inputs.dry_run // false' "$GITHUB_EVENT_PATH")"
+ force="$(jq -r '.inputs.force // false' "$GITHUB_EVENT_PATH")"
+ [[ "$dry_run" == true || "$dry_run" == false ]] || {
+ echo "invalid dry_run input: expected true or false" >&2
+ exit 1
+ }
+ [[ "$force" == true || "$force" == false ]] || {
+ echo "invalid force input: expected true or false" >&2
+ exit 1
+ }
+ DOC_REF="${ref:-$GITHUB_REF_NAME}"
+ if is_release; then release_vars; fi
+ printf 'DOC_REF=%s\nDRY_RUN=%s\nDOCS_FORCE=%s\n' "$DOC_REF" "$dry_run"
"$force"
+}
+
+prepare() (
+ [[ "${GITHUB_ACTIONS:-}" == "true" ]] || {
+ echo "error: prepare is CI-only; use a temporary docs copy for local
previews" >&2
+ exit 2
+ }
+ if [[ "$GITHUB_EVENT_NAME" == workflow_dispatch ]]; then
+ release_vars
+ git fetch --no-tags origin "refs/tags/$DOC_REF"
+ # Swap in the tag's pages but keep today's other files, so anything the
configs
+ # reference (logo, extra CSS, ...) exists even if the tag predates it.
javascripts/
+ # and stylesheets/ stay as they are: they hold the current version
switcher.
+ find docs -name '*.md' -delete
+ git archive FETCH_HEAD docs | tar -x --exclude='docs/javascripts'
--exclude='docs/stylesheets'
+ # Historical backfills keep version-to-version links relative to their own
version.
+ python3 scripts/prepare_docs_links.py --docs-dir docs
+ else
+ python3 scripts/prepare_docs_links.py \
+ --docs-dir docs \
+ --versioned-prefix latest
+ fi
+)
+
+publish() {
+ local dir="$1"
+ mkdir -p "$dir"
+ if is_release; then
+ release_vars
+ local force_args=()
+ if [[ "$GITHUB_EVENT_NAME" == workflow_dispatch && "${DOCS_FORCE:-false}"
== true ]]; then
+ force_args+=(--force)
+ fi
+ bash scripts/publish-docs.sh \
+ --config zensical-versioned.toml \
+ --target "$MINOR" \
+ --publish-dir "$dir" \
+ --release "$VERSION" \
+ "${force_args[@]+"${force_args[@]}"}"
+ else
+ bash scripts/publish-docs.sh \
+ --config zensical-unversioned.toml \
+ --target root \
+ --publish-dir "$dir"
+ bash scripts/publish-docs.sh \
+ --config zensical-versioned.toml \
+ --target main \
+ --publish-dir "$dir"
+ fi
+}
+
+case "${1:-}" in
+ env) emit_env ;;
+ prepare) prepare ;;
+ publish) [[ $# -eq 2 ]] || { echo "usage: $0 publish DIR" >&2; exit 2; };
publish "$2" ;;
+ *) echo "usage: $0 env | prepare | publish DIR" >&2; exit 2 ;;
+esac
\ No newline at end of file
diff --git a/scripts/test_docs_scripts.py b/scripts/test_docs_scripts.py
new file mode 100644
index 0000000..ec05177
--- /dev/null
+++ b/scripts/test_docs_scripts.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Unit tests for documentation versioning and link preparation."""
+
+import contextlib
+import fnmatch
+import io
+import json
+import posixpath
+import re
+import tempfile
+import tomllib
+import unittest
+from pathlib import Path
+from urllib.parse import urlparse
+
+import docs_versions as dv
+import prepare_docs_links as phd
+
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+
+class DocsVersionsTest(unittest.TestCase):
+ def test_switcher_version_segments_match_manifest_rules(self):
+ source = (REPO_ROOT /
"docs/javascripts/version-switcher.js").read_text()
+ match = re.search(r"const VERSION_SEGMENT = /(.+)/;", source)
+ self.assertIsNotNone(match, "version-switcher.js must define
VERSION_SEGMENT")
+ switcher_pattern = re.compile(match.group(1))
+
+ for segment in ("main", "latest", "0.3", "12.34", "0", "0.3.1",
"v0.3", "0.x", "٠.٣"):
+ with self.subTest(segment=segment):
+ python_accepts = segment in (dv.MAIN, dv.LATEST) or
bool(dv.MINOR_RE.fullmatch(segment))
+ self.assertEqual(bool(switcher_pattern.fullmatch(segment)),
python_accepts)
+
+ def test_latest_uses_numeric_not_lexicographic_order(self):
+ entries = []
+ for minor in ("0.9", "0.10", "0.2"):
+ entries = dv.build_manifest(entries, minor)
+ self.assertEqual([entry["version"] for entry in entries], ["0.10",
"0.9", "0.2", "main"])
+ self.assertEqual(dv.latest_version(entries), "0.10")
+
+ def test_main_is_latest_before_first_final_release(self):
+ entries = dv.build_manifest([], dv.MAIN)
+ self.assertEqual(entries, [{"version": "main", "title": dv.MAIN_TITLE,
"aliases": ["latest"]}])
+ self.assertEqual(dv.latest_version(entries), "main")
+ entries = dv.build_manifest(entries, "0.3", "0.3.0")
+ self.assertEqual(entries[-1], {"version": "main", "title":
dv.MAIN_TITLE, "aliases": []})
+ self.assertEqual(entries[0]["aliases"], ["latest"])
+ self.assertEqual(dv.latest_version(entries), "0.3")
+
+ def test_patch_release_overwrites_minor_entry(self):
+ entries = dv.build_manifest([], "0.3", "0.3.0")
+ entries = dv.build_manifest(entries, "0.3", "0.3.1")
+ self.assertEqual([entry["version"] for entry in entries], ["0.3",
"main"])
+ self.assertEqual(entries[0]["release"], "0.3.1")
+
+ def test_downgrade_refused_unless_forced(self):
+ entries = dv.build_manifest([], "0.3", "0.3.2")
+ with self.assertRaises(dv.DocsVersionError):
+ dv.check_not_downgrade(entries, "0.3", "0.3.1")
+ dv.check_not_downgrade(entries, "0.3", "0.3.1", force=True)
+ dv.check_not_downgrade(entries, "0.3", "0.3.2")
+
+ def test_invalid_arguments_rejected(self):
+ cases = [
+ ("0.3", "0.3.0rc1"),
+ ("٠.٣", None),
+ ("0.3", "0.4.0"),
+ ("main", "0.3.0"),
+ ("root", "0.3.0"),
+ ("v0.3", None),
+ ("0.3.1", None),
+ ]
+ for target, release in cases:
+ with self.subTest(target=target, release=release):
+ with self.assertRaises(dv.DocsVersionError):
+ dv.validate_args(target, release)
+
+ @staticmethod
+ def make_site(root: Path, minor: str = "0.3", landing: bool = False):
+ pages = ["index.html", "guide/index.html", "guide/page.html",
"404.html"]
+ if landing:
+ pages.append(f"{dv.LANDING_PAGE}/index.html")
+ for relative in pages:
+ path = root / minor / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("<html></html>")
+
+ def test_latest_redirects_are_relative_and_keep_hash_and_query(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ self.make_site(root)
+ self.assertEqual(dv.write_latest_redirects(root, "0.3"), 3)
+ index = (root / "latest/index.html").read_text()
+ self.assertIn('"../0.3/getting-started/"', index)
+ self.assertIn("location.search + location.hash", index)
+ self.assertIn('"../../0.3/guide/"', (root /
"latest/guide/index.html").read_text())
+ self.assertIn('"../../0.3/guide/page.html"', (root /
"latest/guide/page.html").read_text())
+
+ def test_latest_redirects_replace_previous_alias(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ self.make_site(root, "0.3")
+ dv.write_latest_redirects(root, "0.3")
+ self.make_site(root, "0.4")
+ (root / "0.4/guide/page.html").unlink()
+ dv.write_latest_redirects(root, "0.4")
+ self.assertFalse((root / "latest/guide/page.html").exists())
+ self.assertIn('"../0.4/getting-started/"', (root /
"latest/index.html").read_text())
+
+ def test_finalize_writes_landing_manifest_and_latest(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ self.make_site(root, landing=True)
+ args = ["finalize", "--publish-dir", str(root), "--target", "0.3",
"--release", "0.3.0"]
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.assertEqual(dv.main(args), 0)
+ self.assertIn('new URL("getting-started/", location.href)', (root
/ "0.3/index.html").read_text())
+ self.assertEqual(dv.latest_version(dv.load_manifest(root)), "0.3")
+ self.assertTrue((root / "latest/index.html").is_file())
+
+ def test_finalize_refuses_a_version_without_the_landing_page(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ self.make_site(root) # no getting-started/ page: the version root
would redirect to a 404
+ args = ["finalize", "--publish-dir", str(root), "--target", "0.3",
"--release", "0.3.0"]
+ stderr = io.StringIO()
+ with contextlib.redirect_stderr(stderr):
+ self.assertEqual(dv.main(args), 2)
+ self.assertIn("getting-started", stderr.getvalue())
+ self.assertFalse((root / dv.MANIFEST).exists())
+
+ def test_load_manifest_rejects_malformed_entries(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / dv.MANIFEST).write_text(json.dumps([{"version": "0.3"},
None]))
+
+ with self.assertRaisesRegex(dv.DocsVersionError, "entry 1"):
+ dv.load_manifest(root)
+
+
+class DocumentationLinkPreparationTest(unittest.TestCase):
+ """Keeps docs, configs and SHARED_PAGES in sync, and pins the link rewrite
rules."""
+
+ @staticmethod
+ def project_config(name: str) -> dict:
+ with (REPO_ROOT / name).open("rb") as config_file:
+ return tomllib.load(config_file)["project"]
+
+ @classmethod
+ def excludes(cls, name: str) -> list[str]:
+ patterns = cls.project_config(name)["exclude_docs"].splitlines()
+ # fnmatch only agrees with gitignore-style matching for plain paths
and simple
+ # globs, so fail loudly on anything fancier instead of passing or
failing wrongly.
+ for pattern in patterns:
+ if pattern.startswith(("/", "!", "#")) or pattern.endswith("/"):
+ raise AssertionError(f"{name}: exclude_docs pattern
{pattern!r} is not supported by these tests")
+ return patterns
+
+ @staticmethod
+ def matches(page: str, patterns: list[str]) -> bool:
+ return any(fnmatch.fnmatchcase(page, pattern) for pattern in patterns)
+
+ @staticmethod
+ def doc_pages() -> list[str]:
+ docs_dir = REPO_ROOT / "docs"
+ return sorted(path.relative_to(docs_dir).as_posix() for path in
docs_dir.rglob("*.md"))
+
+ def test_shared_pages_match_zensical_configs(self):
+ # Shared pages are the ones the versioned build excludes and the
unversioned build keeps.
+ # Equality also proves every listed page exists and no root-only page
is missing.
+ versioned_excludes = self.excludes("zensical-versioned.toml")
+ unversioned_excludes = self.excludes("zensical-unversioned.toml")
+ root_only = {
+ page
+ for page in self.doc_pages()
+ if self.matches(page, versioned_excludes) and not
self.matches(page, unversioned_excludes)
+ }
+ self.assertEqual(root_only, set(phd.SHARED_PAGES))
+
+ def test_site_path_prefix_matches_site_url(self):
+ for name in ("zensical-unversioned.toml", "zensical-versioned.toml"):
+ site_url = self.project_config(name).get("site_url")
+ if not site_url:
+ continue
+ with self.subTest(config=name):
+ self.assertEqual(urlparse(site_url).path.rstrip("/"),
phd.SITE_PATH_PREFIX)
+
+ def test_theme_preference_scope_is_shared_across_configs(self):
+ configs = ("zensical.toml", "zensical-unversioned.toml",
"zensical-versioned.toml")
+ scopes = {self.project_config(name)["extra"]["scope"] for name in
configs}
+ self.assertEqual(scopes, {f"{phd.SITE_PATH_PREFIX}/"})
+
+ def test_unsupported_link_syntax_does_not_cross_sections(self):
+ # The rewriter only handles inline markdown links. Reference-style
definitions and
+ # raw HTML links would silently break if they point into the other
section.
+ reference = re.compile(r"^\s*\[[^\]]+\]:\s*<?(\S+?)>?(?:\s|$)",
re.MULTILINE)
+ html_link = re.compile(r"""\b(?:href|src)=["']([^"']+)["']""")
+ docs_dir = REPO_ROOT / "docs"
+
+ for page in self.doc_pages():
+ text = (docs_dir / page).read_text()
+ for target in reference.findall(text) + html_link.findall(text):
+ link_path = target.partition("#")[0]
+ if not link_path or link_path.startswith("/") or "://" in
link_path:
+ continue
+ resolved =
posixpath.normpath(posixpath.join(posixpath.dirname(page), link_path))
+ if not resolved.endswith(".md") or not (docs_dir /
resolved).is_file():
+ continue
+ with self.subTest(page=page, target=target):
+ self.assertEqual(
+ page in phd.SHARED_PAGES,
+ resolved in phd.SHARED_PAGES,
+ f"{page} links to {resolved} across sections with
syntax the rewriter does not handle",
+ )
+
+ def test_shared_links_are_rewritten_under_project_path(self):
+ with tempfile.TemporaryDirectory() as directory:
+ docs_dir = Path(directory)
+ (docs_dir / "reference").mkdir()
+ index = docs_dir / "index.md"
+ index.write_text("[Shared](reference/security.md#scope)")
+ (docs_dir / "reference/security.md").write_text("Shared security
page")
+
+ self.assertTrue(phd.rewrite_file(index, docs_dir))
+ self.assertEqual(
+ index.read_text(),
+
"[Shared](/superset-kubernetes-operator/reference/security/#scope)",
+ )
+
+ def test_links_inside_fenced_code_blocks_are_not_rewritten(self):
+ with tempfile.TemporaryDirectory() as directory:
+ docs_dir = Path(directory)
+ (docs_dir / "reference").mkdir()
+ page = docs_dir / "index.md"
+ page.write_text(
+ "[Live](reference/security.md)\n\n"
+ "```markdown\n[Example](reference/security.md)\n```\n"
+ )
+ (docs_dir / "reference/security.md").write_text("Shared security
page")
+
+ phd.rewrite_file(page, docs_dir)
+
+ self.assertEqual(
+ page.read_text(),
+ "[Live](/superset-kubernetes-operator/reference/security/)\n\n"
+ "```markdown\n[Example](reference/security.md)\n```\n",
+ )
+
+ def
test_shared_links_to_versioned_pages_use_project_and_version_paths(self):
+ with tempfile.TemporaryDirectory() as directory:
+ docs_dir = Path(directory)
+ (docs_dir / "reference").mkdir()
+ (docs_dir / "user-guide").mkdir()
+ index = docs_dir / "index.md"
+ index.write_text(
+ "[Guide home](user-guide/index.md) "
+ "[Configuration](user-guide/configuration.md?tab=redis#cache)"
+ )
+ (docs_dir / "reference/security.md").write_text("Shared security
page")
+ (docs_dir / "user-guide/index.md").write_text("Guide home")
+ (docs_dir / "user-guide/configuration.md").write_text("Versioned
page")
+
+ pages = phd.versioned_page_urls(docs_dir, "latest")
+ self.assertTrue(phd.rewrite_file(index, docs_dir,
versioned_pages=pages))
+ self.assertEqual(
+ index.read_text(),
+ "[Guide
home](/superset-kubernetes-operator/latest/user-guide/) "
+
"[Configuration](/superset-kubernetes-operator/latest/user-guide/configuration/?tab=redis#cache)",
+ )
+
+ def
test_versioned_page_keeps_links_to_other_versioned_pages_relative(self):
+ with tempfile.TemporaryDirectory() as directory:
+ docs_dir = Path(directory)
+ (docs_dir / "user-guide").mkdir()
+ page = docs_dir / "user-guide/index.md"
+ page.write_text("[Configuration](configuration.md)")
+ (docs_dir /
"user-guide/configuration.md").write_text("Configuration")
+
+ pages = phd.versioned_page_urls(docs_dir, "latest")
+ phd.rewrite_file(page, docs_dir, versioned_pages=pages)
+
+ self.assertEqual(page.read_text(),
"[Configuration](configuration.md)")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/zensical.toml b/zensical-unversioned.toml
similarity index 52%
copy from zensical.toml
copy to zensical-unversioned.toml
index 7d22c44..b0bc280 100644
--- a/zensical.toml
+++ b/zensical-unversioned.toml
@@ -20,35 +20,49 @@ site_description = "Kubernetes operator for deploying and
managing Apache Supers
repo_url = "https://github.com/apache/superset-kubernetes-operator"
repo_name = "apache/superset-kubernetes-operator"
+extra = { scope = "/superset-kubernetes-operator/" }
+
nav = [
- { Home = "index.md" },
- { "Getting Started" = "getting-started.md" },
+ { Home = "/superset-kubernetes-operator/" },
+ { "Getting Started" =
"/superset-kubernetes-operator/latest/getting-started/" },
{ "User Guide" = [
- { Installation = "user-guide/installation.md" },
- { Configuration = "user-guide/configuration.md" },
- { Lifecycle = "user-guide/lifecycle.md" },
- { "Networking & Monitoring" = "user-guide/networking-and-monitoring.md" },
- { "Migration from Helm Chart" = "user-guide/migration.md" },
+ { Installation =
"/superset-kubernetes-operator/latest/user-guide/installation/" },
+ { Configuration =
"/superset-kubernetes-operator/latest/user-guide/configuration/" },
+ { Lifecycle = "/superset-kubernetes-operator/latest/user-guide/lifecycle/"
},
+ { "Networking & Monitoring" =
"/superset-kubernetes-operator/latest/user-guide/networking-and-monitoring/" },
+ { "Migration from Helm Chart" =
"/superset-kubernetes-operator/latest/user-guide/migration/" },
] },
{ Architecture = [
- { Overview = "architecture/overview.md" },
- { Internals = "architecture/internals.md" },
+ { Overview = "/superset-kubernetes-operator/latest/architecture/overview/"
},
+ { Internals =
"/superset-kubernetes-operator/latest/architecture/internals/" },
] },
{ Reference = [
- { "API Reference" = "reference/api-reference.md" },
- { Downloads = "reference/downloads.md" },
- { Releases = "reference/releases.md" },
- { Security = "reference/security.md" },
+ { "API Reference" =
"/superset-kubernetes-operator/latest/reference/api-reference/" },
+ { Downloads = "/superset-kubernetes-operator/reference/downloads/" },
+ { Releases = "/superset-kubernetes-operator/reference/releases/" },
+ { Security = "/superset-kubernetes-operator/reference/security/" },
] },
{ Contributing = [
- { "Development Setup" = "contributing/development-setup.md" },
- { "Development Guidelines" = "contributing/development-guidelines.md" },
- { Releasing = "contributing/releasing.md" },
+ { "Development Setup" =
"/superset-kubernetes-operator/contributing/development-setup/" },
+ { "Development Guidelines" =
"/superset-kubernetes-operator/contributing/development-guidelines/" },
+ { Releasing = "/superset-kubernetes-operator/contributing/releasing/" },
] },
]
-extra_css = ["stylesheets/extra.css"]
-extra_javascript = ["https://unpkg.com/mermaid@11/dist/mermaid.min.js"]
+# The root site owns only project-level documentation. Version-sensitive
+# documentation is built with zensical-versioned.toml into /main/ or /<minor>/.
+exclude_docs = """
+getting-started.md
+user-guide/**
+architecture/**
+reference/api-reference.md
+"""
+
+extra_css = ["stylesheets/extra.css", "stylesheets/version-banner.css"]
+extra_javascript = [
+ "javascripts/version-switcher.js",
+ "https://unpkg.com/mermaid@11/dist/mermaid.min.js",
+]
[project.theme]
features = [
diff --git a/zensical.toml b/zensical-versioned.toml
similarity index 70%
copy from zensical.toml
copy to zensical-versioned.toml
index 7d22c44..163613b 100644
--- a/zensical.toml
+++ b/zensical-versioned.toml
@@ -20,8 +20,10 @@ site_description = "Kubernetes operator for deploying and
managing Apache Supers
repo_url = "https://github.com/apache/superset-kubernetes-operator"
repo_name = "apache/superset-kubernetes-operator"
+extra = { scope = "/superset-kubernetes-operator/" }
+
nav = [
- { Home = "index.md" },
+ { Home = "/superset-kubernetes-operator/" },
{ "Getting Started" = "getting-started.md" },
{ "User Guide" = [
{ Installation = "user-guide/installation.md" },
@@ -36,19 +38,32 @@ nav = [
] },
{ Reference = [
{ "API Reference" = "reference/api-reference.md" },
- { Downloads = "reference/downloads.md" },
- { Releases = "reference/releases.md" },
- { Security = "reference/security.md" },
+ { Downloads = "/superset-kubernetes-operator/reference/downloads/" },
+ { Releases = "/superset-kubernetes-operator/reference/releases/" },
+ { Security = "/superset-kubernetes-operator/reference/security/" },
] },
{ Contributing = [
- { "Development Setup" = "contributing/development-setup.md" },
- { "Development Guidelines" = "contributing/development-guidelines.md" },
- { Releasing = "contributing/releasing.md" },
+ { "Development Setup" =
"/superset-kubernetes-operator/contributing/development-setup/" },
+ { "Development Guidelines" =
"/superset-kubernetes-operator/contributing/development-guidelines/" },
+ { Releasing = "/superset-kubernetes-operator/contributing/releasing/" },
] },
]
-extra_css = ["stylesheets/extra.css"]
-extra_javascript = ["https://unpkg.com/mermaid@11/dist/mermaid.min.js"]
+# Keep strict link checking scoped to this page set. Versioned documentation
+# stays local while project-level pages are linked from the shared site root.
+exclude_docs = """
+index.md
+reference/downloads.md
+reference/releases.md
+reference/security.md
+contributing/**
+"""
+
+extra_css = ["stylesheets/extra.css", "stylesheets/version-banner.css"]
+extra_javascript = [
+ "javascripts/version-switcher.js",
+ "https://unpkg.com/mermaid@11/dist/mermaid.min.js",
+]
[project.theme]
features = [
diff --git a/zensical.toml b/zensical.toml
index 7d22c44..ace6ed3 100644
--- a/zensical.toml
+++ b/zensical.toml
@@ -20,6 +20,8 @@ site_description = "Kubernetes operator for deploying and
managing Apache Supers
repo_url = "https://github.com/apache/superset-kubernetes-operator"
repo_name = "apache/superset-kubernetes-operator"
+extra = { scope = "/superset-kubernetes-operator/" }
+
nav = [
{ Home = "index.md" },
{ "Getting Started" = "getting-started.md" },