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

时间:2011-05-20 06:36:04

标签: python python-sphinx

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

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

1 个答案:

答案 0 :(得分:8)

我能想到的两个选择是:

  1. 向远程项目添加svn:externals链接(您已经了解)。
  2. 使用自定义指令扩展Sphinx以包含来自远程subversion存储库的文件。
  3. 我不是Sphinx内部的专家,但能够拼凑一个快速扩展,它嵌入来自远程subversion存储库的文件。

    该扩展添加了一个svninclude指令,该指令采用1个参数,即您的文档所在的存储库的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))
    

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

    .. svninclude:: http://svn.domain.com/svn/project
    
        one.rst
        doc/two.rst
    

    路径one.rstdoc/two.rst相对于subversion网址,例如http://svn.domain.com/svn/project/one.rst

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

    1. 'svninclude'添加到extensions中的source/conf.py列表。
    2. 在项目根目录中放置svninclude.py
    3. 然后跑了:

      % PYTHONPATH=. sphinx-build -b html ./source ./build