File: confval.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 (253 lines) | stat: -rw-r--r-- 6,019 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
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
#!/usr/bin/env python3
#
#  confval.py
r"""
The confval directive and role for configuration values.

.. extensions:: sphinx_toolbox.confval

Usage
-------

.. rst:directive:: .. confval:: name

	Used to document a configuration value.

	.. raw:: latex

		\begin{multicols}{2}

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

		Indicates the configuration value's type.

	.. rst:directive:option:: required
		:type: flag

		Indicates the whether the configuration value is required.

	.. rst:directive:option:: default
		:type: string

		Indicates the default value.

	.. rst:directive:option:: noindex
		:type: flag

		Disables the index entry and cross-referencing for this configuration value.

		.. versionadded:: 2.11.0

	.. raw:: latex

		\end{multicols}


.. latex:vspace:: -0px


.. rst:role:: confval

	Role which provides a cross-reference to a :rst:dir:`confval` directive.

.. latex:vspace:: 10px

**Examples:**

.. rest-example::

	.. confval:: demo
		:type: string
		:default: ``"Hello World"``
		:required: False

.. latex:vspace:: -20px

.. rest-example::

	To enable this feature set the :confval:`demo` configuration value to "True".


.. latex:clearpage::


API Reference
--------------

"""
#
#  Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
#  Based on https://github.com/readthedocs/sphinx_rtd_theme/blob/master/docs/conf.py
#  Copyright (c) 2013-2018 Dave Snider, Read the Docs, Inc. & contributors
#
#  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 typing import List

# 3rd party
from docutils.nodes import Node
from docutils.parsers.rst import directives
from docutils.statemachine import StringList
from domdf_python_tools.utils import strtobool
from sphinx.application import Sphinx
from sphinx.domains import ObjType
from sphinx.domains.std import GenericObject, StandardDomain
from sphinx.errors import ExtensionError
from sphinx.roles import XRefRole

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

__all__ = ("ConfigurationValue", "register_confval", "setup")


class ConfigurationValue(GenericObject):
	"""
	The confval directive.

	.. versionchanged:: 1.1.0

		The formatting of the type, required and default options can be customised
		using the ``self.format_*`` methods.

	.. versionchanged:: 2.11.0

		Added the ``:noindex:`` option, which disables the index entry
		and cross-referencing for this configuration value.
	"""

	indextemplate: str = "%s (configuration value)"

	option_spec: OptionSpec = {  # type: ignore[assignment]
		"type": directives.unchanged_required,
		"required": directives.unchanged_required,
		"default": directives.unchanged_required,
		"noindex": flag,
		}

	def run(self) -> List[Node]:
		"""
		Process the content of the directive.
		"""

		content: List[str] = []

		if self.options and set(self.options.keys()) != {"noindex"}:
			content.extend(('', ".. raw:: latex", '', r"    \vspace{-45px}", ''))

		if "type" in self.options:
			content.append(f"| **Type:** {self.format_type(self.options['type'])}")
		if "required" in self.options:
			content.append(f"| **Required:** ``{self.format_required(self.options['required'])}``")
		if "default" in self.options:
			content.append(f"| **Default:** {self.format_default(self.options['default'])}")

		if self.content:

			content.extend((
					'',
					".. raw:: latex",
					'',
					r"    \vspace{-25px}",
					'',
					))
			content.extend(self.content)

		self.content = StringList(content)

		return super().run()

	@staticmethod
	def format_type(the_type: str) -> str:
		"""
		Formats the ``:type:`` option.

		.. versionadded:: 1.1.0

		:param the_type:
		"""

		return the_type

	@staticmethod
	def format_required(required: str) -> bool:
		"""
		Formats the ``:required:`` option.

		.. versionadded:: 1.1.0

		:param required:
		"""

		return strtobool(required)

	@staticmethod
	def format_default(default: str) -> str:
		"""
		Formats the ``:default:`` option.

		.. versionadded:: 1.1.0

		:param default:
		"""

		return default


def register_confval(app: Sphinx, override: bool = False) -> None:
	"""
	Create and register the ``confval`` role and directive.

	:param app: The Sphinx application.
	:param override:
	"""

	if "std" not in app.registry.domains:
		app.add_domain(StandardDomain)  # pragma: no cover

	name = "confval"

	app.registry.add_directive_to_domain("std", name, ConfigurationValue)
	app.registry.add_role_to_domain("std", name, XRefRole())

	object_types = app.registry.domain_object_types.setdefault("std", {})

	if name in object_types and not override:  # pragma: no cover
		raise ExtensionError(f"The {name!r} object_type is already registered")

	object_types[name] = ObjType(name, name)


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

	.. versionadded:: 0.7.0

	:param app: The Sphinx application.
	"""

	register_confval(app)

	return {"parallel_read_safe": True}