Refactor metadata handling

This commit is contained in:
Takeshi KOMIYA
2018-11-30 17:56:17 +09:00
parent 3528a68d2a
commit 8608102da6
5 changed files with 21 additions and 24 deletions

View File

@@ -9,6 +9,8 @@
:license: BSD, see LICENSE for details.
"""
from typing import List, cast
from docutils import nodes
from sphinx.environment.collectors import EnvironmentCollector
@@ -52,12 +54,18 @@ class MetadataCollector(EnvironmentCollector):
for node in docinfo:
# nodes are multiply inherited...
if isinstance(node, nodes.authors):
md['authors'] = [author.astext() for author in node]
elif isinstance(node, nodes.TextElement): # e.g. author
md[node.__class__.__name__] = node.astext()
authors = cast(List[nodes.author], node)
md['authors'] = [author.astext() for author in authors]
elif isinstance(node, nodes.field):
assert len(node) == 2
field_name = cast(nodes.field_name, node[0])
field_body = cast(nodes.field_body, node[1])
md[field_name.astext()] = field_body.astext()
else:
name, body = node
md[name.astext()] = body.astext()
# 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:

View File

@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
master_doc = 'index'

View File

@@ -42,16 +42,5 @@
markup language, containing examples of all basic
constructs and many advanced constructs.
================================
reStructuredText Demonstration
================================
.. Above is the document title, and below is the subtitle.
They are transformed from section titles after parsing.
--------------------------------
Examples of Syntax Constructs
--------------------------------
.. bibliographic fields (which also require a transform):
test-metadata
==============

View File

@@ -23,7 +23,6 @@ Contents:
bom
math
autodoc
metadata
extensions
extensions
footnote

View File

@@ -15,7 +15,7 @@
import pytest
@pytest.mark.sphinx('pseudoxml')
@pytest.mark.sphinx('dummy', testroot='metadata')
def test_docinfo(app, status, warning):
"""
Inspect the 'docinfo' metadata stored in the first node of the document.
@@ -24,9 +24,7 @@ def test_docinfo(app, status, warning):
'dedication' blocks, or the 'meta' role. Doing otherwise is probably more
messing with the internals of sphinx than this rare use case merits.
"""
app.builder.build(['metadata'])
env = app.env
exampledocinfo = env.metadata['metadata']
app.build()
expecteddocinfo = {
'author': u'David Goodger',
'authors': [u'Me', u'Myself', u'I'],
@@ -51,4 +49,4 @@ def test_docinfo(app, status, warning):
'orphan': u'',
'nocomments': u'',
}
assert exampledocinfo == expecteddocinfo
assert app.env.metadata['index'] == expecteddocinfo