将外部文档包含在Sphinx项目中

6 python python-sphinx

我们在SVN中使用Sphinx维护了相当大的文档.

作为生成输出的一部分,我们希望将相关Python模块的发行说明作为主要内容(而不是超链接!).外部模块的发行说明也在SVN中保留.是否有一些Sphinx-ish方法从其他(SVN)源中提取文档的各个部分?好吧,使用SVN外部是一种解决问题的方法,但也许不是最聪明的方式......任何更好的选择?

sam*_*ias 8

我能想到的两个选择是:

  1. 添加svn:externals远程项目的链接(您已经了解).
  2. 使用自定义指令扩展Sphinx以包含来自远程subversion存储库的文件.

我不是Sphinx内部的专家,但能够拼凑一个快速扩展,嵌入来自远程subversion存储库的文件.

该扩展添加了一个带有svninclude1个参数的指令,即您的文档所在的存储库的URL.它将此存储库检入到_svncache位于项目根目录中的临时目录中,然后继续读取每个文件的内容并将它们插入到解析器的状态机中.

这是svninclude.py扩展的代码.它过于简单,目前没有错误检查.如果你计划实施这个,请告诉我,如果你遇到困难,我可以提供一些额外的提示:

import os, re, subprocess, sys
from docutils import nodes, statemachine
from docutils.parsers.rst import directives
from sphinx.util.compat import Directive, directive_dwim

class SvnInclude(Directive):

    has_content = True
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = False

    def _setup_repo(self, repo):
        env = self.state.document.settings.env
        path = os.path.normpath(env.doc2path(env.docname, base=None))
        cache = os.path.join(os.path.dirname(path), '_svncache')
        root = os.path.join(cache, re.sub('[\W\-]+', '_', repo))
        if not os.path.exists(root):
            os.makedirs(root)
        subprocess.call(['svn', 'co', repo, root])
        return root

    def run(self):
        root = self._setup_repo(self.arguments[0])
        for path in self.content:
            data = open(os.path.join(root, path), 'rb').read()
            lines = statemachine.string2lines(data)
            self.state_machine.insert_input(lines, path)
        return []

def setup(app):
    app.add_directive('svninclude', directive_dwim(SvnInclude))
Run Code Online (Sandbox Code Playgroud)

以下是您在index.rst(或其他文件)中包含的标记示例:

.. svninclude:: http://svn.domain.com/svn/project

    one.rst
    doc/two.rst
Run Code Online (Sandbox Code Playgroud)

例如,路径one.rstdoc/two.rst相对于subversion url的位置http://svn.domain.com/svn/project/one.rst.

您当然希望打包svninclude.py并将其安装在Python路径中.这是我测试它的方法:

  1. 添加'svninclude'extensions列表中source/conf.py.
  2. 放在svninclude.py项目根目录中.

然后跑了:

% PYTHONPATH=. sphinx-build -b html ./source ./build
Run Code Online (Sandbox Code Playgroud)