Build documentation using sphinx
325097
def docs(context, builder='html'):
    ""
    cmdline = 'python -msphinx -M {} {} {} {}'.format(builder, DOCS_SRCDIR, DOCS_BUILDDIR, SPHINX_OPTS)
    context.run(cmdline)
290652
def autodocs():
    ""
    build_dir = path('docs/_build')
    index_html = build_dir / 'html/index.html'
    if build_dir.exists():
        build_dir.rmtree()

    with pushd("docs"):
        print "\n*** Generating API doc ***\n"
        sh("sphinx-apidoc -o apidoc -f -T -M ../src/pyrocore")
        sh("sphinx-apidoc -o apidoc -f -T -M $(dirname $(python -c 'import tempita; print(tempita.__file__)'))")
        print "\n*** Generating HTML doc ***\n"
        sh('nohup %s/Makefile SPHINXBUILD="sphinx-autobuild -p %d'
           ' -i \'.*\' -i \'*.log\' -i \'*.png\' -i \'*.txt\'" html >autobuild.log 2>&1 &'
           % (os.getcwd(), SPHINX_AUTOBUILD_PORT))

    for i in range(25):
        time.sleep(2.5)
        pid = watchdog_pid()
        if pid:
            sh("touch docs/index.rst")
            sh('ps {}'.format(pid))
            url = 'http://localhost:{port:d}/'.format(port=SPHINX_AUTOBUILD_PORT)
            print("\n*** Open '{}' in your browser...".format(url))
            break
403705
def _build_toctree(self):
        
        dirname = posixpath.dirname(self._env.docname)
        tree_prefix = self.options['toctree'].strip()
        root = posixpath.normpath(posixpath.join(dirname, tree_prefix))
        docnames = [docname for docname in self._env.found_docs
                    if docname.startswith(root)]

        # Sort docnames alphabetically based on **class** name.
        # The standard we assume is that task doc pages are named after
        # their Python namespace.
        # NOTE: this ordering only applies to the toctree; the visual ordering
        # is set by `process_task_topic_list`.
        # NOTE: docnames are **always** POSIX-like paths
        class_names = [docname.split('/')[-1].split('.')[-1]
                       for docname in docnames]
        docnames = [docname for docname, _ in
                    sorted(zip(docnames, class_names),
                           key=lambda pair: pair[1])]

        tocnode = sphinx.addnodes.toctree()
        tocnode['includefiles'] = docnames
        tocnode['entries'] = [(None, docname) for docname in docnames]
        tocnode['maxdepth'] = -1
        tocnode['glob'] = None
        tocnode['hidden'] = True

        return tocnode
683349
def call_env_doctree_read(cls, kb_app, sphinx_app: Sphinx,
                              doctree: doctree):
        

        for callback in EventAction.get_callbacks(kb_app,
                                                  SphinxEvent.DREAD):
            callback(kb_app, sphinx_app, doctree)
398438
def run_sphinx():
    """"""
    old_dir = here_directory()
    os.chdir(str(doc_directory()))
    doc_status = subprocess.check_call(['make', 'html'], shell=True)
    os.chdir(str(old_dir))  # go back to former working directory
    if doc_status is not 0:
        exit(Fore.RED + 'Something broke generating your documentation...')
1121113
def _build_toctree_node(parent=None, entries=None, includefiles=None,
                        caption=None):
    
    # Add the toctree's node itself
    subnode = sphinx.addnodes.toctree()
    subnode['parent'] = parent
    subnode['entries'] = entries
    subnode['includefiles'] = includefiles
    subnode['caption'] = caption
    # These values are needed for toctree node types. We don't need/want
    # these to be configurable for module-toctree.
    subnode['maxdepth'] = 1
    subnode['hidden'] = False
    subnode['glob'] = None
    subnode['hidden'] = False
    subnode['includehidden'] = False
    subnode['numbered'] = 0
    subnode['titlesonly'] = False
    return subnode
239930
def render_sphinx_doc(self, doc, context=None, css_path=CSS_PATH):
        """"""
        # Math rendering option could have changed
        if self.main.editor is not None:
            fname = self.main.editor.get_current_filename()
            dname = osp.dirname(fname)
        else:
            dname = ''
        self._sphinx_thread.render(doc, context, self.get_option('math'),
                                   dname, css_path=self.css_path)
128663
def doc():
    """"""
    kwdb = current_app.kwdb

    libraries = get_collections(kwdb, libtype="library")
    resource_files = get_collections(kwdb, libtype="resource")
    hierarchy = get_navpanel_data(kwdb)

    return flask.render_template("home.html",
                                 data={"libraries": libraries,
                                       "version": __version__,
                                       "libdoc": None,
                                       "hierarchy": hierarchy,
                                       "resource_files": resource_files
                                   })
