File: sidebar_links.py

package info (click to toggle)
sphinx-toolbox 3.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,924 kB
  • sloc: python: 11,636; sh: 26; javascript: 25; makefile: 16
file content (197 lines) | stat: -rw-r--r-- 5,535 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3
#
#  sidebar_links.py
r"""
Directive which adds a toctree to the sidebar containing links to the GitHub repository, PyPI project page etc.

.. versionadded:: 2.9.0

.. extensions:: sphinx_toolbox.sidebar_links


.. latex:vspace:: -5px

Usage
-------

.. latex:vspace:: -10px

.. rst:directive:: sidebar-links

	Adds a toctree to the sidebar containing links to the GitHub repository, PyPI project page etc.
	The toctree is only shown in the sidebar and is hidden with non-HTML builders.

	.. only:: html

		You can see an example of this in the sidebar of this documentation.

	.. note:: This directive can only be used on the root document (i.e. index.rst).

	.. rst:directive:option:: github
		:type: flag

		Flag to add a link to the project's GitHub repository.

		To use this option add the following to your ``conf.py``:

		.. code-block:: python

			extensions = [
					...
					'sphinx_toolbox.github',
					]

			github_username = '<your username>'
			github_repository = '<your repository>'


		See :mod:`sphinx_toolbox.github` for more information.

	.. rst:directive:option:: pypi
		:type: string

		Flag to add a link to the project page on PyPI.

		The name of the project on PyPI must be passed as the option's value.

	.. rst:directive:option:: caption
		:type: string

		The caption of the toctree. Defaults to ``Links``

	Additional toctree entries may be added as the content of the directive, in the same manner as normal toctrees.


API Reference
--------------
"""
#
#  Copyright © 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
import warnings
from typing import List

# 3rd party
import docutils
from docutils import nodes
from docutils.parsers.rst import directives
from domdf_python_tools.stringlist import StringList
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.util.docutils import SphinxDirective

# this package
from sphinx_toolbox.utils import OptionSpec, SphinxExtMetadata, flag, metadata_add_version

__all__ = ("SidebarLinksDirective", "setup")


class SidebarLinksDirective(SphinxDirective):
	"""
	Directive which adds a toctree to the sidebar containing links to the GitHub repository, PyPI project page etc.
	"""

	has_content: bool = True

	option_spec: OptionSpec = {  # type: ignore[assignment]
		"pypi": directives.unchanged_required,
		"github": flag,
		"caption": directives.unchanged_required,
		}

	def process_github_option(self) -> str:
		"""
		Process the ``:github:`` flag.
		"""

		if "sphinx_toolbox.github" not in self.env.app.extensions:
			raise ValueError(
					"The 'sphinx_toolbox.github' extension is required for the "
					":github: option but it is not enabled!"
					)

		username = getattr(self.env.config, "github_username", None)
		if username is None:
			raise ValueError("'github_username' has not been set in 'conf.py'!")

		repository = getattr(self.env.config, "github_repository", None)
		if repository is None:
			raise ValueError("'github_repository' has not been set in 'conf.py'!")

		return f"GitHub <https://github.com/{username}/{repository}>"

	def run(self) -> List[nodes.Node]:
		"""
		Create the installation node.
		"""

		if self.env.docname != self.env.config.master_doc:  # pragma: no cover
			warnings.warn(
					"The 'sidebar-links' directive can only be used on the Sphinx master doc. "
					"No links will be shown.",
					UserWarning,
					)
			return []

		body = StringList([
				".. toctree::",
				"    :hidden:",
				])

		with body.with_indent("    ", 1):
			if "caption" in self.options:
				body.append(f":caption: {self.options['caption']}")
			else:  # pragma: no cover
				body.append(":caption: Links")

			body.blankline()

			if "github" in self.options:
				body.append(self.process_github_option())
			if "pypi" in self.options:
				body.append(f"PyPI <https://pypi.org/project/{self.options['pypi']}>")

			body.extend(self.content)

		body.blankline()
		body.blankline()

		only_node = addnodes.only(expr="html")
		content_node = nodes.paragraph(rawsource=str(body))
		only_node += content_node
		self.state.nested_parse(docutils.statemachine.StringList(body), self.content_offset, content_node)

		return [only_node]


@metadata_add_version
def setup(app: Sphinx) -> SphinxExtMetadata:
	"""
	Setup :mod:`sphinx_toolbox.sidebar_links`.

	:param app: The Sphinx application.
	"""

	app.add_directive("sidebar-links", SidebarLinksDirective)

	return {"parallel_read_safe": True}