apidoc: Use a template for generating module file

This commit is contained in:
Takeshi KOMIYA
2019-05-02 19:31:28 +09:00
parent 035d5507f0
commit b482e38ca2
3 changed files with 52 additions and 8 deletions

View File

@@ -28,6 +28,7 @@ from sphinx.cmd.quickstart import EXTENSIONS
from sphinx.locale import __
from sphinx.util import rst
from sphinx.util.osutil import FileAvoidWrite, ensuredir
from sphinx.util.template import ReSTRenderer
if False:
# For type annotation
@@ -47,6 +48,8 @@ else:
INITPY = '__init__.py'
PY_SUFFIXES = {'.py', '.pyx'}
template_dir = path.join(package_dir, 'templates', 'apidoc')
def makename(package, module):
# type: (str, str) -> str
@@ -94,16 +97,18 @@ def format_directive(module, package=None):
return directive
def create_module_file(package, module, opts):
def create_module_file(package, basename, opts):
# type: (str, str, Any) -> None
"""Build the text of the file and write the file."""
if not opts.noheadings:
text = format_heading(1, '%s module' % module)
else:
text = ''
# text += format_heading(2, ':mod:`%s` Module' % module)
text += format_directive(module, package)
write_file(makename(package, module), text, opts)
qualname = makename(package, basename)
context = {
'show_headings': not opts.noheadings,
'basename': basename,
'qualname': qualname,
'automodule_options': OPTIONS,
}
text = ReSTRenderer(template_dir).render('module.rst', context)
write_file(qualname, text, opts)
def create_package_file(root, master_package, subroot, py_files, opts, subs, is_namespace, excludes=[]): # NOQA

View File

@@ -0,0 +1,9 @@
{%- if show_headings %}
{{- [basename, "module"] | join(' ') | e | heading }}
{% endif -%}
.. automodule:: {{ qualname }}
{%- for option in automodule_options %}
:{{ option }}:
{%- endfor %}

View File

@@ -13,6 +13,7 @@ from collections import namedtuple
import pytest
from sphinx.ext.apidoc import main as apidoc_main
from sphinx.testing.path import path
@pytest.fixture()
@@ -398,3 +399,32 @@ def test_subpackage_in_toc(make_app, apidoc):
assert 'parent.child.foo' in parent_child
assert (outdir / 'parent.child.foo.rst').isfile()
def test_module_file(tempdir):
outdir = path(tempdir)
(outdir / 'example.py').write_text('')
apidoc_main(['-o', tempdir, tempdir])
assert (outdir / 'example.rst').exists()
content = (outdir / 'example.rst').text()
assert content == ("example module\n"
"==============\n"
"\n"
".. automodule:: example\n"
" :members:\n"
" :undoc-members:\n"
" :show-inheritance:\n")
def test_module_file_noheadings(tempdir):
outdir = path(tempdir)
(outdir / 'example.py').write_text('')
apidoc_main(['--no-headings', '-o', tempdir, tempdir])
assert (outdir / 'example.rst').exists()
content = (outdir / 'example.rst').text()
assert content == (".. automodule:: example\n"
" :members:\n"
" :undoc-members:\n"
" :show-inheritance:\n")