예제 #1
0
def make_doc_directory(config, path):
    sphinx_conf = {
            'path'           : path,   # root path
            'sep'            : False,
            'dot'            : '_',
            'project'        : config['project_name'],
            'author'         : config['author'],
            'version'        : config['version'],
            'release'        : config['version'],
            'suffix'         : '.rst',
            'master'         : 'index',
            'epub'           : True,
            'ext_autodoc'    : True,
            'ext_doctest'    : False,
            'ext_interspinx' : True,
            'ext_todo'       : True,
            'ext_coverage'   : False,
            'ext_pngmath'    : True,
            'ext_mathjax'    : False,
            'ext_ifconfig'   : True,
            'ext_viewcode'   : True,
            'makefile'       : True,
            'batchfile'      : True}
    quickstart.generate(sphinx_conf)
    write_cmdline(config, os.path.join(path, 'cmdline.rst'))
    modify_doc_makefile(config, os.path.join(path, 'Makefile'))
    modify_doc_index(config, os.path.join(path, 'index.rst'))
예제 #2
0
def make_doc_directory(config, path):
    sphinx_conf = {
            'path'           : path,   # root path
            'sep'            : False,
            'dot'            : '_',
            'project'        : config['project_name'],
            'author'         : config['author'],
            'version'        : '@@VERSION@@',
            'release'        : '@@VERSION@@',
            'suffix'         : '.rst',
            'master'         : 'index',
            'epub'           : True,
            'ext_autodoc'    : True,
            'ext_doctest'    : False,
            'ext_interspinx' : True,
            'ext_todo'       : True,
            'ext_coverage'   : False,
            'ext_pngmath'    : True,
            'ext_mathjax'    : False,
            'ext_ifconfig'   : True,
            'ext_viewcode'   : True,
            'makefile'       : True,
            'batchfile'      : True}
    quickstart.generate(sphinx_conf)
    src_path = os.path.join(path, 'conf.py')
    with open(src_path, 'r') as src:
        with open(os.path.join(path, 'conf.py.skel'), 'w') as dst:
            for line in src.readlines():
                if RE_HTML_THEME.match(line):
                    line = 'html_theme = "openlmitheme"\n'
                dst.write(line)
    os.unlink(src_path)
    write_cmdline(config, os.path.join(path, 'cmdline.rst'))
    modify_doc_makefile(config, os.path.join(path, 'Makefile'))
    modify_doc_index(config, os.path.join(path, 'index.rst'))
예제 #3
0
def createNewProject(path, project_name, author):
    d = {
        'path': path,
        'sep': True,
        'dot': '_',
        'project': project_name,
        'author': author,
        'version': '1.0',
        'release': '1.0',
        'suffix': '.rst',
        'master': 'index',
        'epub': False,
        'ext_autodoc': False,
        'ext_doctest': False,
        'ext_intersphinx': False,
        'ext_todo': False,
        'ext_coverage': False,
        'ext_pngmath': False,
        'ext_mathiax': False,
        'ext_ifconfig': True,
        'ext_todo': True,
        'ext_viewcode': False,
        'makefile': True,
        'batchfile': False,
    }
    generate(d)
예제 #4
0
def createNewProject(path, project_name, author):
    d= {
        'path': path,
        'sep': True,
        'dot': '_',
        'project': project_name,
        'author': author,
        'version': '1.0',
        'release': '1.0',
        'suffix': '.rst',
        'master': 'index',
        'epub': False,
        'ext_autodoc': False,
        'ext_doctest': False,
        'ext_intersphinx': False,
        'ext_todo': False,
        'ext_coverage': False,
        'ext_pngmath': False,
        'ext_mathiax': False,
        'ext_ifconfig': True,
        'ext_todo': True,
        'ext_viewcode': False,
        'makefile': True,
        'batchfile': False,
    }
    generate(d)
예제 #5
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['todo_include_todos'] is False
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
예제 #6
0
    def sphinx(self):
        """
        Initialize Sphinx documentation for this project.


        Return: None
        Exceptions: None
        """
        try:
            from sphinx import quickstart
        except ImportError:
            print "Can't import Sphinx. Skipping"
            return

        sphinxopts = dict(dotfile.items("sphinx"))
        for f in sphinxopts:
            if sphinxopts[f] in ["False"]:
                sphinxopts[f] = False
            if sphinxopts[f] in ["True"]:
                sphinxopts[f] = True

        sphinxopts["path"] = self.root + "doc"
        sphinxopts["project"] = args.name
        if variable("author", None, ask="Project Author"):
            sphinxopts["author"] = variable("author", None)
        sphinxopts["version"] = self.version
        sphinxopts["release"] = self.version

        quickstart.ask_user(sphinxopts)
        quickstart.generate(sphinxopts)
        return
예제 #7
0
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'n',
        'coverage': 'no',
        'pngmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_raw_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == ['sphinx.ext.autodoc', 'sphinx.ext.doctest']
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
           time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')]
    assert ns['epub_author'] == u'Wolfgang Schäuble & G\'Beckstein'
    assert ns['man_pages'] == [
        ('contents', 'stasi', u'STASI™ Documentation',
         [u'Wolfgang Schäuble & G\'Beckstein'], 1)]
    assert ns['texinfo_documents'] == [
        ('contents', 'STASI', u'STASI™ Documentation',
         u'Wolfgang Schäuble & G\'Beckstein', 'STASI',
         'One line description of project.', 'Miscellaneous'),]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
