|
5 | 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html
|
6 | 6 |
|
7 | 7 | import datetime
|
| 8 | +import importlib |
| 9 | +import inspect |
8 | 10 | import os
|
| 11 | +import subprocess |
9 | 12 | import sys
|
10 | 13 |
|
11 | 14 | # -- Path setup --------------------------------------------------------------
|
|
34 | 37 | extensions = [
|
35 | 38 | "sphinx.ext.autodoc",
|
36 | 39 | "sphinx.ext.intersphinx",
|
37 |
| - "sphinx.ext.viewcode", |
| 40 | + "sphinx.ext.linkcode", |
38 | 41 | "sphinx_autodoc_typehints",
|
39 | 42 | "sphinx_copybutton",
|
40 | 43 | "sphinx_inline_tabs",
|
|
55 | 58 | # This pattern also affects html_static_path and html_extra_path.
|
56 | 59 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
|
57 | 60 |
|
| 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 | + |
58 | 107 |
|
59 | 108 | # -- Options for HTML output -------------------------------------------------
|
60 | 109 |
|
|
0 commit comments