226267
def buildcss(app, buildpath, imagefile):
    """"""
    # set default values
    div = 'body'
    repeat = 'repeat-y'
    position = 'center'
    attachment = 'scroll'

    if app.config.sphinxmark_div != 'default':
        div = app.config.sphinxmark_div

    if app.config.sphinxmark_repeat is False:
        repeat = 'no-repeat'

    if app.config.sphinxmark_fixed is True:
        attachment = 'fixed'

    border = app.config.sphinxmark_border
    if border == 'left' or border == 'right':
        css = template('border', div=div, image=imagefile, side=border)
    else:
        css = template('watermark', div=div, image=imagefile, repeat=repeat,
                       position=position, attachment=attachment)
    LOG.debug('[sphinxmark] Template: ' + css)
    cssname = 'sphinxmark.css'
    cssfile = os.path.join(buildpath, cssname)

    with open(cssfile, 'w') as f:
        f.write(css)

    return(cssname)
852799
def run_apidoc(_):
    """"""
    current_directory = os.path.abspath(os.path.dirname(__file__))
    output_path = os.path.join(current_directory, 'source')
    cmd_path = 'sphinx-apidoc'
    if hasattr(sys, 'real_prefix'):  # Check to see if we are in a virtualenv
        # If we are, assemble the path manually
        cmd_path = os.path.abspath(os.path.join(sys.prefix, 'bin', 'sphinx-apidoc'))
    main([cmd_path, '-e', '-o', output_path, '../cinder_data', '--force'])
102310
def ignore_sphinx():
    """"""
    (directives, roles) = _get_directives_and_roles_from_sphinx()

    directives += [
        'centered',
        'include',
        'deprecated',
        'index',
        'no-code-block',
        'literalinclude',
        'hlist',
        'seealso',
        'toctree',
        'todo',
        'versionadded',
        'versionchanged']

    ext_autosummary = [
        'autosummary',
        'currentmodule',
    ]

    ignore_directives_and_roles(directives + ext_autosummary,
                                roles + ['ctype'])
35319
def run(self):
        """"""
        print('---- BUILDING ----')
        _build.run(self)

        # build documentation
        print('---- BUILDING DOCS ----')
        docdir = os.path.join(self.build_lib, 'pyshtools', 'doc')
        self.mkpath(docdir)
        doc_builder = os.path.join(self.build_lib, 'pyshtools', 'make_docs.py')
        doc_source = '.'
        check_call([sys.executable, doc_builder, doc_source, self.build_lib])

        print('---- ALL DONE ----')
761915
def sphinx(self):
        """"""
        if callable(self.default):
            default_val = self.default()
            default_str = 'new instance of {}'.format(
                default_val.__class__.__name__
            )
        else:
            default_val = self.default
            default_str = '{}'.format(self.default)
        try:
            if default_val is None or default_val is undefined:
                default_str = ''
            elif len(default_val) == 0:                                        #pylint: disable=len-as-condition
                default_str = ''
            else:
                default_str = ', Default: {}'.format(default_str)
        except TypeError:
            default_str = ', Default: {}'.format(default_str)

        prop_doc = super(Property, self).sphinx()
        return '{doc}{default}'.format(doc=prop_doc, default=default_str)
1004699
def cli():
    """"""
    parser = argparse.ArgumentParser(prog="sphinx-serve",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter,
                                     conflict_handler="resolve",
                                     description=__doc__
                                     )

    parser.add_argument("-v", "--version", action="version",
                        version="%(prog)s {0}".format(__version__)
                        )

    parser.add_argument("-h", "--host", action="store",
                        default="0.0.0.0",
                        help="Listen to the given hostname"
                        )

    parser.add_argument("-p", "--port", action="store",
                        type=int, default=8081,
                        help="Listen to given port"
                        )

    parser.add_argument("-b", "--build", action="store",
                        default="_build",
                        help="Build folder name"
                        )

    parser.add_argument("-s", "--single", action="store_true",
                        help="Serve the single-html documentation version"
                        )

    return parser.parse_args()
