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
|
#!/usr/bin/env python3
#
# sourcelink.py
r"""
Show a link to the corresponding source code at the top of :rst:dir:`automodule` output.
.. versionadded:: 0.6.0
.. extensions:: sphinx_toolbox.more_autodoc.sourcelink
Configuration
----------------
.. raw:: latex
\begin{flushleft}
:mod:`sphinx_toolbox.more_autodoc.sourcelink` can be configured using the :confval:`autodoc_default_options`
option in ``conf.py``, or with the :rst:dir:`:sourcelink: <sourcelink>` option flag to :rst:dir:`automodule`.
.. raw:: latex
\end{flushleft}
.. confval:: autodoc_show_sourcelink
:type: :class:`bool`
:default: :py:obj:`False`
If :py:obj:`True`, shows a link to the corresponding source code
at the top of each :rst:dir:`automodule` directive.
.. rst:directive:option:: sourcelink
When passed as an option flag to an :rst:dir:`automodule` directive,
show a link to the corresponding source code at the top of the output *for that module only*.
.. latex:vspace:: 5px
.. versionchanged:: 1.1.0
Added support for the :rst:dir:`:sourcelink: <sourcelink>` option flag to :rst:dir:`automodule`.
.. latex:clearpage::
API Reference
--------------
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# stdlib
from types import ModuleType
from typing import Any, List, Mapping
# 3rd party
import autodocsumm # type: ignore[import-untyped]
import sphinx.ext.autodoc
from sphinx.application import Sphinx
# this package
from sphinx_toolbox.more_autosummary import PatchedAutoSummModuleDocumenter
from sphinx_toolbox.utils import SphinxExtMetadata, flag, metadata_add_version
__all__ = ("sourcelinks_process_docstring", "setup")
def sourcelinks_process_docstring( # noqa: MAN001
app: Sphinx,
what,
name: str,
obj,
options: Mapping[str, Any],
lines: List[str],
) -> None:
"""
Process the docstring of a module and add a link to the source code if given in the configuration.
:param app: The Sphinx application.
:param what:
:param name: The name of the object being documented.
:param obj: The object being documented.
:param options: Mapping of autodoc options to values.
:param lines: List of strings representing the current contents of the docstring.
"""
show_sourcelink = options.get("sourcelink", app.config.autodoc_show_sourcelink)
if isinstance(obj, ModuleType) and what == "module" and show_sourcelink:
if not obj.__file__:
return
elif obj.__file__.endswith("/__init__.py"):
source_target = f"{name.replace('.', '/')}/__init__.py"
elif obj.__file__.endswith("\\__init__.py"):
source_target = f"{name.replace('.', '/')}/__init__.py"
elif obj.__file__.endswith(".py"):
source_target = f"{name.replace('.', '/')}.py"
else:
return
lines_to_insert = (
".. rst-class:: source-link",
'',
f" **Source code:** :source:`{source_target}`",
'',
"--------------------",
'',
)
for line in reversed(lines_to_insert): # pylint: disable=W8402
lines.insert(0, line)
@metadata_add_version
def setup(app: Sphinx) -> SphinxExtMetadata:
"""
Setup :mod:`sphinx_toolbox.more_autodoc.sourcelink`.
:param app: The Sphinx application.
"""
sphinx.ext.autodoc.ModuleDocumenter.option_spec["sourcelink"] = flag
autodocsumm.AutoSummModuleDocumenter.option_spec["sourcelink"] = flag
PatchedAutoSummModuleDocumenter.option_spec["sourcelink"] = flag
app.setup_extension("sphinx_toolbox.source")
app.setup_extension("sphinx_toolbox._css")
app.setup_extension("sphinx.ext.autodoc")
app.connect("autodoc-process-docstring", sourcelinks_process_docstring)
app.add_config_value("autodoc_show_sourcelink", False, "env", [bool])
return {"parallel_read_safe": True}
|