在扩展中声明对sphinx-build的附加依赖

时间:2019-02-04 17:03:30

标签: python-sphinx build-dependencies

TL,DR:如何从Sphinx扩展名告诉sphinx-build将附加文件视为依赖项?在我的直接用例中,这是扩展程序的源代码,但问题可能同样适用于扩展程序使用的某些辅助文件。

我正在使用自定义扩展程序使用Sphinx生成文档。我正在使用sphinx-build来构建文档。例如,我使用此命令生成HTML(这是sphinx-quickstart生成的makefile中的命令):

sphinx-build -b html -d _build/doctrees   . _build/html

由于我的自定义扩展名与文档的来源一起维护,因此我希望sphinx-build将其视为生成的HTML(和LaTeX等)的依赖项。因此,无论何时更改扩展程序的源代码,我都希望sphinx-build重新生成输出。

我如何告诉sphinx-build将其他文件视为依赖项?在toctree中没有提及,因为它不是源文件的一部分。从逻辑上讲,这应该是我通过扩展程序的setup函数执行的操作。


示例扩展名(my_extension.py):

from docutils import nodes
from docutils.parsers.rst import Directive

class Foo(Directive):
    def run(self):
        node = nodes.paragraph(text='Hello world\n')
        return [node]

def setup(app):
    app.add_directive('foo', Foo)

样本来源(index.rst):

.. toctree::
   :maxdepth: 2

.. foo::

示例conf.py(基本上是sphinx-quickstart的输出加上我的扩展名):

import sys
import os
sys.path.insert(0, os.path.abspath('.'))
extensions = ['my_extension']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Hello directive'
copyright = '2019, Gilles'
author = 'Gilles'
version = '1'
release = '1'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme = 'alabaster'
html_static_path = ['_static']
htmlhelp_basename = 'Hellodirectivedoc'
latex_elements = {
}
latex_documents = [
    (master_doc, 'Hellodirective.tex', 'Hello directive Documentation',
     'Gilles', 'manual'),
]
man_pages = [
    (master_doc, 'hellodirective', 'Hello directive Documentation',
     [author], 1)
]
texinfo_documents = [
    (master_doc, 'Hellodirective', 'Hello directive Documentation',
     author, 'Hellodirective', 'One line description of project.',
     'Miscellaneous'),
]

解决方案的验证:

  1. 运行make html(或如上所述的sphinx-build)。
  2. 修改my_extension.py,将Hello world替换为Hello again
  3. 再次运行make html
  4. 生成的HTML(_build/html/index.html)现在必须包含Hello again而不是Hello world

1 个答案:

答案 0 :(得分:0)

note_dependency method in the build environment API似乎可以满足我的要求。但是我应该什么时候打电话呢?我尝试了各种events,但似乎没有一个在正确的状态下碰到环境对象。起作用的是从指令中调用它。

import os
from docutils import nodes
from docutils.parsers.rst import Directive
import sphinx.application

class Foo(Directive):
    def run(self):
        self.state.document.settings.env.note_dependency(__file__)
        node = nodes.paragraph(text='Hello done\n')
        return [node]

def setup(app):
    app.add_directive('foo', Foo)

如果文档包含至少一个foo伪指令,则引入此伪指令的扩展名更改时,它将被标记为陈旧。这很有道理,尽管如果扩展添加了许多指令或进行了不同的更改可能会很乏味。我不知道是否有更好的方法。

Luc Van Oostenryck's autodoc-C的启发。

相关问题