Debian Codegraph @

sphinx_favicon/__init__.py

raw
1 """Sphinx extension to add custom favicons.
2
3 With sphinx-favicon, you can add custom favicons to your Sphinx html documentation quickly and easily.
4
5 You can define favicons directly in your conf.py, with different rel attributes such as "icon" or "apple-touch-icon" and any favicon size.
6
7 The sphinx-favicon extension gives you more flexibility than the standard favicon.ico supported by Sphinx. It provides a quick and easy way to add the most important favicon formats for different browsers and devices.
8 """
9
10 from io import BytesIO
11 from os import PathLike
12 from pathlib import Path
13 from typing import Any, Callable, Dict, List, Optional, Sequence, Union, cast
14 from urllib.parse import urlparse
15
16 import docutils.nodes as nodes
17 import imagesize
18 import requests
19 from requests.exceptions import RequestException
20 from sphinx.application import Sphinx
21 from sphinx.util import logging
22
23 logger = logging.getLogger(__name__)
24
25 # Configuration type accepted for `favicons` in conf.py
26 # Support a single dict, or a list of dicts/strings (strings are shorthand for {"href": <value>})
27 FaviconsDef = Union[Dict[str, str], List[Union[Dict[str, str], str]]]
28
29 OUTPUT_STATIC_DIR: str = "_static"
30 "output folder for static items in the html builder"
31
32 FILE_FIELD: str = "static-file"
33 "field in the ``FaviconsDef`` pointing to file in the ``html_static_path``"
34
35 SUPPORTED_MIME_TYPES: Dict[str, str] = {
36 "bmp": "image/x-ms-bmp",
37 "gif": "image/gif",
38 "ico": "image/x-icon",
39 "jpeg": "image/jpeg",
40 "jpg": "image/jpeg",
41 "png": "image/png",
42 "svg": "image/svg+xml",
43 }
44 "supported mime types of the link tag"
45
46
47 SUPPORTED_SIZE_TYPES: List[str] = ["bmp", "gif", "jpeg", "jpg", "png"]
48 "list of file type that can be used to compute size"
49
50
51 def generate_meta(favicon: Dict[str, str]) -> str:
52 """Generate metatag based on favicon data.
53
54 Default behavior:
55 - If favicon data contains no ``rel`` attribute, sets ``rel="icon"``
56 - If no ``sizes`` attribute is provided, ``sizes`` will be computed from the file
57 - If no favicon MIME type is provided, the value for ``type`` will be
58 based on the favicon's file name extension (for BMP, GIF, ICO, JPG, JPEG,
59 SVG, or PNG files)
60
61 Args:
62 favicon: Favicon data
63
64 Returns:
65 Favicon link or meta tag
66 """
67 # get the tag of the output
68 tag = "meta" if "name" in favicon else "link"
69
70 # default to "icon" for link elements
71 if tag == "link":
72 favicon.setdefault("rel", "icon")
73 favicon["href"] # to raise an error if not set
74 extension = favicon["href"].split(".")[-1]
75
76 # set the type for link elements.
77 # if type is not set, try to guess it from the file extension
78 type_ = favicon.get("type")
79 if not type_ and tag == "link" and extension in SUPPORTED_MIME_TYPES:
80 type_ = SUPPORTED_MIME_TYPES[extension]
81 favicon["type"] = type_
82
83 # build the html element
84 parameters = [f'{k}="{v}"' for k, v in favicon.items() if v is not None]
85 html_element = f" <{tag} {' '.join(parameters)}>"
86
87 return html_element
88
89
90 def _sizes(
91 favicon: Dict[str, str],
92 static_path: Sequence[Union[str, PathLike[str]]],
93 confdir: Union[str, PathLike[str]],
94 ) -> Dict[str, str]:
95 """Compute the size of the favicon if its size is not explicitly defined.
96
97 If the file is a SUPPORTED_MIME_TYPES, then the size is computed on the fly and added
98 to the favicon attributes. Don't do anything if the favicon is not a link tag.
99
100 Args:
101 favicon: The favicon description as set in the conf.py file
102 static_path: The static_path registered in the application
103 confdir: The source directory of the documentation
104
105 Returns:
106 The favicon with a fully qualified size
107 """
108 # exit if the favicon tag has no href (like meta)
109 if not (FILE_FIELD in favicon or "href" in favicon):
110 return favicon
111
112 # init the parameters
113 link: Optional[str] = favicon.get("href") or favicon.get(FILE_FIELD)
114 extension: Optional[str] = link.split(".")[-1] if link else None
115 sizes: Optional[str] = favicon.get("sizes")
116
117 # get the size automatically if not supplied
118 if link and sizes is None and extension in SUPPORTED_SIZE_TYPES:
119 file: Optional[Union[BytesIO, Path]] = None
120 if bool(urlparse(link).netloc):
121 try:
122 response = requests.get(link)
123 except RequestException:
124 response = requests.Response()
125 response.status_code = -1
126
127 if response.status_code == 200:
128 file = BytesIO(response.content)
129 else:
130 logger.warning(
131 f"The provided link ({link}) cannot be read. "
132 "Size will not be computed."
133 )
134 else:
135 for folder in static_path:
136 path = Path(confdir) / folder / link
137 if path.is_file():
138 file = path
139 break
140 if file is None:
141 logger.warning(
142 f"The provided path ({link}) is not part of any of the static path. "
143 "Size will not be computed."
144 )
145
146 # compute the image size if image file is found
147 if file is not None:
148 w, h = imagesize.get(file)
149 size = f"{int(w)}x{int(h)}"
150 favicon["sizes"] = size
151
152 return favicon
153
154
155 def _static_to_href(pathto: Callable, init_favicon: Dict[str, str]) -> Dict[str, str]:
156 """Replace static ref to fully qualified href.
157
158 if the ``href`` is a relative path then it's replaced with the correct ``href``. We keep checking for ``static-file`` for legacy reasons.
159 If both ``static-file`` and ``href`` are provided, ``href`` will be ignored.
160 If the favicon has no ``href`` nor ``static-file`` then do nothing.
161
162 Args:
163 pathto: Sphinx helper_ function to handle relative URLs
164 init_favicon: The favicon description as set in the conf.py file
165
166 Returns:
167 The favicon with a fully qualified href
168 """
169 # work on a copy of the favicon (mutable issue)
170 favicon = init_favicon.copy()
171
172 # exit if the favicon tag has no href (like meta)
173 if not (FILE_FIELD in favicon or "href" in favicon):
174 return favicon
175
176 # legacy check for "static-file"
177 if FILE_FIELD in favicon:
178 favicon["href"] = favicon.pop(FILE_FIELD)
179
180 # check if link is absolute
181 link = favicon["href"]
182 is_absolute = bool(urlparse(link).netloc) or link.startswith("/")
183
184 # if the link is absolute do nothing, else replace it with a full one
185 if not is_absolute:
186 # `pathto` may return a `_StrPath`, cast to `str` for consistent typing
187 favicon["href"] = str(pathto(f"{OUTPUT_STATIC_DIR}/{link}", resource=True))
188
189 return favicon
190
191
192 def create_favicons_meta(
193 pathto: Callable,
194 favicons: FaviconsDef,
195 static_path: Sequence[Union[str, PathLike[str]]],
196 confdir: Union[str, PathLike[str]],
197 ) -> Optional[str]:
198 """Create ``<link>`` elements for favicons defined in configuration.
199
200 Args:
201 pathto: Sphinx helper_ function to handle relative URLs
202 favicons: Favicon data from configuration. Can be a single dict or a list of dicts.
203 static_path: the static_path registered in the application
204 confdir: the source directory of the documentation
205
206 Returns:
207 ``<link>`` elements for all favicons.
208
209 See Also:
210 https://www.sphinx-doc.org/en/master/templating.html#path
211 """
212 # force cast the favicon config as a list
213 if isinstance(favicons, dict):
214 favicons = [favicons]
215
216 # read this list and create the links for each item
217 meta_favicons = []
218 for favicon in favicons:
219 if isinstance(favicon, str):
220 favicon = {"href": favicon}
221
222 if not isinstance(favicon, dict):
223 logger.warning(
224 f"Invalid config value for favicon extension: {favicon}."
225 "Custom favicons will not be included in build."
226 )
227 continue
228 favicon = cast(Dict[str, str], favicon)
229 favicon = _sizes(favicon, static_path, confdir)
230 tag = generate_meta(_static_to_href(pathto, favicon))
231 meta_favicons.append(tag)
232
233 return "\n".join(meta_favicons)
234
235
236 def html_page_context(
237 app: Sphinx,
238 pagename: str,
239 templatename: str,
240 context: Dict[str, Any],
241 doctree: nodes.document,
242 ) -> None:
243 """Update the html page context by adding the favicons.
244
245 Args:
246 app: The sphinx application
247 pagename: the name of the page as string
248 templatename: the name of the template as string
249 context: the html context dictionary
250 doctree: the docutils document tree
251 """
252 # extract parameters from app
253 favicons: Optional[FaviconsDef] = app.config["favicons"]
254 pathto: Callable = context["pathto"]
255 static_path = cast(Sequence[Union[str, PathLike[str]]], app.config["html_static_path"]) # type: ignore[assignment]
256 confdir: Union[str, PathLike[str]] = app.confdir
257
258 if not (doctree and favicons):
259 return
260
261 favicons_meta = create_favicons_meta(pathto, favicons, static_path, confdir)
262 context["metatags"] += favicons_meta
263
264
265 def setup(app: Sphinx) -> Dict[str, Any]:
266 """Add custom configuration to sphinx app.
267
268 Args:
269 app: the Sphinx application
270
271 Returns:
272 the 2 parralel parameters set to ``True``
273 """
274 app.add_config_value("favicons", None, "html")
275 app.connect("html-page-context", html_page_context)
276
277 return {
278 "parallel_read_safe": True,
279 "parallel_write_safe": True,
280 }