예제 #8
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['todo_include_todos'] is False
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
예제 #9
0
def main(argv=sys.argv):
    """Parse and check the command line arguments."""
    parser = setup_parser()

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >> sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot='_',
            project=opts.header,
            author=opts.author or 'Author',
            version=opts.version or '',
            release=opts.release or opts.version or '',
            suffix='.' + opts.suffix,
            master='index',
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #10
0
def main(argv=sys.argv):
    """Parse and check the command line arguments."""
    parser = setup_parser()

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #11
0
def bootstrap(path, name, version, release=None):

    d = dict((
        # root path
        ("path", path),
        # separate source and build dirs (bool)
        ("sep", False),
        # name prefix for templates and static dir
        ("dot", ""),
        # project name
        ("project", name),
        # Author name(s)
        ("author", u"Lionel Dricot & Izidor Matušov"),
        # Project version, e.g. 2.5
        ("version", version or ""),
        # Project release, e.g. 2.5.1
        ("release", release or version or ""),
        # Source file suffix
        ("suffix", ".rst"),
        # master document name (without suffix)
        ("master", "index"),
        # Maximum depth of submodules to show in the TOC (int)
        ("mastertocmaxdepth", 4),
        # add configuration for epub builder
        ("epub", False),
        # automatically insert docstrings from modules (bool)
        ("ext_autodoc", True),
        # automatically test code in doctest blocks (bool)
        ("ext_doctest", False),
        # link Sphinx docs of different projects (bool)
        ("ext_intersphinx", False),
        # write "todo" entries (bool)
        ("ext_todo", True),
        # checks for documentation coverage (bool)
        ("ext_coverage", False),
        # include math, rendered as PNG images (bool)
        ("ext_pngmath", False),
        # include math, rendered in the browser by MathJax (bool)
        ("ext_mathjax", True),
        # conditional inclusion of content based on config values (bool)
        ("ext_ifconfig", False),
        # include links to the source code of documented Python objects (bool)
        ("ext_viewcode", True),
        # create Makefile (bool)
        ("makefile", False),
        # create Windows command file (bool)
        ("batchfile", False),
    ))

    if not isdir(path):
        os.makedirs(path)

    modules = recurse_tree(name, d)
    d["mastertoctree"] = create_modules_list(modules)
    create_modules_toc_file(modules, d)

    generate(d, silent=True, overwrite=True)
예제 #12
0
def make_doc_directory(config, path):
    sphinx_conf = {
        'path': path,  # root path
        'sep': False,
        'dot': '_',
        'project': config['project_name'],
        'author': config['author'],
        'version': '@@VERSION@@',
        'release': '@@VERSION@@',
        'suffix': '.rst',
        'master': 'index',
        'epub': True,
        'ext_autodoc': True,
        'ext_doctest': False,
        'ext_interspinx': True,
        'ext_todo': True,
        'ext_coverage': False,
        'ext_pngmath': True,
        'ext_mathjax': False,
        'ext_ifconfig': True,
        'ext_viewcode': True,
        'makefile': True,
        'batchfile': True
    }
    quickstart.generate(sphinx_conf)
    src_path = os.path.join(path, 'conf.py')
    with open(src_path, 'r') as src:
        with open(os.path.join(path, 'conf.py.skel'), 'w') as dst:
            for line in src.readlines():
                if RE_HTML_THEME.match(line):
                    line = 'html_theme = "openlmitheme"\n'
                dst.write(line)
    os.unlink(src_path)
    write_cmdline(config, os.path.join(path, 'cmdline.rst'))
    modify_doc_makefile(config, os.path.join(path, 'Makefile'))
    modify_doc_index(config, os.path.join(path, 'index.rst'))
    with open(os.path.join(path, 'python.rst'), 'w') as dst:
        name = str(config['command']).capitalize()
        match = RE_PROJECT_NAME.match(config['project_name'])
        if match:
            name = match.group(1)
        title = "%s Script python reference" % name
        heading = "%s\n%s" % (title, '=' * len(title))
        dst.write(
            DOC_PYTHON_REFERENCE.format(name=config['command'],
                                        heading=heading))
