Debian Codegraph @

src/pydata_sphinx_theme/utils.py

raw
1 """General helpers for the management of config parameters."""
2
3 import copy
4 import os
5 import re
6
7 from typing import Any, Callable, Dict, Iterable, List, Optional, Union
8
9 from docutils.nodes import Node
10 from sphinx.application import Sphinx
11 from sphinx.util import logging, matching
12
13
14 def get_theme_options_dict(app: Sphinx) -> Dict[str, Any]:
15 """Return theme options for the application w/ a fallback if they don't exist.
16
17 The "top-level" mapping (the one we should usually check first, and modify
18 if desired) is ``app.builder.theme_options``. It is created by Sphinx as a
19 copy of ``app.config.html_theme_options`` (containing user-configs from
20 their ``conf.py``); sometimes that copy never occurs though which is why we
21 check both.
22 """
23 if (
24 hasattr(app, "builder")
25 and app.builder is not None
26 and hasattr(app.builder, "theme_options")
27 ):
28 return app.builder.theme_options
29 elif hasattr(app.config, "html_theme_options"):
30 return app.config.html_theme_options
31 else:
32 return {}
33
34
35 def config_provided_by_user(app: Sphinx, key: str) -> bool:
36 """Check if the user has manually provided the config."""
37 return any(key in ii for ii in [app.config.overrides, app.config._raw_config])
38
39
40 def traverse_or_findall(
41 node: Node, condition: Union[Callable, type], **kwargs
42 ) -> Iterable[Node]:
43 """Triage node.traverse (docutils <0.18.1) vs node.findall.
44
45 TODO: This check can be removed when the minimum supported docutils version
46 for numpydoc is docutils>=0.18.1.
47 """
48 return (
49 node.findall(condition, **kwargs)
50 if hasattr(node, "findall")
51 else node.traverse(condition, **kwargs)
52 )
53
54
55 def escape_ansi(string: str) -> str:
56 """Helper function to remove ansi coloring from sphinx warnings."""
57 ansi_escape = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]")
58 return ansi_escape.sub("", string)
59
60
61 SPHINX_LOGGER = logging.getLogger(__name__)
62
63
64 def maybe_warn(app: Sphinx, msg, *args, **kwargs):
65 """Wraps the Sphinx logger to allow warning suppression."""
66 theme_options = get_theme_options_dict(app)
67 should_warn = theme_options.get("surface_warnings", False)
68 if should_warn:
69 SPHINX_LOGGER.warning(msg, *args, **kwargs)
70 else:
71 SPHINX_LOGGER.info(msg, *args, **kwargs)
72
73
74 def set_secondary_sidebar_items(
75 app: Sphinx, pagename: str, templatename: str, context, doctree
76 ) -> None:
77 """Set the secondary sidebar items to render for the given pagename."""
78 if "theme_secondary_sidebar_items" in context:
79 templates = context["theme_secondary_sidebar_items"]
80 if isinstance(templates, dict):
81 templates = _get_matching_sidebar_items(pagename, templates)
82
83 context["secondary_sidebar_items"] = _update_and_remove_templates(
84 app,
85 context,
86 templates,
87 "theme_secondary_sidebar_items",
88 )
89
90
91 def _update_and_remove_templates(
92 app: Sphinx,
93 context: Dict[str, Any],
94 templates: Union[List, str],
95 section: str,
96 templates_skip_empty_check: Optional[List[str]] = None,
97 ) -> List[str]:
98 """
99 Update templates to include html suffix if needed; remove templates which render
100 empty.
101
102 Args:
103 app: Sphinx application passed to the html page context
104 context: The html page context; dictionary of values passed to the templating
105 engine
106 templates: A list of template names, or a string of comma separated template
107 names
108 section: Name of the template section where the templates are to be rendered.
109 Valid section names include any of the ``sphinx`` or ``html_theme_options``
110 that take templates or lists of templates as arguments, for example:
111 ``theme_navbar_start``, ``theme_primary_sidebar_end``,
112 ``theme_secondary_sidebar_items``, ``sidebars``, etc.
113 For a complete list of valid section names, see the source for
114 :py:func:`pydata_sphinx_theme.update_and_remove_templates` and
115 :py:func:`pydata_sphinx_theme.utils.set_secondary_sidebar_items`,
116 both of which call this function.
117 templates_skip_empty_check: Names of any templates which should never be removed
118 from the list of filtered templates returned by this function.
119 These templates aren't checked if they render empty, which can save time if
120 the template is slow to render.
121
122 Returns:
123 A list of template names (including '.html' suffix) to render into the section
124 """
125 if templates_skip_empty_check is None:
126 templates_skip_empty_check = []
127
128 # Break apart `,` separated strings so we can use , in the defaults
129 if isinstance(templates, str):
130 templates = [template.strip() for template in templates.split(",")]
131
132 # Add `.html` to templates with no suffix
133 suffixed_templates = []
134 for template in templates:
135 if os.path.splitext(template)[1]:
136 suffixed_templates.append(template)
137 else:
138 suffixed_templates.append(f"{template}.html")
139
140 ctx = copy.copy(context)
141 ctx.update({section: suffixed_templates})
142
143 # Check whether the template renders to an empty string; remove if this is the case
144 # Skip templates that are slow to render with templates_skip_empty_check
145 filtered_templates = []
146 for template in suffixed_templates:
147 if any(template.endswith(item) for item in templates_skip_empty_check):
148 filtered_templates.append(template)
149 else:
150 rendered = app.builder.templates.render(template, ctx)
151 if len(rendered.strip()) != 0:
152 filtered_templates.append(template)
153
154 return filtered_templates
155
156
157 def _get_matching_sidebar_items(
158 pagename: str, sidebars: Dict[str, List[str]]
159 ) -> List[str]:
160 """Get the matching sidebar templates to render for the given pagename.
161
162 If a page matches more than one pattern, a warning is emitted, and the templates
163 for the last matching pattern are used.
164
165 This function was adapted from
166 sphinx.builders.html.StandaloneHTMLBuilder.add_sidebars.
167 """
168 matched = None
169 secondary_sidebar_items = []
170 for pattern, sidebar_items in sidebars.items():
171 if matching.patmatch(pagename, pattern):
172 if matched and _has_wildcard(pattern) and _has_wildcard(matched):
173 (
174 SPHINX_LOGGER.warning(
175 "Page %s matches two wildcard patterns in secondary_sidebar_items: %s and %s", # noqa: E501
176 pagename,
177 matched,
178 pattern,
179 ),
180 )
181 matched = pattern
182 secondary_sidebar_items = sidebar_items
183 return secondary_sidebar_items
184
185
186 def _has_wildcard(pattern: str) -> bool:
187 """Check whether the pattern contains a wildcard.
188
189 Taken from sphinx.builders.StandaloneHTMLBuilder.add_sidebars.
190 """
191 return any(char in pattern for char in "*?[")