Refactor metadata collector

This commit is contained in:
Takeshi KOMIYA 2018-12-02 01:49:14 +09:00
parent e527be396a
commit c1d0960d66

View File

@ -37,44 +37,37 @@ class MetadataCollector(EnvironmentCollector):
env.metadata[docname] = other.metadata[docname] env.metadata[docname] = other.metadata[docname]
def process_doc(self, app, doctree): def process_doc(self, app, doctree):
# type: (Sphinx, nodes.Node) -> None # type: (Sphinx, nodes.document) -> None
"""Process the docinfo part of the doctree as metadata. """Process the docinfo part of the doctree as metadata.
Keep processing minimal -- just return what docutils says. Keep processing minimal -- just return what docutils says.
""" """
md = app.env.metadata[app.env.docname] if len(doctree) > 0 and isinstance(doctree[0], nodes.docinfo):
try: md = app.env.metadata[app.env.docname]
docinfo = doctree[0] for node in doctree[0]:
except IndexError: # nodes are multiply inherited...
# probably an empty document if isinstance(node, nodes.authors):
return authors = cast(List[nodes.author], node)
if docinfo.__class__ is not nodes.docinfo: md['authors'] = [author.astext() for author in authors]
# nothing to see here elif isinstance(node, nodes.field):
return assert len(node) == 2
for node in docinfo: field_name = cast(nodes.field_name, node[0])
# nodes are multiply inherited... field_body = cast(nodes.field_body, node[1])
if isinstance(node, nodes.authors): md[field_name.astext()] = field_body.astext()
authors = cast(List[nodes.author], node) elif isinstance(node, nodes.TextElement):
md['authors'] = [author.astext() for author in authors] # other children must be TextElement
elif isinstance(node, nodes.field): # see: http://docutils.sourceforge.net/docs/ref/doctree.html#bibliographic-elements # NOQA
assert len(node) == 2 md[node.__class__.__name__] = node.astext()
field_name = cast(nodes.field_name, node[0])
field_body = cast(nodes.field_body, node[1])
md[field_name.astext()] = field_body.astext()
else:
# other children must be TextElement
# see: http://docutils.sourceforge.net/docs/ref/doctree.html#bibliographic-elements # NOQA
element = cast(nodes.TextElement, node)
md[element.__class__.__name__] = element.astext()
for name, value in md.items():
if name in ('tocdepth',):
try:
value = int(value)
except ValueError:
value = 0
md[name] = value
del doctree[0] for name, value in md.items():
if name in ('tocdepth',):
try:
value = int(value)
except ValueError:
value = 0
md[name] = value
doctree.pop(0)
def setup(app): def setup(app):