Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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 }}
Comment thread
MLopez-Ibanez marked this conversation as resolved.
Resolved
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
Expand Down
3 changes: 3 additions & 0 deletions python/doc/site.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"html_site_root": "https://multi-objective.github.io/moocore/python/"
}
38 changes: 25 additions & 13 deletions python/doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 ---------------------------------------------------
Expand Down Expand Up @@ -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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you tested that this works when you build the documentation locally in your computer? The github action does not place version.json at the root of the documentation but one folder above it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

html_site_root points to .../moocore/python/ (one level above the versioned doc folders), so switcher_json_url resolves to .../moocore/python/versions.json. Local builds still succeed because PyData Sphinx Theme fetches that URL in the browser, though the dropdown stays empty until versions.json is published.


html_theme_options = {
"collapse_navigation": True,
"show_version_warning_banner": True,
"github_url": github_url,
"header_links_before_dropdown": 5,
"icon_links": [
Expand All @@ -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
Expand All @@ -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,
Expand Down
131 changes: 131 additions & 0 deletions python/doc/update_versions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Update versions.json for PyData Sphinx Theme version switcher."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to pass the version as a mandatory argument rather than reading the environment variables.

The script should also do git fetch. An updated version could be

""Update versions.json for PyData Sphinx Theme version switcher."""

import argparse
import json
import subprocess
from pathlib import Path

BASE = "https" + "://multi-objective.github.io/moocore/python/"


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."""
    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."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("version", help="documentation version to publish")
    args = parser.parse_args()
    update_versions(args.version)


if __name__ == "__main__":
    main()


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/"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This url should be taken from html_site_root in conf.py There must be a way to share common data via a site.json or some similar configuration file.



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()