Build docs with sphinx-build
351692
def build(ctx, builder="html", options=""):
    """"""
    sourcedir = ctx.config.sphinx.sourcedir
    destdir = Path(ctx.config.sphinx.destdir or "build")/builder
    destdir = destdir.abspath()
    with cd(sourcedir):
        destdir_relative = Path(".").relpathto(destdir)
        command = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \
                    .format(builder=builder, sourcedir=".",
                            destdir=destdir_relative, opts=options)
        ctx.run(command)
784394
def on_doctree_read(app, document):
    
    literal_blocks = uqbar.book.sphinx.collect_literal_blocks(document)
    cache_mapping = uqbar.book.sphinx.group_literal_blocks_by_cache_path(literal_blocks)
    node_mapping = {}
    use_cache = bool(app.config["uqbar_book_use_cache"])
    for cache_path, literal_block_groups in cache_mapping.items():
        kwargs = dict(
            extensions=app.uqbar_book_extensions,
            setup_lines=app.config["uqbar_book_console_setup"],
            teardown_lines=app.config["uqbar_book_console_teardown"],
            use_black=bool(app.config["uqbar_book_use_black"]),
        )
        for literal_blocks in literal_block_groups:
            try:
                if use_cache:
                    local_node_mapping = uqbar.book.sphinx.interpret_code_blocks_with_cache(
                        literal_blocks, cache_path, app.connection, **kwargs
                    )
                else:
                    local_node_mapping = uqbar.book.sphinx.interpret_code_blocks(
                        literal_blocks, **kwargs
                    )
                node_mapping.update(local_node_mapping)
            except ConsoleError as exception:
                message = exception.args[0].splitlines()[-1]
                logger.warning(message, location=exception.args[1])
                if app.config["uqbar_book_strict"]:
                    raise
    uqbar.book.sphinx.rebuild_document(document, node_mapping)
896193
def init(args):
    
    # working directory
    dir_path = Path().absolute()

    if not args.project_name or args.project_name.find("/") >= 0:
        print(
            "{}You should specify a valid project name{}".format(
                utils.colors.FAIL, utils.colors.ENDC
            )
        )
        return

    project_path = dir_path / args.project_name

    # Create the Home Documentation's directory
    if not project_path.exists():
        project_path.mkdir()
    else:
        print(
            "{}This project already exists{}".format(
                utils.colors.FAIL, utils.colors.ENDC
            )
        )
        return

    # Directory with the Home Documentation's source code
    home_doc_path = project_path / "docs"
    home_doc_path.mkdir()
    help_doc_path = home_doc_path / "help"
    help_doc_path.mkdir()

    file_path = Path(__file__).resolve().parent / "include"

    # Add initial files
    copyfile(file_path / "index.md", home_doc_path / "index.md")
    copyfile(file_path / "How_To_Use_Mkinx.md", help_doc_path / "How_To_Use_Mkinx.md")
    copyfile(
        file_path / "Writing_Sphinx_Documentation.md",
        help_doc_path / "Writing_Sphinx_Documentation.md",
    )

    with open(file_path / "mkdocs.yml", "r") as f:
        lines = f.readlines()

    input_text = "What is your Documentation's name"
    input_text += " (it can be changed later in mkdocs.yml)?\n"
    input_text += "[Default: {} - Home Documentation]\n"

    site_name = input(input_text.format(args.project_name.capitalize()))
    if not site_name:
        site_name = "{} - Home Documentation".format(args.project_name.capitalize())

    lines[0] = "site_name: {}\n".format(site_name)

    with open(project_path / "mkdocs.yml", "w") as f:
        f.writelines(lines)

    example_project_path = project_path / "example_project" / "example_project"

    windows = "y" if sys.platform in {"win32", "cygwin"} else "n"

    copytree(file_path / "example_project", example_project_path)
    move(str(example_project_path / "source"), str(project_path / "example_project"))
    move(
        str(project_path / "example_project" / "example_project" / "Makefile"),
        str(project_path / "example_project"),
    )
    if windows == "y":
        move(
            str(project_path / "example_project" / "example_project" / "make.bat"),
            str(project_path / "example_project"),
        )
    else:
        os.remove(
            str(project_path / "example_project" / "example_project" / "make.bat")
        )

    static = project_path / "example_project" / "source"
    static /= "_static"
    if not static.exists():
        static.mkdir()

    _ = subprocess.check_output(
        "cd {} && mkinx build -F -A > /dev/null".format(args.project_name), shell=True
    )

    print(
        "\n\n",
        utils.colors.OKBLUE,
        "{}/{} created as a showcase of how mkinx works".format(
            args.project_name, "example_project"
        ),
        utils.colors.ENDC,
    )

    print(
        "\n",
        utils.colors.OKGREEN,
        "Success!",
        utils.colors.ENDC,
        "You can now start your Docs in ./{}\n".format(args.project_name),
        utils.colors.HEADER,
        "$ cd ./{}".format(args.project_name),
        utils.colors.ENDC,
    )
    print(
        "  Start the server from within your Docs to see them \n  (default",
        "port is 8443 but you can change it with the -s flag):",
    )
    print(
        utils.colors.HEADER,
        " {} $ mkinx serve\n".format(args.project_name),
        utils.colors.ENDC,
    )
