File: flake8.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 (148 lines) | stat: -rw-r--r-- 4,100 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
#!/usr/bin/env python3
#
#  flake8.py
r"""
A Sphinx directive for documenting flake8 codes.

.. versionadded:: 1.6.0
.. extensions:: sphinx_toolbox.flake8


Usage
------

.. rst:directive:: .. flake8-codes:: plugin

	Adds a table documenting a flake8 plugin's codes.

	The directive takes a single argument -- the fully qualified name of the flake8 plugin module.

	Codes to document are given in the body of the directive.


	:bold-title:`Example`

	.. rest-example::

		.. flake8-codes:: flake8_dunder_all

			DALL000


.. 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
import warnings
from typing import List, Sequence, Tuple

# 3rd party
import docutils
import tabulate
from docutils import nodes
from docutils.statemachine import StringList
from sphinx.application import Sphinx
from sphinx.ext.autodoc.importer import import_module
from sphinx.util.docutils import SphinxDirective

# this package
from sphinx_toolbox.utils import Purger, SphinxExtMetadata, metadata_add_version

__all__ = ("Flake8CodesDirective", "setup")

table_node_purger = Purger("all_flake8_code_table_nodes")


class Flake8CodesDirective(SphinxDirective):
	"""
	A Sphinx directive for documenting flake8 codes.
	"""

	has_content: bool = True

	# the fully qualified name of the flake8 plugin module
	required_arguments: int = 1

	def run(self) -> Sequence[nodes.Node]:  # type: ignore[override]
		"""
		Process the content of the directive.
		"""

		plugin: str = self.arguments[0]

		if not self.content:
			warnings.warn("No codes specified")
			return []

		module = import_module(plugin)
		codes: List[Tuple[str, str]] = []

		for code in self.content:
			if code.strip():
				if hasattr(module, code):
					description = getattr(module, code)
					if description.startswith(code):
						description = description[len(code):]
					codes.append((code, description.strip()))
				else:
					warnings.warn(f"No such code {code!r}")

		if not codes:
			warnings.warn("No codes specified")
			return []

		targetid = f'flake8codes-{self.env.new_serialno("flake8codes"):d}'
		targetnode = nodes.section(ids=[targetid])

		table = tabulate.tabulate(codes, headers=["Code", "Description"], tablefmt="rst")
		content = '\n' + table.replace('\t', "    ") + '\n'

		view = StringList(content.split('\n'))
		table_node = nodes.paragraph(rawsource=content)
		self.state.nested_parse(view, self.content_offset, table_node)

		if docutils.__version_info__ >= (0, 18):
			table_node.children[0]["classes"] += ["colwidths-given"]  # type: ignore[index]

		table_node_purger.add_node(self.env, table_node, targetnode, self.lineno)

		return [table_node]


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

	:param app: The Sphinx application.
	"""

	app.add_directive("flake8-codes", Flake8CodesDirective)
	app.connect("env-purge-doc", table_node_purger.purge_nodes)

	return {"parallel_read_safe": True}