melisa/docs/source/extensions/attributable.py

301 lines
8.5 KiB
Python
Raw Permalink Normal View History

2022-03-17 21:32:43 +03:00
"""
I am so sorry, but i found this extension somewhere in the internet.
IT LOOKS REALLY BEAUTIFUL!
"""
from sphinx.util.docutils import SphinxDirective
from sphinx.locale import _
from docutils import nodes
from sphinx import addnodes
from collections import OrderedDict, namedtuple
import importlib
import inspect
import re
class attributetable(nodes.General, nodes.Element):
pass
class attributetablecolumn(nodes.General, nodes.Element):
pass
class attributetabletitle(nodes.TextElement):
pass
class attributetableplaceholder(nodes.General, nodes.Element):
pass
class attributetablebadge(nodes.TextElement):
pass
class attributetable_item(nodes.Part, nodes.Element):
pass
def visit_attributetable_node(self, node):
class_ = node["python-class"]
2022-06-30 22:29:10 +03:00
self.body.append(f'<div class="py-attribute-table" data-move-to-id="{class_}">')
2022-03-17 21:32:43 +03:00
def visit_attributetablecolumn_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append(self.starttag(node, "div", CLASS="py-attribute-table-column"))
2022-03-17 21:32:43 +03:00
def visit_attributetabletitle_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append(self.starttag(node, "span"))
2022-03-17 21:32:43 +03:00
def visit_attributetablebadge_node(self, node):
attributes = {
2022-06-30 22:29:10 +03:00
"class": "py-attribute-table-badge",
"title": node["badge-type"],
2022-03-17 21:32:43 +03:00
}
2022-06-30 22:29:10 +03:00
self.body.append(self.starttag(node, "span", **attributes))
2022-03-17 21:32:43 +03:00
def visit_attributetable_item_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append(self.starttag(node, "li", CLASS="py-attribute-table-entry"))
2022-03-17 21:32:43 +03:00
def depart_attributetable_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append("</div>")
2022-03-17 21:32:43 +03:00
def depart_attributetablecolumn_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append("</div>")
2022-03-17 21:32:43 +03:00
def depart_attributetabletitle_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append("</span>")
2022-03-17 21:32:43 +03:00
def depart_attributetablebadge_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append("</span>")
2022-03-17 21:32:43 +03:00
def depart_attributetable_item_node(self, node):
2022-06-30 22:29:10 +03:00
self.body.append("</li>")
2022-03-17 21:32:43 +03:00
2022-06-30 22:29:10 +03:00
_name_parser_regex = re.compile(r"(?P<module>[\w.]+\.)?(?P<name>\w+)")
2022-03-17 21:32:43 +03:00
class PyAttributeTable(SphinxDirective):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {}
def parse_name(self, content):
path, name = _name_parser_regex.match(content).groups()
if path:
2022-06-30 22:29:10 +03:00
modulename = path.rstrip(".")
2022-03-17 21:32:43 +03:00
else:
2022-06-30 22:29:10 +03:00
modulename = self.env.temp_data.get("autodoc:module")
2022-03-17 21:32:43 +03:00
if not modulename:
2022-06-30 22:29:10 +03:00
modulename = self.env.ref_context.get("py:module")
2022-03-17 21:32:43 +03:00
if modulename is None:
2022-06-30 22:29:10 +03:00
raise RuntimeError(
"modulename somehow None for %s in %s." % (content, self.env.docname)
)
2022-03-17 21:32:43 +03:00
return modulename, name
def run(self):
"""If you're curious on the HTML this is meant to generate:
<div class="py-attribute-table">
<div class="py-attribute-table-column">
<span>_('Attributes')</span>
<ul>
<li>
<a href="...">
</li>
</ul>
</div>
<div class="py-attribute-table-column">
<span>_('Methods')</span>
<ul>
<li>
<a href="..."></a>
<span class="py-attribute-badge" title="decorator">D</span>
</li>
</ul>
</div>
</div>
However, since this requires the tree to be complete
and parsed, it'll need to be done at a different stage and then
replaced.
"""
content = self.arguments[0].strip()
2022-06-30 22:29:10 +03:00
node = attributetableplaceholder("")
2022-03-17 21:32:43 +03:00
modulename, name = self.parse_name(content)
2022-06-30 22:29:10 +03:00
node["python-doc"] = self.env.docname
node["python-module"] = modulename
node["python-class"] = name
node["python-full-name"] = f"{modulename}.{name}"
2022-03-17 21:32:43 +03:00
return [node]
def build_lookup_table(env):
# Given an environment, load up a lookup table of
# full-class-name: objects
result = {}
2022-06-30 22:29:10 +03:00
domain = env.domains["py"]
2022-03-17 21:32:43 +03:00
ignored = {
2022-06-30 22:29:10 +03:00
"data",
"exception",
"module",
"class",
2022-03-17 21:32:43 +03:00
}
for (fullname, _, objtype, docname, _, _) in domain.get_objects():
if objtype in ignored:
continue
2022-06-30 22:29:10 +03:00
classname, _, child = fullname.rpartition(".")
2022-03-17 21:32:43 +03:00
try:
result[classname].append(child)
except KeyError:
result[classname] = [child]
return result
2022-06-30 22:29:10 +03:00
TableElement = namedtuple("TableElement", "fullname label badge")
2022-03-17 21:32:43 +03:00
def process_attributetable(app, doctree, fromdocname):
env = app.builder.env
lookup = build_lookup_table(env)
for node in doctree.traverse(attributetableplaceholder):
2022-06-30 22:29:10 +03:00
modulename, classname, fullname = (
node["python-module"],
node["python-class"],
node["python-full-name"],
)
2022-03-17 21:32:43 +03:00
groups = get_class_results(lookup, modulename, classname, fullname)
2022-06-30 22:29:10 +03:00
table = attributetable("")
2022-03-17 21:32:43 +03:00
for label, subitems in groups.items():
if not subitems:
continue
2022-06-30 22:29:10 +03:00
table.append(
class_results_to_node(label, sorted(subitems, key=lambda c: c.label))
)
2022-03-17 21:32:43 +03:00
2022-06-30 22:29:10 +03:00
table["python-class"] = fullname
2022-03-17 21:32:43 +03:00
node.replace_self([table] if table else [])
def get_class_results(lookup, modulename, name, fullname):
module = importlib.import_module(modulename)
cls = getattr(module, name)
2022-06-30 22:29:10 +03:00
groups = OrderedDict(
[
(_("Attributes"), []),
(_("Methods"), []),
]
)
2022-03-17 21:32:43 +03:00
try:
members = lookup[fullname]
except KeyError:
return groups
for attr in members:
2022-06-30 22:29:10 +03:00
attrlookup = f"{fullname}.{attr}"
key = _("Attributes")
2022-03-17 21:32:43 +03:00
badge = None
label = attr
value = None
for base in cls.__mro__:
value = base.__dict__.get(attr)
if value is not None:
break
if value is not None:
2022-06-30 22:29:10 +03:00
doc = value.__doc__ or ""
if inspect.iscoroutinefunction(value) or doc.startswith("|coro|"):
key = _("Methods")
badge = attributetablebadge("async", "async")
badge["badge-type"] = _("coroutine")
2022-03-17 21:32:43 +03:00
elif isinstance(value, classmethod):
2022-06-30 22:29:10 +03:00
key = _("Methods")
label = f"{name}.{attr}"
badge = attributetablebadge("cls", "cls")
badge["badge-type"] = _("classmethod")
elif inspect.isfunction(value) or isinstance(value, staticmethod):
if doc.startswith(("A decorator", "A shortcut decorator")) or label in (
"event",
"loop",
2022-03-17 21:32:43 +03:00
):
# finicky but surprisingly consistent
2022-06-30 22:29:10 +03:00
badge = attributetablebadge("@", "@")
badge["badge-type"] = _("decorator")
key = _("Methods")
2022-03-17 21:32:43 +03:00
else:
2022-06-30 22:29:10 +03:00
key = _("Methods")
badge = attributetablebadge("def", "def")
badge["badge-type"] = _("method")
2022-03-17 21:32:43 +03:00
2022-06-30 22:29:10 +03:00
groups[key].append(TableElement(fullname=attrlookup, label=label, badge=badge))
2022-03-17 21:32:43 +03:00
return groups
def class_results_to_node(key, elements):
title = attributetabletitle(key, key)
2022-06-30 22:29:10 +03:00
ul = nodes.bullet_list("")
2022-03-17 21:32:43 +03:00
for element in elements:
2022-06-30 22:29:10 +03:00
ref = nodes.reference(
"",
"",
internal=True,
refuri="#" + element.fullname,
anchorname="",
*[nodes.Text(element.label)],
)
para = addnodes.compact_paragraph("", "", ref)
2022-03-17 21:32:43 +03:00
if element.badge is not None:
2022-06-30 22:29:10 +03:00
ul.append(attributetable_item("", element.badge, para))
2022-03-17 21:32:43 +03:00
else:
2022-06-30 22:29:10 +03:00
ul.append(attributetable_item("", para))
2022-03-17 21:32:43 +03:00
2022-06-30 22:29:10 +03:00
return attributetablecolumn("", title, ul)
2022-03-17 21:32:43 +03:00
def setup(app):
2022-06-30 22:29:10 +03:00
app.add_directive("attributetable", PyAttributeTable)
app.add_node(
attributetable, html=(visit_attributetable_node, depart_attributetable_node)
)
app.add_node(
attributetablecolumn,
html=(visit_attributetablecolumn_node, depart_attributetablecolumn_node),
)
app.add_node(
attributetabletitle,
html=(visit_attributetabletitle_node, depart_attributetabletitle_node),
)
app.add_node(
attributetablebadge,
html=(visit_attributetablebadge_node, depart_attributetablebadge_node),
)
app.add_node(
attributetable_item,
html=(visit_attributetable_item_node, depart_attributetable_item_node),
)
2022-03-17 21:32:43 +03:00
app.add_node(attributetableplaceholder)
2022-06-30 22:29:10 +03:00
app.connect("doctree-resolved", process_attributetable)