-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathconf.py
More file actions
354 lines (288 loc) · 12.7 KB
/
conf.py
File metadata and controls
354 lines (288 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python
"""Sphinx configuration file"""
from typing import Any
import docutils.nodes
import os
import re
import runpy
import sphinx.ext.autodoc
import sphinx.transforms
import sys
# --- Pre-processing Tasks
# Make thumbnails for the example code screenshots
runpy.run_path('../util/generate_example_thumbnails.py', run_name='__main__')
# Create a listing of the resources
runpy.run_path('../util/create_resources_listing.py', run_name='__main__')
# Run the generate quick API index script
runpy.run_path('../util/update_quick_index.py', run_name='__main__')
autodoc_inherit_docstrings = False
autodoc_default_options = {
'members': True,
# 'member-order': 'groupwise',
'member-order': 'alphabetical',
'undoc-members': True,
'show-inheritance': True
}
toc_object_entries_show_parents = 'hide'
# Special methods in api docs gets a special prefix emoji
prettyspecialmethods_signature_prefix = '🧙'
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../arcade'))
# Don't change to
# from arcade.version import VERSION
# or read the docs build will fail.
from version import VERSION # pyright: ignore [reportMissingImports]
RELEASE = VERSION
# -- General configuration ------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx_rtd_theme', # Read the Docs theme
'sphinx_rtd_dark_mode', # Dark mode for the RTD theme
'sphinx.ext.autodoc', # API doc generation tools
'sphinx.ext.napoleon', # Support for NumPy and Google style docstrings
'sphinx.ext.imgconverter', # Converts .gif for PDF doc build
'sphinx.ext.intersphinx', # Link to other projects' docs
'sphinx.ext.viewcode', # display code with line numbers and line highlighting
'sphinx_copybutton', # Adds a copy button to code blocks
'sphinx_sitemap', # sitemap.xml generation
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'Python Arcade Library'
copyright = '2024, Paul Vincent Craven'
author = 'Paul Vincent Craven'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = VERSION
# The full version, including alpha/beta/rc tags.
release = RELEASE
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
"links.rst",
"substitutions.rst",
"_archive/*",
]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default' # will use "sphinx" or the theme's default
# If true, `todo` and `todoList` produce output, else they produce nothing.
# todo_include_todos = True
# napoleon_numpy_docstring = False
# napoleon_google_docstring = True
# Warn about all references where the target cannot be found.
# This is important to always enable to catch broken doc or api links
# nitpicky = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# See sphinx-rtd-theme docs for details on each option:
# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html
html_theme_options = {
'display_version': True,
'logo_only': False,
'sticky_navigation': True,
'navigation_depth': 4,
'collapse_navigation': False,
}
# The single config option provided by sphinx-rtd-dark-mode
# https://github.com/MrDogeBro/sphinx_rtd_dark_mode#config
default_dark_mode = True
html_title = f'Python Arcade {version}'
html_js_files = [
'https://code.jquery.com/jquery-3.6.3.min.js',
'https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js',
]
html_css_files = [
'https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css',
]
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = '_static/android-chrome-192x192.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = '_static/favicon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
html_extra_path = ['html_extra']
# Output file base name for HTML help builder.
htmlhelp_basename = 'Arcade'
html_baseurl = 'https://api.arcade.academy/'
# Fix line numbers on code listings until the RTD theme updates to sphinx 4+
# html_codeblock_linenos_style = 'table'
# Configuration for intersphinx enabling linking other projects
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'pyglet': ('https://pyglet.readthedocs.io/en/latest/', None),
'PIL': ('https://pillow.readthedocs.io/en/stable', None),
'pymunk': ('https://www.pymunk.org/en/latest/', None),
}
def strip_init_return_typehint(app, what, name, obj, options, signature, return_annotation):
# Prevent a the `-> None` annotation from appearing after classes.
# This annotation comes from the `__init__`, but it renders on the class,
# e.g. `Foo() -> None`
# From the user's perspective, this is wrong: `Foo() -> Foo` not `None`
if what == "class" and return_annotation is None:
return (signature, None)
def inspect_docstring_for_member(
_app,
what: str,
name: str,
_obj: object,
_options: dict[str, Any],
lines: list[str],
):
"""
Callback for the autodoc-process-docstring event.
Where we can plug in various sanity checks such as warning about
undocumented members.
Args:
_app: The Sphinx application object
what (string): The type of object ("attribute", "class", "module", "function", "method")
name: The fully qualified name of the object
_obj: The object being documented
_options: The autodoc options for this object
lines: The lines of the docstring
"""
# For debugging purposes
# print(
# f"app={_app}\n"
# f"what={what}\n"
# f"name={name}\n"
# f"obj={_obj}\n"
# f"options={_options}\n"
# f"lines){lines}\n"
# )
if len(lines) == 0:
print(f"{what} {name} is undocumented")
# Docstring on __init__ in classes raise an error.
# Class docstrings should cover the initializer.
if what == "class":
doc = _obj.__init__.__doc__
if doc and isinstance(doc, str) and not doc.startswith("Initialize self"):
raise ValueError((
f"Class {name} has a docstring on __init__. "
"The class docstring should cover docs for the initializer:\n {_obj.__init__.__doc__}"
))
def generate_color_table(filename, source):
"""
This function Generates the Color tables in the docs for color and csscolor packages.
"""
append_text = "\n\n.. raw:: html\n\n"
append_text += " <table class='colorTable'><tbody>\n"
# Will match a line containing:
# name '(?P<name>[a-z_A-Z]*)' followed by
# a Color '(?: *= *Color *\( *)' followed by
# red '(?P<red>\d*)' followed by
# green '(?P<green>\d*)' followed by
# blue '(?P<blue>\d*)' followed by
# alpha '(?P<alpha>\d*)'
color_match = re.compile(r'(?P<name>[a-z_A-Z]*)(?:[ =]*Color[ (]*)(?P<red>\d*)[ ,]*(?P<green>\d*)[ ,]*(?P<blue>\d*)[ ,]*(?P<alpha>\d*)')
with open(filename) as color_file:
for line in color_file:
# Check if the line has a Color.
matches = color_match.match(line)
if not matches:
continue
color_rgba = f"({matches.group('red')}, {matches.group('green')}, {matches.group('blue')}, {matches.group('alpha')})"
# Generate the alpha for CSS color function
alpha = int( matches.group('alpha') ) / 255
css_rgba = f"({matches.group('red')}, {matches.group('green')}, {matches.group('blue')}, {alpha!s:.4})"
append_text += " <tr>"
append_text += f"<td>{matches.group('name')}</td>"
append_text += f"<td>{color_rgba}</td>"
append_text += f"<td class='checkered'><div style='background-color:rgba{css_rgba};'> </div></td>"
append_text += "</tr>\n"
append_text += " </tbody></table>"
source[0] += append_text
def source_read_handler(_app, docname, source):
"""
Event handler for source-read event.
Where we can modify the source of a document before it is parsed.
"""
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
# Transform source for arcade.color and arcade.csscolor
if docname == "api_docs/arcade.color":
generate_color_table("../arcade/color/__init__.py", source)
elif docname == "api_docs/arcade.csscolor":
generate_color_table("../arcade/csscolor/__init__.py", source)
def on_autodoc_process_bases(app, name, obj, options, bases):
"""We don't care about the `object` base class, so remove it from the list of bases."""
bases[:] = [base for base in bases if base is not object]
def setup(app):
# Separate stylesheets loosely by category.
app.add_css_file("css/colors.css")
app.add_css_file("css/layout.css")
app.add_css_file("css/custom.css")
app.add_js_file("js/custom.js")
# IMPORTANT: We can't use app.add_autodocumenter!
# See the docstring of ClassDocumenter above for why.
# sphinx.ext.autodoc.ClassDocumenter = ClassDocumenter
app.connect('source-read', source_read_handler)
app.connect("autodoc-process-docstring", inspect_docstring_for_member)
app.connect('autodoc-process-signature', strip_init_return_typehint, -1000)
app.connect('autodoc-process-bases', on_autodoc_process_bases)
# app.add_transform(Transform)
# ------------------------------------------------------
# Old hacks that breaks the api docs. !!! DO NOT USE !!!
# ------------------------------------------------------
# NOTE: Breaks annotated return types in properties and various other members
# class ClassDocumenter(sphinx.ext.autodoc.ClassDocumenter):
# """A replacement for the default autodocumenter.
# .. warning:: You must monkeypatch the baseclass with this!
# .. code-block:: python
# sphinx.ext.autodoc.ClassDocumenter = ClassDocumenter
# Why? New ClassDocumenter subclasses appear to be registered for
# specific names. For example, ``.. autointenum::`` would be declared
# as follows::
# class IntEnumDocumenter(ClassDocumenter):
# objtype = 'intenum'
# # Full class omitted, taken from the extension tutorial:
# # https://www.sphinx-doc.org/en/master/development/tutorials/autodoc_ext.html#writing-the-extension
# However, this documenter is for the default name, so passing it to
# `app.app_autodocumenter` will produce a warning about a conflict.
# Arcade's build config promotes warnings to errors, breaking build.
# """
# def add_directive_header(self, sig: str) -> None:
# r = super().add_directive_header(sig)
# # Strip empty `Bases: `, will be empty when only superclass is `object`
# # cuz we remove it earlier
# strings = self.directive.result
# if strings[-1] == ' Bases: ':
# strings.pop()
# return r
# NOTE: Breaks some properties
# class Transform(sphinx.transforms.SphinxTransform):
# default_priority = 800
# def apply(self):
# self.document.walk(Visitor(self.document))
# class Visitor(docutils.nodes.SparseNodeVisitor):
# def visit_desc_annotation(self, node):
# # Remove `property` prefix from properties so they look the same as
# # attributes
# if 'property' in node.astext():
# node.parent.remove(node)