Skip to content

Commit

Permalink
MAINT: clean up conf.py with new Sphinx extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
redeboer committed Dec 9, 2023
1 parent 2a9fa41 commit d39925f
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 199 deletions.
1 change: 1 addition & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
*.doctree
*.inv
*build/
api/

!_static/*
286 changes: 87 additions & 199 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,78 +1,75 @@
"""Configuration file for the Sphinx documentation builder.
This file only contains a selection of the most common options. For a full list see the
documentation:
https://www.sphinx-doc.org/en/master/usage/configuration.html
documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html
"""

# pyright: reportMissingImports=false
from __future__ import annotations

import os
import re
import sys
from datetime import datetime
from functools import lru_cache

if sys.version_info < (3, 8):
from importlib_metadata import PackageNotFoundError
from importlib_metadata import version as get_package_version
else:
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as get_package_version

# -- Project information -----------------------------------------------------
project = "PWA Software Pages"
PACKAGE = "pwa_pages"
copyright = "2020, ComPWA" # noqa: A001
author = "Common Partial Wave Analysis"


def get_branch_name() -> str:
branch = os.environ.get("READTHEDOCS_VERSION")
if branch == "latest":
branch = "main"
if branch is None:
branch = os.environ.get("GITHUB_REF", "main")
branch = branch.replace("refs/heads/", "") # type: ignore[union-attr]
branch = branch.replace("refs/pull/", "")
branch = branch.replace("refs/tags/", "")
if re.match(r"^\d+/[a-z]+$", branch) is not None: # type: ignore[arg-type]
branch = "main" # PR preview
print(f" Branch name: {branch}")
return branch


def get_repository_name() -> str:
repo = os.environ.get("GITHUB_REPOSITORY", "ComPWA/PWA-pages")
print(f" Repository: {repo}")
return repo
from sphinx_api_relink.helpers import (
get_branch_name,
get_execution_mode,
get_package_version,
pin,
pin_minor,
set_intersphinx_version_remapping,
)

set_intersphinx_version_remapping({
"ipython": {
"8.12.2": "8.12.1",
"8.12.3": "8.12.1",
},
"matplotlib": {"3.5.1": "3.5.0"},
})

BRANCH = get_branch_name()
REPO_NAME = get_repository_name()

try:
__VERSION = get_package_version(PACKAGE)
version = ".".join(__VERSION.split(".")[:3])
except PackageNotFoundError:
pass

ORGANIZATION = "ComPWA"
PACKAGE = "pwa_pages"
REPO_NAME = "PWA-pages"
REPO_TITLE = "PWA Software Pages"

# -- General configuration ---------------------------------------------------
master_doc = "index.md"
source_suffix = {
".ipynb": "myst-nb",
".md": "myst-nb",
".rst": "restructuredtext",
add_module_names = False
api_github_repo = f"{ORGANIZATION}/{REPO_NAME}"
api_target_substitutions: dict[str, str | tuple[str, str]] = {
"datetime": "datetime.datetime",
}

# The master toctree document.
master_doc = "index"
modindex_common_prefix = [
f"{PACKAGE}.",
author = "Common Partial Wave Analysis"
autodoc_default_options = {
"members": True,
"undoc-members": True,
"show-inheritance": True,
"special-members": ", ".join([
"__call__",
"__eq__",
]),
}
autosectionlabel_prefix_document = True
bibtex_bibfiles = ["bibliography.bib"]
bibtex_default_style = "unsrt_et_al"
bibtex_reference_style = "author_year"
codeautolink_concat_default = True
codeautolink_global_preface = """
from IPython.display import display
"""
comments_config = {
"hypothesis": True,
"utterances": {
"repo": f"{ORGANIZATION}/{REPO_NAME}",
"issue-term": "pathname",
"label": "📝 Docs",
},
}
copybutton_prompt_is_regexp = True
copybutton_prompt_text = r">>> |\.\.\. " # doctest
copyright = f"2020, {ORGANIZATION}"
default_role = "py:obj"
exclude_patterns = [
"**.ipynb_checkpoints",
"*build",
]

extensions = [
"myst_nb",
"sphinx.ext.autodoc",
Expand All @@ -82,9 +79,8 @@ def get_repository_name() -> str:
"sphinx.ext.mathjax",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
"sphinx_codeautolink",
"sphinx_api_relink",
"sphinx_codeautolink",
"sphinx_comments",
"sphinx_copybutton",
"sphinx_design",
Expand All @@ -94,26 +90,7 @@ def get_repository_name() -> str:
"sphinx_togglebutton",
"sphinxcontrib.bibtex",
]
exclude_patterns = [
"**.ipynb_checkpoints",
"*build",
]

# General sphinx settings
add_module_names = False
autodoc_default_options = {
"members": True,
"undoc-members": True,
"show-inheritance": True,
"special-members": ", ".join([
"__call__",
"__eq__",
]),
}
codeautolink_concat_default = True
codeautolink_global_preface = """
from IPython.display import display
"""
generate_apidoc_package_path = f"../src/{PACKAGE}"
graphviz_output_format = "svg"
html_copy_source = True # needed for download notebook button
html_css_files = ["custom.css"]
Expand All @@ -126,7 +103,7 @@ def get_repository_name() -> str:
html_static_path = ["_static"]
html_theme = "sphinx_book_theme"
html_theme_options = {
"repository_url": f"https://github.com/{REPO_NAME}",
"repository_url": f"https://github.com/{ORGANIZATION}/{REPO_NAME}",
"repository_branch": BRANCH,
"path_to_docs": "docs",
"use_download_button": True,
Expand All @@ -142,91 +119,13 @@ def get_repository_name() -> str:
},
}
html_title = "Partial Wave Analysis"
pygments_style = "sphinx"
todo_include_todos = True
viewcode_follow_imported_members = True

# Cross-referencing configuration
default_role = "py:obj"
primary_domain = "py"
nitpicky = True # warn if cross-references are missing

# Intersphinx settings
version_remapping = {
"ipython": {
"8.12.2": "8.12.1",
"8.12.3": "8.12.1",
},
"matplotlib": {"3.5.1": "3.5.0"},
}


def get_version(package_name: str) -> str:
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
constraints_path = f"../.constraints/py{python_version}.txt"
package_name = package_name.lower()
with open(constraints_path) as stream:
constraints = stream.read()
for line in constraints.split("\n"):
line = line.split("#")[0] # remove comments
line = line.strip()
line = line.lower()
if not line.startswith(package_name):
continue
if not line:
continue
line_segments = tuple(line.split("=="))
if len(line_segments) != 2: # noqa: PLR2004
continue
_, installed_version, *_ = line_segments
installed_version = installed_version.strip()
remapped_versions = version_remapping.get(package_name)
if remapped_versions is not None:
existing_version = remapped_versions.get(installed_version)
if existing_version is not None:
return existing_version
return installed_version
return "stable"


def get_minor_version(package_name: str) -> str:
installed_version = get_version(package_name)
if installed_version == "stable":
return installed_version
matches = re.match(r"^([0-9]+\.[0-9]+).*$", installed_version)
if matches is None:
msg = f"Could not find documentation for {package_name} v{installed_version}"
raise ValueError(msg)
return matches[1]


intersphinx_mapping = {
"IPython": (
f"https://ipython.readthedocs.io/en/{get_version('IPython')}",
None,
),
"matplotlib": (
f"https://matplotlib.org/{get_version('matplotlib')}",
None,
),
"IPython": (f"https://ipython.readthedocs.io/en/{pin('IPython')}", None),
"matplotlib": (f"https://matplotlib.org/{pin('matplotlib')}", None),
"python": ("https://docs.python.org/3", None),
"pydantic": (f"https://docs.pydantic.dev/{pin_minor('pydantic')}", None),
"sympy": ("https://docs.sympy.org/latest", None),
}

# Settings for autosectionlabel
autosectionlabel_prefix_document = True

# Settings for bibtex
bibtex_bibfiles = [
"bibliography.bib",
]
bibtex_reference_style = "author_year"

# Settings for copybutton
copybutton_prompt_is_regexp = True
copybutton_prompt_text = r">>> |\.\.\. " # doctest

# Settings for linkcheck
linkcheck_anchors = False
linkcheck_ignore = [
"http://127.0.0.1:8000",
Expand All @@ -236,31 +135,10 @@ def get_minor_version(package_name: str) -> str:
"https://home.fnal.gov/~kutschke/Angdist/angdist.ps",
"https://physique.cuso.ch",
"https://suchung.web.cern.ch",
"https://www.bookfinder.com",
]


# Settings for myst_nb
def get_execution_mode() -> str:
if "FORCE_EXECUTE_NB" in os.environ:
print_once("\033[93;1mWill run ALL Jupyter notebooks!\033[0m")
return "force"
if "EXECUTE_NB" in os.environ:
return "cache"
return "off"


@lru_cache(maxsize=None)
def print_once(message: str) -> None:
print(message)


nb_execution_mode = get_execution_mode()
nb_execution_show_tb = True
nb_execution_timeout = -1
nb_output_stderr = "remove"
nb_execution_show_tb = True

# Settings for myst-parser
master_doc = "index"
modindex_common_prefix = [f"{PACKAGE}."]
myst_enable_extensions = [
"amsmath",
"colon_fence",
Expand All @@ -274,19 +152,29 @@ def print_once(message: str) -> None:
"repo": REPO_NAME,
}
myst_update_mathjax = False

# Settings for sphinx_comments
comments_config = {
"hypothesis": True,
"utterances": {
"repo": f"ComPWA/{REPO_NAME}",
"issue-term": "pathname",
"label": "📝 Docs",
},
nb_execution_mode = get_execution_mode()
nb_execution_show_tb = True
nb_execution_timeout = -1
nb_output_stderr = "remove"
nitpick_ignore_regex = [
(r"py:(class|obj)", "ConfigDict"),
(r"py:(class|obj)", "FieldInfo"),
(r"py:(class|obj)", "Model.__fields__"),
(r"py:(class|obj)", "pydantic.main.BaseModel"),
]
nitpicky = True
primary_domain = "py"
project = REPO_TITLE
pygments_style = "sphinx"
release = get_package_version(PACKAGE)
source_suffix = {
".ipynb": "myst-nb",
".md": "myst-nb",
".rst": "restructuredtext",
}

# Settings for Thebe cell output
thebe_config = {
"repository_url": html_theme_options["repository_url"],
"repository_branch": html_theme_options["repository_branch"],
}
todo_include_todos = True
version = get_package_version(PACKAGE)
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ analysis
caption: Appendices
hidden:
---
API <api/pwa_pages>
glossary
references
```
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ task-tags = ["cspell"]
"S113",
"T201",
]
"docs/conf.py" = ["A001"]
"setup.py" = ["D100"]
"src/pwa_pages/project_inventory.py" = [
"FA100",
Expand Down
2 changes: 2 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ commands =
--re-ignore docs/.*\.yaml \
--re-ignore docs/.*\.yml \
--re-ignore docs/_build/.* \
--re-ignore docs/api \
--watch docs \
docs/ docs/_build/html
description =
Expand Down Expand Up @@ -108,6 +109,7 @@ commands =
--re-ignore docs/.*\.yaml \
--re-ignore docs/.*\.yml \
--re-ignore docs/_build/.* \
--re-ignore docs/api \
--watch docs \
docs/ docs/_build/html
description =
Expand Down

0 comments on commit d39925f

Please sign in to comment.