979455
def _get_directives_and_roles_from_sphinx():
    """"""
    if SPHINX_INSTALLED:
        sphinx_directives = list(sphinx.domains.std.StandardDomain.directives)
        sphinx_roles = list(sphinx.domains.std.StandardDomain.roles)

        for domain in [sphinx.domains.c.CDomain,
                       sphinx.domains.cpp.CPPDomain,
                       sphinx.domains.javascript.JavaScriptDomain,
                       sphinx.domains.python.PythonDomain]:

            sphinx_directives += list(domain.directives) + [
                '{}:{}'.format(domain.name, item)
                for item in list(domain.directives)]

            sphinx_roles += list(domain.roles) + [
                '{}:{}'.format(domain.name, item)
                for item in list(domain.roles)]
    else:
        sphinx_roles = [
            'abbr',
            'command',
            'dfn',
            'doc',
            'download',
            'envvar',
            'file',
            'guilabel',
            'kbd',
            'keyword',
            'mailheader',
            'makevar',
            'manpage',
            'menuselection',
            'mimetype',
            'newsgroup',
            'option',
            'program',
            'py:func',
            'ref',
            'regexp',
            'samp',
            'term',
            'token']

        sphinx_directives = [
            'autosummary',
            'currentmodule',
            'centered',
            'c:function',
            'c:type',
            'include',
            'deprecated',
            'envvar',
            'glossary',
            'index',
            'no-code-block',
            'literalinclude',
            'hlist',
            'option',
            'productionlist',
            'py:function',
            'seealso',
            'toctree',
            'todo',
            'versionadded',
            'versionchanged']

    return (sphinx_directives, sphinx_roles)
427287
def _get_paths(options):
    
    opts = options

    docroot = path(opts.get('docroot', 'docs'))
    if not docroot.exists():
        raise BuildFailure("Sphinx documentation root (%s) does not exist."
                           % docroot)

    builddir = docroot / opts.get("builddir", ".build")

    srcdir = docroot / opts.get("sourcedir", "")
    if not srcdir.exists():
        raise BuildFailure("Sphinx source file dir (%s) does not exist"
                           % srcdir)

    # Where is the sphinx conf.py file?
    confdir = path(opts.get('confdir', srcdir))

    # Where should output files be generated?
    outdir = opts.get('outdir', '')
    if outdir:
        outdir = path(outdir)
    else:
        outdir = builddir / opts.get('builder', 'html')

    # Where are doctrees cached?
    doctrees = opts.get('doctrees', '')
    if not doctrees:
        doctrees = builddir / "doctrees"
    else:
        doctrees = path(doctrees)

    return Bunch(locals())
1362918
def _construct_manpage_specific_structure(self, parser_info):
        
        items = []
        # SYNOPSIS section
        synopsis_section = nodes.section(
            '',
            nodes.title(text='Synopsis'),
            nodes.literal_block(text=parser_info["bare_usage"]),
            ids=['synopsis-section'])
        items.append(synopsis_section)
        # DESCRIPTION section
        if 'nodescription' not in self.options:
            description_section = nodes.section(
                '',
                nodes.title(text='Description'),
                nodes.paragraph(text=parser_info.get(
                    'description', parser_info.get(
                        'help', "undocumented").capitalize())),
                ids=['description-section'])
            nested_parse_with_titles(
                self.state, self.content, description_section)
            items.append(description_section)
        if parser_info.get('epilog') and 'noepilog' not in self.options:
            # TODO: do whatever sphinx does to understand ReST inside
            # docstrings magically imported from other places. The nested
            # parse method invoked above seem to be able to do this but
            # I haven't found a way to do it for arbitrary text
            if description_section:
                description_section += nodes.paragraph(
                    text=parser_info['epilog'])
            else:
                description_section = nodes.paragraph(
                    text=parser_info['epilog'])
                items.append(description_section)
        # OPTIONS section
        options_section = nodes.section(
            '',
            nodes.title(text='Options'),
            ids=['options-section'])
        if 'args' in parser_info:
            options_section += nodes.paragraph()
            options_section += nodes.subtitle(text='Positional arguments:')
            options_section += self._format_positional_arguments(parser_info)
        for action_group in parser_info['action_groups']:
            if 'options' in parser_info:
                options_section += nodes.paragraph()
                options_section += nodes.subtitle(text=action_group['title'])
                options_section += self._format_optional_arguments(action_group)

        # NOTE: we cannot generate NAME ourselves. It is generated by
        # docutils.writers.manpage
        # TODO: items.append(files)
        # TODO: items.append(see also)
        # TODO: items.append(bugs)

        if len(options_section.children) > 1:
            items.append(options_section)
        if 'nosubcommands' not in self.options:
            # SUBCOMMANDS section (non-standard)
            subcommands_section = nodes.section(
                '',
                nodes.title(text='Sub-Commands'),
                ids=['subcommands-section'])
            if 'children' in parser_info:
                subcommands_section += self._format_subcommands(parser_info)
            if len(subcommands_section) > 1:
                items.append(subcommands_section)
        if os.getenv("INCLUDE_DEBUG_SECTION"):
            import json
            # DEBUG section (non-standard)
            debug_section = nodes.section(
                '',
                nodes.title(text="Argparse + Sphinx Debugging"),
                nodes.literal_block(text=json.dumps(parser_info, indent='  ')),
                ids=['debug-section'])
            items.append(debug_section)
        return items