Repository navigation
Enable version switcher in Python documentation #92
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
d742f34
705e096
399b4da
09567b9
302588f
df2ac46
b60343a
3f34133
de3696e
6e8a4b3
1a98527
0b31c29
98c628b
b7c60fe
eb8ca7d
75bd668
0de6e35
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "html_site_root": "https://multi-objective.github.io/moocore/python/" | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
|
||
| 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, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| """Update versions.json for PyData Sphinx Theme version switcher.""" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ""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/" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This url should be taken from |
||
|
|
||
|
|
||
| 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() | ||
Uh oh!
There was an error while loading. Please reload this page.