예제 #13
0
def test_generated_files_eol(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    def assert_eol(filename, eol):
        content = filename.bytes().decode('unicode-escape')
        assert all([l[-len(eol):] == eol for l in content.splitlines(True)])

    assert_eol(tempdir / 'make.bat', '\r\n')
    assert_eol(tempdir / 'Makefile', '\n')
예제 #14
0
def test_generated_files_eol(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    def assert_eol(filename, eol):
        content = filename.bytes().decode('unicode-escape')
        assert all([l[-len(eol):] == eol for l in content.splitlines(True)])

    assert_eol(tempdir / 'make.bat', '\r\n')
    assert_eol(tempdir / 'Makefile', '\n')
예제 #15
0
def make_doc_directory(config, path):
    sphinx_conf = {
            'path'           : path,   # root path
            'sep'            : False,
            'dot'            : '_',
            'project'        : config['project_name'],
            'author'         : config['author'],
            'version'        : '@@VERSION@@',
            'release'        : '@@VERSION@@',
            'suffix'         : '.rst',
            'master'         : 'index',
            'epub'           : True,
            'ext_autodoc'    : True,
            'ext_doctest'    : False,
            'ext_interspinx' : True,
            'ext_todo'       : True,
            'ext_coverage'   : False,
            'ext_pngmath'    : True,
            'ext_mathjax'    : False,
            'ext_ifconfig'   : True,
            'ext_viewcode'   : True,
            'makefile'       : True,
            'batchfile'      : True}
    quickstart.generate(sphinx_conf)
    src_path = os.path.join(path, 'conf.py')
    with open(src_path, 'r') as src:
        with open(os.path.join(path, 'conf.py.skel'), 'w') as dst:
            for line in src.readlines():
                if RE_HTML_THEME.match(line):
                    line = 'html_theme = "openlmitheme"\n'
                dst.write(line)
    os.unlink(src_path)
    write_cmdline(config, os.path.join(path, 'cmdline.rst'))
    modify_doc_makefile(config, os.path.join(path, 'Makefile'))
    modify_doc_index(config, os.path.join(path, 'index.rst'))
    with open(os.path.join(path, 'python.rst'), 'w') as dst:
        name = str(config['command']).capitalize()
        match = RE_PROJECT_NAME.match(config['project_name'])
        if match:
            name = match.group(1)
        title = "%s Script python reference" % name
        heading = "%s\n%s" % (title, '='*len(title))
        dst.write(DOC_PYTHON_REFERENCE.format(
            name=config['command'], heading=heading))
예제 #16
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
    assert ns['man_pages'][0][1] == 'sphinx'
    assert ns['texinfo_documents'][0][1] == 'sphinx'
예제 #17
0
def test_default_filename(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'\u30c9\u30a4\u30c4',  # Fullwidth characters only
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['latex_documents'][0][1] == 'sphinx.tex'
    assert ns['man_pages'][0][1] == 'sphinx'
    assert ns['texinfo_documents'][0][1] == 'sphinx'
예제 #18
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_raw_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    f = open(conffile, 'rbU')
    try:
        code = compile(f.read(), conffile, 'exec')
    finally:
        f.close()
    exec code in ns
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')
    ]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
예제 #19
0
def test_quickstart_defaults(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': 'Sphinx Test',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_raw_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'conf.py'
    assert conffile.isfile()
    ns = {}
    f = open(conffile, 'rbU')
    try:
        code = compile(f.read(), conffile, 'exec')
    finally:
        f.close()
    exec code in ns
    assert ns['extensions'] == []
    assert ns['templates_path'] == ['_templates']
    assert ns['source_suffix'] == '.rst'
    assert ns['master_doc'] == 'index'
    assert ns['project'] == 'Sphinx Test'
    assert ns['copyright'] == '%s, Georg Brandl' % time.strftime('%Y')
    assert ns['version'] == '0.1'
    assert ns['release'] == '0.1'
    assert ns['html_static_path'] == ['_static']
    assert ns['latex_documents'] == [
        ('index', 'SphinxTest.tex', 'Sphinx Test Documentation',
         'Georg Brandl', 'manual')]

    assert (tempdir / '_static').isdir()
    assert (tempdir / '_templates').isdir()
    assert (tempdir / 'index.rst').isfile()
    assert (tempdir / 'Makefile').isfile()
    assert (tempdir / 'make.bat').isfile()
예제 #20
0
def test_quickstart_and_build(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'Fullwidth characters: \u30c9\u30a4\u30c4',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    app = application.Sphinx(
        tempdir,  # srcdir
        tempdir,  # confdir
        (tempdir / '_build' / 'html'),  # outdir
        (tempdir / '_build' / '.doctree'),  # doctreedir
        'html',  # buildername
        status=StringIO(),
        warning=warnfile)
    app.builder.build_all()
    warnings = warnfile.getvalue()
    assert not warnings
예제 #21
0
def test_quickstart_and_build(tempdir):
    answers = {
        'Root path': tempdir,
        'Project name': u'Fullwidth characters: \u30c9\u30a4\u30c4',
        'Author name': 'Georg Brandl',
        'Project version': '0.1',
    }
    qs.term_input = mock_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    app = application.Sphinx(
        tempdir,  # srcdir
        tempdir,  # confdir
        (tempdir / '_build' / 'html'),  # outdir
        (tempdir / '_build' / '.doctree'),  # doctreedir
        'html',  # buildername
        status=StringIO(),
        warning=warnfile)
    app.builder.build_all()
    warnings = warnfile.getvalue()
    assert not warnings
예제 #22
0
def test_quickstart_defaults(tempdir):
    answers = {
        "Root path": tempdir,
        "Project name": "Sphinx Test",
        "Author name": "Georg Brandl",
        "Project version": "0.1",
    }
    qs.term_input = mock_raw_input(answers)
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / "conf.py"
    assert conffile.isfile()
    ns = {}
    f = open(conffile, "U")
    try:
        code = compile(f.read(), conffile, "exec")
    finally:
        f.close()
    exec code in ns
    assert ns["extensions"] == []
    assert ns["templates_path"] == ["_templates"]
    assert ns["source_suffix"] == ".rst"
    assert ns["master_doc"] == "index"
    assert ns["project"] == "Sphinx Test"
    assert ns["copyright"] == "%s, Georg Brandl" % time.strftime("%Y")
    assert ns["version"] == "0.1"
    assert ns["release"] == "0.1"
    assert ns["html_static_path"] == ["_static"]
    assert ns["latex_documents"] == [("index", "SphinxTest.tex", "Sphinx Test Documentation", "Georg Brandl", "manual")]

    assert (tempdir / "_static").isdir()
    assert (tempdir / "_templates").isdir()
    assert (tempdir / "index.rst").isfile()
    assert (tempdir / "Makefile").isfile()
    assert (tempdir / "make.bat").isfile()
예제 #23
0
def make_doc_directory(config, path):
    sphinx_conf = {
        'path': path,  # root path
        'sep': False,
        'dot': '_',
        'project': config['project_name'],
        'author': config['author'],
        'version': '@@VERSION@@',
        'release': '@@VERSION@@',
        'suffix': '.rst',
        'master': 'index',
        'epub': True,
        'ext_autodoc': True,
        'ext_doctest': False,
        'ext_interspinx': True,
        'ext_todo': True,
        'ext_coverage': False,
        'ext_pngmath': True,
        'ext_mathjax': False,
        'ext_ifconfig': True,
        'ext_viewcode': True,
        'makefile': True,
        'batchfile': True
    }
    quickstart.generate(sphinx_conf)
    src_path = os.path.join(path, 'conf.py')
    with open(src_path, 'r') as src:
        with open(os.path.join(path, 'conf.py.skel'), 'w') as dst:
            for line in src.readlines():
                if RE_HTML_THEME.match(line):
                    line = 'html_theme = "openlmitheme"\n'
                dst.write(line)
    os.unlink(src_path)
    write_cmdline(config, os.path.join(path, 'cmdline.rst'))
    modify_doc_makefile(config, os.path.join(path, 'Makefile'))
    modify_doc_index(config, os.path.join(path, 'index.rst'))
예제 #24
0
    def create_new(self, silent=True):
        """
        Calls sphinx.quickstart to populate a new project directory.

        Uses the currently-configured options in self.conf_dict and
        self.quickstart_params.
        """

        defaults = quickstart_defaults.copy()

        defaults['path'] = self.dirname
        defaults.update(self.quickstart_params)

        quickstart.generate(defaults, silent=silent)

        if defaults['sep']:
            self.source_dir = os.path.join(self.dirname, 'source')
        else:
            self.source_dir = self.dirname
        self.build_dir = os.path.join(
            self.dirname, '%sbuild' % defaults['dot'])
        if self.conf_dict is not None:
            self.conf_fn = os.path.join(self.source_dir, 'conf.py')
            helpers.update_conf(self.conf_fn, self.conf_dict)
예제 #25
0
def post_render(config):

    target_directory = os.path.abspath(config.target_directory)
    pkg = config.variables['package.directory']

    pkg_dir = os.path.join(target_directory, pkg)
    if not test.d(pkg_dir):
        mkdir(pkg_dir)
        with open(os.path.join(pkg_dir, '__init__.py'), 'wb') as fd:
            fd.write('#  package\n')

    doc_root = os.path.join(target_directory, 'docs')
    vars = config.variables
    d = dict(path=doc_root, author=vars['author.name'],
             project=vars['package.name'],
             version='', ext_autodoc='y', ext_viewcode='y',
             batchfile=False)

    quickstart_do_prompt = quickstart.do_prompt

    def do_prompt(d, key, text, default=None, validator=quickstart.nonempty):
        print(key)
        if key in use_defaults:
            if default == 'y':
                default = True
            elif default == 'n':
                default = False
            d[key] = default
        elif key not in d:
            quickstart_do_prompt(d, key, text, default, validator)

    quickstart.do_prompt = do_prompt

    if not os.path.isdir(doc_root):
        # launch sphinx
        quickstart.ask_user(d)
        quickstart.generate(d)
        filename = os.path.join(doc_root, 'conf.py')

        # patch some files
        with open(filename, 'ab') as fd:
            fd.write('''
html_theme = 'nature'
import pkg_resources
version = pkg_resources.get_distribution("%s").version
release = version
''' % vars['package.name'])
        filename = os.path.join(doc_root, 'Makefile')
        with open(filename, 'rb') as fd:
            data = fd.read()
        data = data.replace('sphinx-build', '../bin/sphinx-build')
        with open(filename, 'wb') as fd:
            fd.write(data)

    # launch buildout
    cd(target_directory)
    if not test.f('bootstrap.py'):
        wget('-O bootstrap.py',
             'https://bootstrap.pypa.io/bootstrap-buildout.py') > 1
        chmod('+x bootstrap.py')

    sh.python('bootstrap.py --allow-site-packages') > 1
    if test.f('bin/buildout'):
        sh.python('bin/buildout') > 1
예제 #26
0
def main2(argv=sys.argv):
    """
    Parse and check the command line arguments.
    """
    parser = optparse.OptionParser(usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_paths, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o',
                      '--output-dir',
                      action='store',
                      dest='destdir',
                      help='Directory to place all output',
                      default='')
    parser.add_option('-d',
                      '--maxdepth',
                      action='store',
                      dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)',
                      type='int',
                      default=4)
    parser.add_option('-f',
                      '--force',
                      action='store_true',
                      dest='force',
                      help='Overwrite all files')
    parser.add_option('-n',
                      '--dry-run',
                      action='store_true',
                      dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-T',
                      '--no-toc',
                      action='store_true',
                      dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-s',
                      '--suffix',
                      action='store',
                      dest='suffix',
                      help='file suffix (default: rst)',
                      default='rst')
    parser.add_option('-F',
                      '--full',
                      action='store_true',
                      dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-H',
                      '--doc-project',
                      action='store',
                      dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A',
                      '--doc-author',
                      action='store',
                      dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V',
                      '--doc-version',
                      action='store',
                      dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R',
                      '--doc-release',
                      action='store',
                      dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot='_',
            project=opts.header,
            author=opts.author or 'Author',
            version=opts.version or '',
            release=opts.release or opts.version or '',
            suffix='.' + opts.suffix,
            master='index',
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #27
0
def main(argv=sys.argv):
    """
    Parse and check the command line arguments.
    """
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_paths, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

Note: By default this script will not overwrite already created files."""
    )

    parser.add_option(
        "-o", "--output-dir", action="store", dest="destdir", help="Directory to place all output", default=""
    )
    parser.add_option(
        "-d",
        "--maxdepth",
        action="store",
        dest="maxdepth",
        help="Maximum depth of submodules to show in the TOC " "(default: 4)",
        type="int",
        default=4,
    )
    parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all files")
    parser.add_option("-U", "--update", action="store_true", dest="update", help="overwrite ReST files if changed only")
    parser.add_option(
        "-n", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating files"
    )
    parser.add_option("-T", "--no-toc", action="store_true", dest="notoc", help="Don't create a table of contents file")
    parser.add_option("-s", "--suffix", action="store", dest="suffix", help="file suffix (default: rst)", default="rst")
    parser.add_option(
        "-F", "--full", action="store_true", dest="full", help="Generate a full project with sphinx-quickstart"
    )
    parser.add_option(
        "-H", "--doc-project", action="store", dest="header", help="Project name (default: root module name)"
    )
    parser.add_option(
        "-A",
        "--doc-author",
        action="store",
        dest="author",
        type="str",
        help="Project author(s), used when --full is given",
    )
    parser.add_option(
        "-V", "--doc-version", action="store", dest="version", help="Project version, used when --full is given"
    )
    parser.add_option(
        "-R",
        "--doc-release",
        action="store",
        dest="release",
        help="Project release, used when --full is given, " "defaults to --doc-version",
    )
    parser.add_option(
        "-M", "--module-page", action="store_true", dest="module_page", help="Create a ReST file for each module"
    )

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error("A package path is required.")

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error("An output directory is required.")
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith("."):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >> sys.stderr, "%s is not a directory." % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs

        modules.sort()
        prev_module = ""
        text = ""
        for module in modules:
            if module.startswith(prev_module + "."):
                continue
            prev_module = module
            text += "   %s\n" % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot="_",
            project=opts.header,
            author=opts.author or "Author",
            version=opts.version or "",
            release=opts.release or opts.version or "",
            suffix="." + opts.suffix,
            master="index",
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #28
0
def monkey_patch_generate(d, templatedir=None):
    global hook_d
    hook_d = copy.copy(d)

    generate(d, templatedir)
예제 #29
0
def test_quickstart_all_answers(tempdir):
    answers = {
        'Root path': tempdir,
        'Separate source and build': 'y',
        'Name prefix for templates': '.',
        'Project name': u'STASI™'.encode('utf-8'),
        'Author name': u'Wolfgang Schäuble & G\'Beckstein'.encode('utf-8'),
        'Project version': '2.0',
        'Project release': '2.0.1',
        'Project language': 'de',
        'Source file suffix': '.txt',
        'Name of your master document': 'contents',
        'autodoc': 'y',
        'doctest': 'yes',
        'intersphinx': 'no',
        'todo': 'y',
        'coverage': 'no',
        'imgmath': 'N',
        'mathjax': 'no',
        'ifconfig': 'no',
        'viewcode': 'no',
        'githubpages': 'no',
        'Create Makefile': 'no',
        'Create Windows command file': 'no',
        'Do you want to use the epub builder': 'yes',
    }
    qs.term_input = mock_input(answers, needanswer=True)
    qs.TERM_ENCODING = 'utf-8'
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / 'source' / 'conf.py'
    assert conffile.isfile()
    ns = {}
    execfile_(conffile, ns)
    assert ns['extensions'] == [
        'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo'
    ]
    assert ns['templates_path'] == ['.templates']
    assert ns['source_suffix'] == '.txt'
    assert ns['master_doc'] == 'contents'
    assert ns['project'] == u'STASI™'
    assert ns['copyright'] == u'%s, Wolfgang Schäuble & G\'Beckstein' % \
        time.strftime('%Y')
    assert ns['version'] == '2.0'
    assert ns['release'] == '2.0.1'
    assert ns['todo_include_todos'] is True
    assert ns['html_static_path'] == ['.static']
    assert ns['latex_documents'] == [
        ('contents', 'STASI.tex', u'STASI™ Documentation',
         u'Wolfgang Schäuble \\& G\'Beckstein', 'manual')]
    assert ns['epub_author'] == u'Wolfgang Schäuble & G\'Beckstein'
    assert ns['man_pages'] == [
        ('contents', 'stasi', u'STASI™ Documentation',
         [u'Wolfgang Schäuble & G\'Beckstein'], 1)]
    assert ns['texinfo_documents'] == [
        ('contents', 'STASI', u'STASI™ Documentation',
         u'Wolfgang Schäuble & G\'Beckstein', 'STASI',
         'One line description of project.', 'Miscellaneous')]

    assert (tempdir / 'build').isdir()
    assert (tempdir / 'source' / '.static').isdir()
    assert (tempdir / 'source' / '.templates').isdir()
    assert (tempdir / 'source' / 'contents.txt').isfile()
def make_rst(rootpath, excludes, destdir, header=None, suffix="rst",
             full=False, author="Author", version="", release="", maxdepth=4,
             dryrun=False, followlinks=False, includeprivate=False,
             separatemodules=True, noheadings=False, force=False, notoc=False):
    """ Make a set of RST files for the modules starting at rootpath
    """

    add_documenter(ModuleDocumenter)
    add_documenter(ClassDocumenter)
    add_documenter(ExceptionDocumenter)
    add_documenter(DataDocumenter)
    add_documenter(FunctionDocumenter)
    add_documenter(MethodDocumenter)
    add_documenter(AttributeDocumenter)
    add_documenter(InstanceAttributeDocumenter)

    if header is None:
        header = path.normpath(rootpath).split(path.sep)[-1]
    if suffix.startswith('.'):
        suffix = suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(destdir):
        if not dryrun:
            os.makedirs(destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, followlinks, includeprivate,
                           separatemodules, noheadings, destdir, dryrun, force,
                           suffix)
    if full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path=destdir,
            sep=False,
            dot='_',
            project=header,
            author=author,
            version=version,
            release=release,
            suffix='.' + suffix,
            master='index',
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=maxdepth,
            mastertoctree=text,
        )
        if not dryrun:
            qs.generate(d, silent=True, overwrite=force)
    elif not notoc:
        create_modules_toc_file(modules, header, maxdepth, destdir, dryrun,
                                force, suffix)
예제 #31
0
def main(argv=sys.argv):
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_path, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_path>s can be files and/or directories that will be excluded
from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option("-o",
                      "--output-dir",
                      action="store",
                      dest="destdir",
                      help="Directory to place all output",
                      default="")
    parser.add_option("-d",
                      "--maxdepth",
                      action="store",
                      dest="maxdepth",
                      help="Maximum depth of submodules to show in the TOC "
                      "(default: 4)",
                      type="int",
                      default=4)
    parser.add_option("-f",
                      "--force",
                      action="store_true",
                      dest="force",
                      help="Overwrite existing files")
    parser.add_option("-l",
                      "--follow-links",
                      action="store_true",
                      dest="followlinks",
                      default=False,
                      help="Follow symbolic links. Powerful when combined "
                      "with collective.recipe.omelette.")
    parser.add_option("-n",
                      "--dry-run",
                      action="store_true",
                      dest="dryrun",
                      help="Run the script without creating files")
    parser.add_option("-e",
                      "--separate",
                      action="store_true",
                      dest="separatemodules",
                      help="Put documentation for each module on its own page")
    parser.add_option("-P",
                      "--private",
                      action="store_true",
                      dest="includeprivate",
                      help="Include '_private' modules")
    parser.add_option("-T",
                      "--no-toc",
                      action="store_true",
                      dest="notoc",
                      help="Don\"t create a table of contents file")
    parser.add_option("-E",
                      "--no-headings",
                      action="store_true",
                      dest="noheadings",
                      help="Don\"t create headings for the module/package "
                      "packages (e.g. when the docstrings already contain "
                      "them)")
    parser.add_option("-s",
                      "--suffix",
                      action="store",
                      dest="suffix",
                      help="file suffix (default: rst)",
                      default="rst")
    parser.add_option("-F",
                      "--full",
                      action="store_true",
                      dest="full",
                      help="Generate a full project with sphinx-quickstart")
    parser.add_option("-H",
                      "--doc-project",
                      action="store",
                      dest="header",
                      help="Project name (default: root module name)")
    parser.add_option("-A",
                      "--doc-author",
                      action="store",
                      dest="author",
                      type="str",
                      help="Project author(s), used when --full is given")
    parser.add_option("-V",
                      "--doc-version",
                      action="store",
                      dest="version",
                      help="Project version, used when --full is given")
    parser.add_option("-R",
                      "--doc-release",
                      action="store",
                      dest="release",
                      help="Project release, used when --full is given, "
                      "defaults to --doc-version")

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error("A package path is required.")

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error("An output directory is required.")
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith("."):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >> sys.stderr, "%s is not a directory." % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs

        modules.sort()
        prev_module = ""
        text = ""
        for module in modules:
            if module.startswith(prev_module + "."):
                continue
            prev_module = module
            text += "   %s\n" % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot="_",
            project=opts.header,
            author=opts.author or "Author",
            version=opts.version or "",
            release=opts.release or opts.version or "",
            suffix="." + opts.suffix,
            master="index",
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #32
0
"ext_pngmath": true,
"sep": true,
"ext_todo": false,
"ext_coverage": false,
"ext_viewcode": false,
"batchfile": true,
"master": "index",
"epub": false,
"ext_intersphinx": false,
"dot": "_",
"ext_doctest": false
}'''

# Load the options from the json string into a Python dict
options = json.loads(json_conf)

# Everything below is copied from quickstart.py: you need not understand it
# unless noted

if not color_terminal():
    nocolor()

try:
    #Ask the user for the rest of the options
    qs.ask_user(options)
except (KeyboardInterrupt, EOFError):
    print
    print '[Interrupted.]'
    exit()
qs.generate(options)
예제 #33
0
def test_quickstart_all_answers(tempdir):
    answers = {
        "Root path": tempdir,
        "Separate source and build": "y",
        "Name prefix for templates": ".",
        "Project name": u"STASI™".encode("utf-8"),
        "Author name": u"Wolfgang Schäuble & G'Beckstein".encode("utf-8"),
        "Project version": "2.0",
        "Project release": "2.0.1",
        "Source file suffix": ".txt",
        "Name of your master document": "contents",
        "autodoc": "y",
        "doctest": "yes",
        "intersphinx": "no",
        "todo": "n",
        "coverage": "no",
        "pngmath": "N",
        "mathjax": "no",
        "ifconfig": "no",
        "viewcode": "no",
        "Create Makefile": "no",
        "Create Windows command file": "no",
        "Do you want to use the epub builder": "yes",
    }
    qs.term_input = mock_raw_input(answers, needanswer=True)
    qs.TERM_ENCODING = "utf-8"
    d = {}
    qs.ask_user(d)
    qs.generate(d)

    conffile = tempdir / "source" / "conf.py"
    assert conffile.isfile()
    ns = {}
    f = open(conffile, "U")
    try:
        code = compile(f.read(), conffile, "exec")
    finally:
        f.close()
    exec code in ns
    assert ns["extensions"] == ["sphinx.ext.autodoc", "sphinx.ext.doctest"]
    assert ns["templates_path"] == [".templates"]
    assert ns["source_suffix"] == ".txt"
    assert ns["master_doc"] == "contents"
    assert ns["project"] == u"STASI™"
    assert ns["copyright"] == u"%s, Wolfgang Schäuble & G'Beckstein" % time.strftime("%Y")
    assert ns["version"] == "2.0"
    assert ns["release"] == "2.0.1"
    assert ns["html_static_path"] == [".static"]
    assert ns["latex_documents"] == [
        ("contents", "STASI.tex", u"STASI™ Documentation", u"Wolfgang Schäuble \\& G'Beckstein", "manual")
    ]
    assert ns["epub_author"] == u"Wolfgang Schäuble & G'Beckstein"
    assert ns["man_pages"] == [("contents", "stasi", u"STASI™ Documentation", [u"Wolfgang Schäuble & G'Beckstein"], 1)]
    assert ns["texinfo_documents"] == [
        (
            "contents",
            "STASI",
            u"STASI™ Documentation",
            u"Wolfgang Schäuble & G'Beckstein",
            "STASI",
            "One line description of project.",
            "Miscellaneous",
        )
    ]

    assert (tempdir / "build").isdir()
    assert (tempdir / "source" / ".static").isdir()
    assert (tempdir / "source" / ".templates").isdir()
    assert (tempdir / "source" / "contents.txt").isfile()
예제 #34
0
def main(argv=sys.argv):
    """
    Parse and check the command line arguments.
    """
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_paths, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o', '--output-dir', action='store', dest='destdir',
                      help='Directory to place all output', default='')
    parser.add_option('-d', '--maxdepth', action='store', dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 2)', type='int', default=2)
    parser.add_option('-f', '--force', action='store_true', dest='force',
                      help='Overwrite all files')
    parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-T', '--no-toc', action='store_true', dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-s', '--suffix', action='store', dest='suffix',
                      help='file suffix (default: rst)', default='rst')
    parser.add_option('-F', '--full', action='store_true', dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-H', '--doc-project', action='store', dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A', '--doc-author', action='store', dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V', '--doc-version', action='store', dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R', '--doc-release', action='store', dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    print "Detected Packages:\n\t", "\n\t".join(modules)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #35
0
def patch_generate(original_d, overwrite=True, silent=False, templatedir=None):
    global d
    d = copy.copy(original_d)
    generate(original_d, overwrite, silent=False, templatedir=None)
예제 #36
0
파일: apidoc.py 프로젝트: havenwang/sphinx
def main(argv=sys.argv):
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_path, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_path>s can be files and/or directories that will be excluded
from generation.

Note: By default this script will not overwrite already created files."""
    )

    parser.add_option(
        "-o", "--output-dir", action="store", dest="destdir", help="Directory to place all output", default=""
    )
    parser.add_option(
        "-d",
        "--maxdepth",
        action="store",
        dest="maxdepth",
        help="Maximum depth of submodules to show in the TOC " "(default: 4)",
        type="int",
        default=4,
    )
    parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite existing files")
    parser.add_option(
        "-l",
        "--follow-links",
        action="store_true",
        dest="followlinks",
        default=False,
        help="Follow symbolic links. Powerful when combined " "with collective.recipe.omelette.",
    )
    parser.add_option(
        "-n", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating files"
    )
    parser.add_option(
        "-e",
        "--separate",
        action="store_true",
        dest="separatemodules",
        help="Put documentation for each module on its own page",
    )
    parser.add_option("-P", "--private", action="store_true", dest="includeprivate", help='Include "_private" modules')
    parser.add_option("-T", "--no-toc", action="store_true", dest="notoc", help="Don't create a table of contents file")
    parser.add_option(
        "-E",
        "--no-headings",
        action="store_true",
        dest="noheadings",
        help="Don't create headings for the module/package "
        "packages (e.g. when the docstrings already contain "
        "them)",
    )
    parser.add_option(
        "-M",
        "--module-first",
        action="store_true",
        dest="modulefirst",
        help="Put module documentation before submodule " "documentation",
    )
    parser.add_option("-s", "--suffix", action="store", dest="suffix", help="file suffix (default: rst)", default="rst")
    parser.add_option(
        "-F", "--full", action="store_true", dest="full", help="Generate a full project with sphinx-quickstart"
    )
    parser.add_option(
        "-H", "--doc-project", action="store", dest="header", help="Project name (default: root module name)"
    )
    parser.add_option(
        "-A",
        "--doc-author",
        action="store",
        dest="author",
        type="str",
        help="Project author(s), used when --full is given",
    )
    parser.add_option(
        "-V", "--doc-version", action="store", dest="version", help="Project version, used when --full is given"
    )
    parser.add_option(
        "-R",
        "--doc-release",
        action="store",
        dest="release",
        help="Project release, used when --full is given, " "defaults to --doc-version",
    )
    parser.add_option("--version", action="store_true", dest="show_version", help="Show version information and exit")

    (opts, args) = parser.parse_args(argv[1:])

    if opts.show_version:
        print("Sphinx (sphinx-apidoc) %s" % __display_version__)
        return 0

    if not args:
        parser.error("A package path is required.")

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error("An output directory is required.")
    if opts.header is None:
        opts.header = path.abspath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith("."):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print("%s is not a directory." % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.abspath(rootpath)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs

        modules.sort()
        prev_module = ""
        text = ""
        for module in modules:
            if module.startswith(prev_module + "."):
                continue
            prev_module = module
            text += "   %s\n" % module
        d = dict(
            path=opts.destdir,
            sep=False,
            dot="_",
            project=opts.header,
            author=opts.author or "Author",
            version=opts.version or "",
            release=opts.release or opts.version or "",
            suffix="." + opts.suffix,
            master="index",
            epub=True,
            ext_autodoc=True,
            ext_viewcode=True,
            ext_todo=True,
            makefile=True,
            batchfile=True,
            mastertocmaxdepth=opts.maxdepth,
            mastertoctree=text,
            language="en",
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #37
0
def main(argv=sys.argv):
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_path, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_path>s can be files and/or directories that will be excluded
from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o', '--output-dir', action='store', dest='destdir',
                      help='Directory to place all output', default='')
    parser.add_option('-d', '--maxdepth', action='store', dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)', type='int', default=4)
    parser.add_option('-f', '--force', action='store_true', dest='force',
                      help='Overwrite existing files')
    parser.add_option('-l', '--follow-links', action='store_true',
                      dest='followlinks', default=False,
                      help='Follow symbolic links. Powerful when combined '
                      'with collective.recipe.omelette.')
    parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-e', '--separate', action='store_true',
                      dest='separatemodules',
                      help='Put documentation for each module on its own page')
    parser.add_option('-P', '--private', action='store_true',
                      dest='includeprivate',
                      help='Include "_private" modules')
    parser.add_option('-T', '--no-toc', action='store_true', dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-E', '--no-headings', action='store_true',
                      dest='noheadings',
                      help='Don\'t create headings for the module/package '
                           'packages (e.g. when the docstrings already contain '
                           'them)')
    parser.add_option('-M', '--module-first', action='store_true',
                      dest='modulefirst',
                      help='Put module documentation before submodule '
                      'documentation')
    parser.add_option('-s', '--suffix', action='store', dest='suffix',
                      help='file suffix (default: rst)', default='rst')
    parser.add_option('-F', '--full', action='store_true', dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-H', '--doc-project', action='store', dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A', '--doc-author', action='store', dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V', '--doc-version', action='store', dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R', '--doc-release', action='store', dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')
    parser.add_option('--version', action='store_true', dest='show_version',
                      help='Show version information and exit')

    (opts, args) = parser.parse_args(argv[1:])

    if opts.show_version:
        print('Sphinx (sphinx-apidoc) %s' % __version__)
        return 0

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
            language = 'en',
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
예제 #38
0
파일: apidoc.py 프로젝트: wlonk/sphinx
def main(argv=sys.argv[1:]):
    # type: (List[str]) -> int
    """Parse and check the command line arguments."""
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_pattern>s can be file and/or directory patterns that will be
excluded from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o', '--output-dir', action='store', dest='destdir',
                      help='Directory to place all output', default='')
    parser.add_option('-d', '--maxdepth', action='store', dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)', type='int', default=4)
    parser.add_option('-f', '--force', action='store_true', dest='force',
                      help='Overwrite existing files')
    parser.add_option('-l', '--follow-links', action='store_true',
                      dest='followlinks', default=False,
                      help='Follow symbolic links. Powerful when combined '
                      'with collective.recipe.omelette.')
    parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-e', '--separate', action='store_true',
                      dest='separatemodules',
                      help='Put documentation for each module on its own page')
    parser.add_option('-P', '--private', action='store_true',
                      dest='includeprivate',
                      help='Include "_private" modules')
    parser.add_option('-T', '--no-toc', action='store_true', dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-E', '--no-headings', action='store_true',
                      dest='noheadings',
                      help='Don\'t create headings for the module/package '
                           'packages (e.g. when the docstrings already contain '
                           'them)')
    parser.add_option('-M', '--module-first', action='store_true',
                      dest='modulefirst',
                      help='Put module documentation before submodule '
                      'documentation')
    parser.add_option('--implicit-namespaces', action='store_true',
                      dest='implicit_namespaces',
                      help='Interpret module paths according to PEP-0420 '
                           'implicit namespaces specification')
    parser.add_option('-s', '--suffix', action='store', dest='suffix',
                      help='file suffix (default: rst)', default='rst')
    parser.add_option('-F', '--full', action='store_true', dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-a', '--append-syspath', action='store_true',
                      dest='append_syspath',
                      help='Append module_path to sys.path, used when --full is given')
    parser.add_option('-H', '--doc-project', action='store', dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A', '--doc-author', action='store', dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V', '--doc-version', action='store', dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R', '--doc-release', action='store', dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')
    parser.add_option('--version', action='store_true', dest='show_version',
                      help='Show version information and exit')
    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext, action='store_true',
                         dest='ext_' + ext, default=False,
                         help='enable %s extension' % ext)

    (opts, args) = parser.parse_args(argv)

    if opts.show_version:
        print('Sphinx (sphinx-apidoc) %s' % __display_version__)
        return 0

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.abspath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.abspath(rootpath)
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep = False,
            dot = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            ext_todo = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = opts.append_syspath,
        )
        enabled_exts = {'ext_' + ext: getattr(opts, 'ext_' + ext)
                        for ext in EXTENSIONS if getattr(opts, 'ext_' + ext)}
        d.update(enabled_exts)

        if isinstance(opts.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(opts.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(opts.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(opts.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
    return 0