Skip to content

Commit 5e0f002

Browse files
committed
Switch from viewcode to linkcode.
This makes docs builds noticeably faster as they no longer need to syntax-highlight and render all source code.
1 parent 9e75d1e commit 5e0f002

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

docs/conf.py

+50-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
# https://www.sphinx-doc.org/en/master/usage/configuration.html
66

77
import datetime
8+
import importlib
9+
import inspect
810
import os
11+
import subprocess
912
import sys
1013

1114
# -- Path setup --------------------------------------------------------------
@@ -34,7 +37,7 @@
3437
extensions = [
3538
"sphinx.ext.autodoc",
3639
"sphinx.ext.intersphinx",
37-
"sphinx.ext.viewcode",
40+
"sphinx.ext.linkcode",
3841
"sphinx_autodoc_typehints",
3942
"sphinx_copybutton",
4043
"sphinx_inline_tabs",
@@ -55,6 +58,52 @@
5558
# This pattern also affects html_static_path and html_extra_path.
5659
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
5760

61+
# Configure viewcode extension.
62+
try:
63+
git_sha1 = subprocess.run(
64+
"git rev-parse --short HEAD",
65+
capture_output=True,
66+
shell=True,
67+
check=True,
68+
text=True,
69+
).stdout.strip()
70+
except subprocess.SubprocessError as exc:
71+
print("Cannot get git commit, disabling linkcode:", exc)
72+
extensions.remove("sphinx.ext.linkcode")
73+
else:
74+
code_url = f"https://github.com/aaugustin/websockets/blob/{git_sha1}"
75+
76+
77+
def linkcode_resolve(domain, info):
78+
assert domain == "py"
79+
80+
mod = importlib.import_module(info["module"])
81+
if "." in info["fullname"]:
82+
objname, attrname = info["fullname"].split(".")
83+
obj = getattr(mod, objname)
84+
try:
85+
# object is a method of a class
86+
obj = getattr(obj, attrname)
87+
except AttributeError:
88+
# object is an attribute of a class
89+
return None
90+
else:
91+
obj = getattr(mod, info["fullname"])
92+
93+
try:
94+
file = inspect.getsourcefile(obj)
95+
lines = inspect.getsourcelines(obj)
96+
except TypeError:
97+
# e.g. object is a typing.Union
98+
return None
99+
file = os.path.relpath(file, os.path.abspath(".."))
100+
if not file.startswith("src/websockets"):
101+
# e.g. object is a typing.NewType
102+
return None
103+
start, end = lines[1], lines[1] + len(lines[0]) - 1
104+
105+
return f"{code_url}/{file}#L{start}-L{end}"
106+
58107

59108
# -- Options for HTML output -------------------------------------------------
60109

0 commit comments

Comments
 (0)