1296927
def build_scala_docs(app):
    """"""
    scala_path = app.builder.srcdir + '/../scala-package'
    scala_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep -v \"\/javaapi\"  | egrep -v \"Suite\"'
    scala_doc_classpath = ':'.join([
        '`find native -name "*.jar" | grep "target/lib/" | tr "\\n" ":" `',
        '`find macros -name "*.jar" | tr "\\n" ":" `',
        '`find core -name "*.jar" | tr "\\n" ":" `',
        '`find infer -name "*.jar" | tr "\\n" ":" `'
    ])
    # There are unresolvable errors on mxnet 1.2.x. We are ignoring those errors while aborting the ci on newer versions
    scala_ignore_errors = '; exit 0' if any(v in _BUILD_VER for v in ['1.2.', '1.3.']) else ''
    _run_cmd('cd {}; scaladoc `{}` -classpath {} -feature -deprecation {}'
             .format(scala_path, scala_doc_sources, scala_doc_classpath, scala_ignore_errors))
    dest_path = app.builder.outdir + '/api/scala/docs'
    _run_cmd('rm -rf ' + dest_path)
    _run_cmd('mkdir -p ' + dest_path)
    # 'index' and 'package.html' do not exist in later versions of scala; delete these after upgrading scala>2.12.x
    scaladocs = ['index', 'index.html', 'org', 'lib', 'index.js', 'package.html']
    for doc_file in scaladocs:
        _run_cmd('cd ' + scala_path + ' && mv -f ' + doc_file + ' ' + dest_path + '; exit 0')
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)
506725
def build_clojure_docs(app):
    """"""
    clojure_path = app.builder.srcdir + '/../contrib/clojure-package'
    _run_cmd('cd ' + clojure_path + '; lein codox')
    dest_path = app.builder.outdir + '/api/clojure/docs'
    _run_cmd('rm -rf ' + dest_path)
    _run_cmd('mkdir -p ' + dest_path)
    clojure_doc_path = app.builder.srcdir + '/../contrib/clojure-package/target/doc'
    _run_cmd('cd ' + clojure_doc_path + ' && cp -r *  ' + dest_path + '; exit 0')
1334590
def sphinx(self):
        """"""
        try:
            assert __IPYTHON__
            classdoc = ''
        except (NameError, AssertionError):
            scls = self.sphinx_class()
            classdoc = ' ({})'.format(scls) if scls else ''

        prop_doc = '**{name}**{cls}: {doc}{info}'.format(
            name=self.name,
            cls=classdoc,
            doc=self.doc,
            info=', {}'.format(self.info) if self.info else '',
        )
        return prop_doc
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()
1153791
def setup(sphinx):
    
    create_auto_documentation()

    # add the py3status lexer (for code blocks)
    from sphinx.highlighting import lexers
    lexers['py3status'] = Py3statusLexer()

    # enable screenshot directive for dynamic screenshots
    sphinx.add_directive('screenshot', ScreenshotDirective)
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 ----')
433948
def env_updated(self,
                    kb_app,
                    sphinx_app: Sphinx,
                    sphinx_env: BuildEnvironment,
                    resource
                    ):
        

        docname = resource.docname
        srcdir = sphinx_app.env.srcdir
        source_imgpath = self.source_filename(docname, srcdir)

        # Copy the image to the Sphinx build directory
        build_dir = sphinx_app.outdir
        docpath = Path(docname)
        parent = docpath.parent
        target_imgpath = str(Path(build_dir, parent, self.filename))

        # Does the target dir exist yet in the build dir? Probably not. If
        # not, make it
        target_dir = Path(build_dir, parent)
        if not target_dir.exists():
            target_dir.mkdir(parents=True, exist_ok=True)

        shutil.copy(source_imgpath, target_imgpath)
