-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathconf.py
More file actions
587 lines (474 loc) · 20.9 KB
/
conf.py
File metadata and controls
587 lines (474 loc) · 20.9 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
#!/usr/bin/env python
"""Sphinx configuration file"""
import os
from functools import cache
import logging
from pathlib import Path
from typing import Any, NamedTuple
import re
import runpy
import sys
from docutils import nodes
from sphinx.util.docutils import SphinxRole
HERE = Path(__file__).resolve()
REPO_LOCAL_ROOT = HERE.parent.parent
ARCADE_MODULE = REPO_LOCAL_ROOT / "arcade"
UTIL_DIR = REPO_LOCAL_ROOT / "util"
log = logging.getLogger("conf.py")
logging.basicConfig(level=logging.WARNING)
# logging.basicConfig(level=logging.INFO)
sys.path.insert(0, str(REPO_LOCAL_ROOT))
sys.path.insert(0, str(ARCADE_MODULE))
log.info(f"Inserted elements in system path: First two are now:")
for i in range(2):
log.info(f" {i}: {sys.path[i]!r}")
# Grab readthedocs env variables for logging + use
# https://docs.readthedocs.com/platform/stable/reference/environment-variables.html
# Their GH comments suggest they want to move away from "magic" injection as
# part of the readthedocs theme, so this seems like the best option for us.
log.info(" Env variables...")
col_width = max(map(len, os.environ.keys()))
READTHEDOCS = dict()
ENV = dict()
for k, v in os.environ.items():
if k.startswith("READTHEDOCS_"):
READTHEDOCS[k.removeprefix("READTHEDOCS_")] = v
ENV[k] = v
from util.doc_helpers.real_filesystem import copy_media
# As of pyglet==2.1.dev7, this is no longer set in pyglet/__init__.py
# because Jupyter / IPython always load Sphinx into sys.modules. See
# the following for more info:
# 1. The ticket: https://github.com/pyglet/pyglet/issues/1215
# 2. The commit: https://github.com/pyglet/pyglet/commit/97076c3a33a7d368cc9c9e44ca67769b6a16a905
sys.is_pyglet_doc_run = True
# --- Pre-processing Tasks
# Report our diagnostic info
log.info(f"Absolute path for our conf.py : {str(HERE)!r}")
log.info(f"Absolute path for the repo root : {str(REPO_LOCAL_ROOT)!r}")
log.info(f"Absolute path for the arcade module : {str(REPO_LOCAL_ROOT)!r}")
log.info(f"Absolute path for the util dir : {str(UTIL_DIR)!r}")
print()
for k, v in ENV.items():
log.info(f"Env variable {k:{col_width}} : {v!r}")
# _temp_version = (REPO_LOCAL_ROOT / "arcade" / "VERSION").read_text().replace("-",'')
# Don't change to
# from arcade.version import VERSION
# or read the docs build will fail.
from version import VERSION # pyright: ignore [reportMissingImports]
log.info(f" Got version {VERSION=!r}")
print()
GIT_REF = "development"
if READTHEDOCS:
if READTHEDOCS.get("VERSION") in ("latest", "stable"):
log.info(" !!!!! APPEARS TO BE A REAL RELEASE !!!!!")
else:
log.info(" +++++ Building a PR or development +++++")
else:
log.info(" - - - Building outside readthedocs +++++")
print()
# We'll pass this to our generation scripts to initialize their globals
REPO_URL_BASE = "https://github.com/pythonarcade/arcade"
FMT_URL_REF_BASE = f"{REPO_URL_BASE}/blob/{GIT_REF}"
RESOURCE_GLOBALS = dict(
GIT_REF=GIT_REF, # pending: post-3.0 clean-up, not sure if things use it now?
# This may be more useful according to some doc? (It's unclear)
# https://docs.readthedocs.com/platform/stable/reference/environment-variables.html#envvar-READTHEDOCS_GIT_COMMIT_HASH
BASE_URL_REPO=REPO_URL_BASE,
# This double-bracket escapes brackets in f-strings
FMT_URL_REF_PAGE=f"{FMT_URL_REF_BASE}/{{}}",
FMT_URL_REF_EMBED=f"{FMT_URL_REF_BASE}/{{}}?raw=true",
RTD_EVIL=READTHEDOCS["CANONICAL_URL"] if READTHEDOCS else "", # pending: post-3.0 cleanup
)
def run_util(filename, run_name="__main__", init_globals=None):
full_absolute_path = UTIL_DIR / filename
full_str = str(full_absolute_path)
log.info(f"Running {full_str!r} with:")
log.info(f" run_name={run_name!r}")
kwargs = dict(run_name=run_name)
if init_globals is not None:
kwargs["init_globals"] = init_globals
log.info(f" init_globals={{")
num_left = len(init_globals)
for k, v in init_globals.items():
end = "," if num_left else ""
log.info(f" {k!r} : {v!r}{end}")
num_left -= num_left
log.info(f" }}")
runpy.run_path(full_str, **kwargs)
# Make thumbnails for the example code screenshots
run_util("generate_example_thumbnails.py")
# Create a tabular representation of the resources with embeds
run_util("create_resources_listing.py", init_globals=RESOURCE_GLOBALS)
# Run the generate quick API index script
run_util("../util/update_quick_index.py")
OUT_STATIC = REPO_LOCAL_ROOT / "build/html/_static/"
src_res_dir = ARCADE_MODULE / "resources/assets"
out_res_dir = REPO_LOCAL_ROOT / "build/html/_static/assets"
# pending: post-3.0 cleanup to find the right source events to make this work?
# if exc or app.builder.format != "html":
# return
# static_dir = (app.outdir / '_static').resolve()
copy_what = { # pending: post-3.0 cleanup to tie this into resource generation correctly
"sounds": ("*.wav", "*.ogg", "*.mp3"),
"music": ("*.wav", "*.ogg", "*.mp3"),
"video": (
"*.mp4",
"*.webm",
),
}
copy_media(src_res_dir, out_res_dir, copy_what)
# We are no longer asking. We are copying.
copy_media(REPO_LOCAL_ROOT / "doc/_static/icons", OUT_STATIC / "icons", {"tabler": ("*.svg",)})
copy_media(REPO_LOCAL_ROOT / "doc/_static/", OUT_STATIC, {"filetiles": ("*.png",)})
# copy_media(
# REP / ""
# )
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 = "🧙"
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
"sphinx_togglebutton", # A way to toggle sections of text/code on or off.
"doc.extensions.prettyspecialmethods", # Forker plugin for prettifying special methods
]
# pending: post-3.0 cleanup:
# 1. Setting this breaks the CSS for both the plugin's buttons and our "custom" ones
# 2. Since our custom ones are only on the gui page for now, it's okay
# Note: tabler doesn't require attribution + it's the original theme for this icon set
# copybutton_image_svg = (REPO_LOCAL_ROOT / "doc/_static/icons/tabler/copy.svg").read_text()
# 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 = "2025, 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 = VERSION
# 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 = [
"_includes/*",
"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 = {
"logo_only": False,
"sticky_navigation": True,
"navigation_depth": 3,
"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),
# As of January 25th, pyglet's 2.1.X branch is on this URL and their
# development build on readthedocs is for their in-progress 3.0.0 alpha.
"pyglet": ("https://pyglet.readthedocs.io/en/latest/", None),
"PIL": ("https://pillow.readthedocs.io/en/stable", None),
"pymunk": ("https://www.pymunk.org/en/latest/", None),
}
# These will be joined as one block and prepended to every source file.
# Substitutions for |version| and |release| are predefined by Sphinx.
PROLOG_PARTS = [
# ".. include:: /links.rst",
".. |pyglet Player| replace:: pyglet :py:class:`~pyglet.media.player.Player`",
".. _Arcade's License File on GitHub: {FMT_URL_REF_BASE}/license.rst",
( # Allows explaining how to copy anywhere in the doc.
".. |Example Copy Button| raw:: html\n\n"
' <div class="arcade-ezcopy doc-ui-example-dummy" style="display: inline-block;">\n'
' <img src="/_static/copy-button.svg"/>\n\n'
" </div>\n\n"
),
]
with open("_includes/links.rst") as f:
PROLOG_PARTS.extend(f.readlines())
rst_prolog = "\n".join(PROLOG_PARTS)
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
name, r, g, b, a = matches.groupdict().values()
color_rgb_comma_sep = f"{r}, {g}, {b}"
# Generate the alpha for CSS color function
rgba_css = f"rgba({color_rgb_comma_sep}, {int(a) / 255!s:.4})"
append_text += " <tr>"
append_text += (
f"<td>"
f'<code class="docutils literal notranslate">'
f'<span class="pre">{name}</span>'
f"</code>"
f"</td>"
)
append_text += (
f'<td class="color-swatch"><div style="background: {rgba_css};"> </div></td>'
)
append_text += f"<td>({color_rgb_comma_sep}, {a})</td>"
append_text += "</tr>\n"
append_text += " </tbody></table>"
source[0] += append_text
@cache
def get_module_root(doc_confdir): # pending: revert #2304 or figure out a better solution
"""Temp fix since RTD doesn't use our make.py and offers no clean way to set build dir
1. https://github.com/pythonarcade/arcade/pull/2304/ tried to change the build dir in make.py
2. The readthedocs config does not use make.py
3. They don't seem to offer any support for non-default build locations
4. Instead, the options seem to be:
* Weird environment variable API that's managed from their admin console (bus factor++)
* Overwrite the entire build process https://blog.readthedocs.com/build-customization/
"""
return doc_confdir.parent / "arcade"
def source_read_handler(_app, doc_name: str, source):
"""
Event handler for source-read event.
Where we can modify the source of a document before it is parsed.
"""
def _get_dir(app, path):
path = get_module_root(_app.confdir) / path
print(f"Generated corrected module path: {path!r}")
return path
# Inject the color tables into the source
if doc_name == "api_docs/arcade.color":
generate_color_table(_get_dir(_app, "color/__init__.py"), source)
elif doc_name == "api_docs/arcade.csscolor":
generate_color_table(_get_dir(_app, "csscolor/__init__.py"), source)
elif doc_name == "api_docs/arcade.uicolor":
generate_color_table(_get_dir(_app, "uicolor.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]
class A(NamedTuple):
dirname: str
comment: str = ""
APP_CONFIG_DIRS = (
A("outdir"),
A("srcdir", "NOTE: This is reST source, not Python source!"),
A("confdir"),
A("doctreedir"),
)
class ResourceRole(SphinxRole): # pending: 3.1
"""Get resource file and category cross-references sorta working.
This needs improvement.
"""
def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]:
raw = self.text.removeprefix(":resource:")
page_id = self.text.replace(":", "").replace("/", "-").replace("_", "-").replace(".", "-")
filename = f"'{raw.split('/')[-1]}'"
node = nodes.reference(
text=filename,
refuri="".join(["/api_docs/resources.html#", page_id]),
)
log.info(" Attempted ResourceRole", locals())
return [node], []
def setup(app):
log.info("Diagnostic info since readthedocs doesn't use our make.py:")
for attr, comment in APP_CONFIG_DIRS:
val = getattr(app, attr, None)
log.info(f"{attr}: {val!r}")
if comment:
log.info(f" {comment}")
# Separate stylesheets loosely by category.
# pending: sphinx >= 8.1.4 to remove the sphinx_static_file_temp_fix.py
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)
app.add_role("resource", ResourceRole())
# Don't do anything that can fail on this event or it'll kill your build hard
# app.connect('build-finished', throws_exception)
# ------------------------------------------------------
# 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)