diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index d3dcd1e81..f4a58221b 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -148,8 +148,9 @@ jobs: - name: Build the docs 🔧 env: - DEST: ${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || 'main' }} + DEST: ${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.event_name == 'release' && github.ref_name || 'dev' }} run: | + DEST="${DEST#v}" make -C doc html mkdir ../staging mv doc/_build/html "../staging/$DEST" @@ -165,7 +166,7 @@ jobs: deploy-docs: name: Deploy docs needs: build-doc - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + if: (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'release' && github.event.action == 'published') runs-on: ubuntu-latest permissions: contents: write @@ -182,14 +183,32 @@ jobs: with: name: docs-python path: artifact - + - name: Prepare versions.json + id: ver + env: + VERSION: ${{ github.event_name == 'release' && github.ref_name || 'dev' }} + run: | + VERSION="${VERSION#v}" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + python3 python/doc/update_versions.py "$VERSION" + if [ "${{ github.event_name }}" = "release" ]; then + ln -sfn "$VERSION" versions_meta/stable + fi + - name: Deploy 🚀 uses: JamesIves/github-pages-deploy-action@v4 with: - folder: artifact/main - target-folder: python + folder: artifact/${{ steps.ver.outputs.version }} + target-folder: python/${{ steps.ver.outputs.version }} single-commit: true clean: true + - name: Deploy versions.json + uses: JamesIves/github-pages-deploy-action@v4 + with: + folder: versions_meta + target-folder: python + single-commit: true + clean: false coverage: timeout-minutes: 15 diff --git a/python/doc/site.json b/python/doc/site.json new file mode 100644 index 000000000..c15c7d3d5 --- /dev/null +++ b/python/doc/site.json @@ -0,0 +1,3 @@ +{ + "html_site_root": "https://multi-objective.github.io/moocore/python/" +} diff --git a/python/doc/source/conf.py b/python/doc/source/conf.py index 2d820c184..ec88c2b6d 100644 --- a/python/doc/source/conf.py +++ b/python/doc/source/conf.py @@ -8,9 +8,11 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information +import json import os import sys from datetime import date +from pathlib import Path import sphinx @@ -34,7 +36,12 @@ # Can we get this from pyproject.toml ? author = "Manuel López-Ibáñez and Fergus Rooney" copyright = f"2024-{year}, {author}" -html_site_root = f"https://multi-objective.github.io/{project}/python/" +_site_config = json.loads( + (Path(__file__).resolve().parent.parent / "site.json").read_text( + encoding="utf-8" + ) +) +html_site_root = _site_config["html_site_root"] github_url = f"https://github.com/multi-objective/{project}" # -- General configuration --------------------------------------------------- @@ -142,19 +149,21 @@ def setup(app): html_theme = "pydata_sphinx_theme" -# FIXME: Implement a version switch like NumPy. -# Set up the version switcher. The versions.json is stored in the doc repo. -# if os.environ.get('CIRCLE_JOB', False) and \ -# os.environ.get('CIRCLE_BRANCH', '') != 'main': -# # For PR, name is set to its ref -# switcher_version = os.environ['CIRCLE_BRANCH'] -# elif ".9999" in version: -# switcher_version = "devdocs" -# else: -# switcher_version = f"{version}" +# Use the version switcher metadata maintained in the gh-pages branch. +# Pull request builds use the PR ref so preview pages are not labelled as a +# released version. +if os.environ.get("GITHUB_ACTIONS") and os.environ.get("GITHUB_HEAD_REF"): + switcher_version = os.environ["GITHUB_HEAD_REF"] +elif ".dev" in version: + switcher_version = "dev" +else: + switcher_version = version + +switcher_json_url = f"{html_site_root}versions.json" html_theme_options = { "collapse_navigation": True, + "show_version_warning_banner": True, "github_url": github_url, "header_links_before_dropdown": 5, "icon_links": [ @@ -169,8 +178,7 @@ def setup(app): }, "navbar_align": "content", # Add light/dark mode and documentation version switcher: - # "navbar_end": ["theme-switcher", "version-switcher", "navbar-icon-links"], - "navbar_end": ["theme-switcher", "navbar-icon-links"], + "navbar_end": ["theme-switcher", "version-switcher", "navbar-icon-links"], "navbar_start": ["navbar-logo"], "navigation_with_keys": False, # https://sphinx-gallery.github.io/stable/advanced.html#using-sphinx-gallery-sidebar-components @@ -180,6 +188,10 @@ def setup(app): "sg_launcher_links", ], "show_prev_next": True, + "switcher": { + "json_url": switcher_json_url, + "version_match": switcher_version, + }, "show_toc_level": 2, # On this page sidebar "sidebar_includehidden": True, "use_edit_page_button": True, diff --git a/python/doc/update_versions.py b/python/doc/update_versions.py new file mode 100644 index 000000000..2ad77812d --- /dev/null +++ b/python/doc/update_versions.py @@ -0,0 +1,131 @@ +"""Update versions.json for PyData Sphinx Theme version switcher.""" + +import argparse +import json +import subprocess +from pathlib import Path + +SITE_CONFIG = json.loads( + (Path(__file__).resolve().parent / "site.json").read_text(encoding="utf-8") +) +BASE = SITE_CONFIG["html_site_root"] + + +def load_existing_versions() -> list[dict]: + """Load existing version entries from gh-pages.""" + subprocess.run(["git", "fetch", "origin", "gh-pages"], check=True) + result = subprocess.run( + ["git", "show", "origin/gh-pages:python/versions.json"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return [] + data = json.loads(result.stdout) + return data if isinstance(data, list) else [] + + +def update_versions(version: str) -> None: + """Update versions.json with the given documentation version.""" + base = BASE + data = load_existing_versions() + if version == "dev": + entry = {"name": "dev", "version": "dev", "url": base + "dev/"} + else: + entry = { + "name": f"{version} (stable)", + "version": version, + "url": f"{base}stable/", + "preferred": True, + } + for item in data: + if isinstance(item, dict): + item.pop("preferred", None) + if item.get("url") == f"{base}stable/" and item.get("version"): + item["name"] = item["version"] + item["url"] = f"{base}{item['version']}/" + + updated = [ + item + for item in data + if not (isinstance(item, dict) and item.get("version") == version) + ] + updated.append(entry) + + out_dir = Path("versions_meta") + out_dir.mkdir(parents=True, exist_ok=True) + with (out_dir / "versions.json").open("w", encoding="utf-8") as f: + json.dump(updated, f, indent=2) + f.write("\n") + + +def main() -> None: + """Parse the target version and update versions.json.""" + parser = argparse.ArgumentParser( + description="Update versions.json for PyData Sphinx Theme version switcher." + ) + parser.add_argument( + "version", help="Documentation version to add or update." + ) + args = parser.parse_args() + update_versions(args.version) + + +if __name__ == "__main__": + main() + +BASE = "https" + "://multi-objective.github.io/moocore/python/" + + +def load_existing_versions() -> list[dict]: + """Load existing version entries from gh-pages.""" + result = subprocess.run( + ["git", "show", "origin/gh-pages:python/versions.json"], + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return [] + data = json.loads(result.stdout) + return data if isinstance(data, list) else [] + + +def update_versions(version: str) -> None: + """Update versions.json with the given documentation version.""" + data = load_existing_versions() + if version == "dev": + entry = {"name": "dev", "version": "dev", "url": BASE + "dev/"} + else: + entry = { + "version": version, + "url": f"{BASE}{version}/", + "preferred": True, + } + for item in data: + if isinstance(item, dict): + item.pop("preferred", None) + + updated = [ + item + for item in data + if not (isinstance(item, dict) and item.get("version") == version) + ] + updated.append(entry) + + out_dir = Path("versions_meta") + out_dir.mkdir(parents=True, exist_ok=True) + with (out_dir / "versions.json").open("w", encoding="utf-8") as f: + json.dump(updated, f, indent=2) + f.write("\n") + + +def main() -> None: + """Parse the target version and update versions.json.""" + version = sys.argv[1] if len(sys.argv) > 1 else os.environ["VERSION"] + update_versions(version) + + +if __name__ == "__main__": + main()