1038643
def sphinx_extension(app, exception):
    ""
    if not app.builder.name in ("html", "dirhtml"):
        return

    if not app.config.sphinx_to_github:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Disabled, doing nothing.")
        return

    if exception:
        if app.config.sphinx_to_github_verbose:
            print("Sphinx-to-github: Exception raised in main build, doing nothing.")
        return

    dir_helper = DirHelper(
            os.path.isdir,
            os.listdir,
            os.walk,
            shutil.rmtree
            )

    file_helper = FileSystemHelper(
            open,
            os.path.join,
            shutil.move,
            os.path.exists
            )

    operations_factory = OperationsFactory()
    handler_factory = HandlerFactory()

    layout_factory = LayoutFactory(
            operations_factory,
            handler_factory,
            file_helper,
            dir_helper,
            app.config.sphinx_to_github_verbose,
            sys.stdout,
            force=True
            )

    layout = layout_factory.create_layout(app.outdir)
    layout.process()
165740
function buildDocs() {
  return Promise.resolve()
    .then(() => new Promise((resolve, reject) => {
      Metalsmith(__dirname)
        .source('./source/docs')
        .destination('./docs')
        .clean(true)
        .use(Markdown())
        .metadata({
          version: __version
        })
        .use(Layouts({
          engine: 'handlebars',
          directory: './source/layouts',
          rename: false
        }))
        // Update {{version}} in content since it's not processed with Handlebars
        .use((files, metalsmith, done) => {
          Object.keys(files).forEach((key) => {
            let file = files[key];

            file.contents = new Buffer(
              file.contents
                .toString()
                .replace(/\{\{version\}\}/g, __version)
            );
          });

          done();
        })
        .build((err) => {
          if(err) {
            reject(err);
            return;
          }
          console.log(Chalk.green('Docs generated! 📚'));

          resolve();
        });
    }));
}
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'])
1234786
def setup(app):
    """"""
    global _is_sphinx
    _is_sphinx = True
    app.add_config_value('no_underscore_emphasis', False, 'env')
    app.add_config_value('m2r_parse_relative_links', False, 'env')
    app.add_config_value('m2r_anonymous_references', False, 'env')
    app.add_config_value('m2r_disable_inline_math', False, 'env')
    app.add_source_parser('.md', M2RParser)
    app.add_directive('mdinclude', MdInclude)
    metadata = dict(
        version=__version__,
        parallel_read_safe=True,
        parallel_write_safe=True,
    )
    return metadata
390066
def setup():
    """"""
    install_requirements = ["attrdict"]
    if sys.version_info[:2] < (3, 4):
        install_requirements.append("pathlib")
    setup_requirements = ['six', 'setuptools>=17.1', 'setuptools_scm']
    needs_sphinx = {
        'build_sphinx',
        'docs',
        'upload_docs',
    }.intersection(sys.argv)
    if needs_sphinx:
        setup_requirements.append('sphinx')
    setuptools.setup(
        author="David Gidwani",
        author_email="david.gidwani@gmail.com",
        classifiers=[
            "Development Status :: 4 - Beta",
            "Intended Audience :: Developers",
            "License :: OSI Approved :: BSD License",
            "Operating System :: OS Independent",
            "Programming Language :: Python",
            "Programming Language :: Python :: 2",
            "Programming Language :: Python :: 2.7",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.3",
            "Programming Language :: Python :: 3.4",
            "Topic :: Software Development",
            "Topic :: Software Development :: Libraries :: Python Modules",
        ],
        description="Painless access to namespaced environment variables",
        download_url="https://github.com/darvid/biome/tarball/0.1",
        install_requires=install_requirements,
        keywords="conf config configuration environment",
        license="BSD",
        long_description=readme(),
        name="biome",
        package_dir={'': 'src'},
        packages=setuptools.find_packages('./src'),
        setup_requires=setup_requirements,
        tests_require=["pytest"],
        url="https://github.com/darvid/biome",
        use_scm_version=True,
    )
1210429
def _insert_common_sphinx_configs(c, *, project_name):
    
    c['project'] = project_name

    # The suffix(es) of source filenames.
    # You can specify multiple suffix as a list of string:
    c['source_suffix'] = '.rst'

    # The encoding of source files.
    c['source_encoding'] = 'utf-8-sig'

    # The master toctree document.
    c['master_doc'] = 'index'

    # Configure figure numbering
    c['numfig'] = True
    c['numfig_format'] = {'figure': 'Figure %s',
                          'table': 'Table %s',
                          'code-block': 'Listing %s'}

    # The reST default role (used for this markup: `text`)
    c['default_role'] = 'obj'

    # This is added to the end of RST files - a good place to put substitutions
    # to be used globally.
    c['rst_epilog'] = """
.. _Astropy: http://astropy.org
    """

    # A list of warning types to suppress arbitrary warning messages. We mean
    # to override directives in
    # astropy_helpers.sphinx.ext.autodoc_enhancements, thus need to ignore
    # those warning. This can be removed once the patch gets released in
    # upstream Sphinx (https://github.com/sphinx-doc/sphinx/pull/1843).
    # Suppress the warnings requires Sphinx v1.4.2
    c['suppress_warnings'] = ['app.add_directive', ]

    return c