def build_doc(self): # doc_dir = os.path.abspath(os.path.join(self._path.this, "doc")) doc_source_dir = os.path.abspath( os.path.join(self._path.this, "doc/source")) doc_build_dir = os.path.abspath( os.path.join(self._path.this, "doc/build")) self.mkdir(doc_dir) self.mkdir(doc_source_dir) self.mkdir(doc_build_dir) # doc_source prepare this_dir = os.path.abspath(self._path.this) # copy file # copy conf file to source dir confpy = os.path.join(_RUNTOOL_DIR_, "sphinx_singlehtml_conf.py") shutil.copy(confpy, os.path.join(doc_source_dir, "conf.py")) # copy fig folder if os.path.isdir(os.path.join(this_dir, "fig")): # delete fig in doc if os.path.isdir(os.path.join(doc_source_dir, "fig")): shutil.rmtree(os.path.join(doc_source_dir, "fig")) shutil.copytree(os.path.join(this_dir, "fig"), os.path.join(doc_source_dir, "fig")) generate_0_svg(os.path.join(doc_source_dir, "fig")) # revise rst revise_report_rst(this_dir, self._info, doc_source_dir) # command build_format = 'html' # singlehtml args = f"-b {build_format} " \ f"{doc_source_dir} {doc_build_dir}" sphinx_main(args.split())
def generate_man_pages(root_folder="", docs_src_path_rel_to_root="", docs_dest_path_rel_to_root="", doctree_temp_location_rel_to_sys_temp="", logger=None): """Generate man pages. Parameters ---------- root_folder : str, optional Path to the main folder that most paths should be relative to. docs_src_path_rel_to_root : str, optional Docs sources path relative to root_folder. docs_dest_path_rel_to_root : str, optional Built docs destination path relative to root_folder. doctree_temp_location_rel_to_sys_temp : str, optional Name of a temporary folder that will be used to create a path relative to the system temporary folder. logger : LogSystem The logger. """ logger.info(shell_utils.get_cli_separator("-"), date=False) logger.info("**Generating manual pages...**") doctree_temp_location = os.path.join(get_system_tempdir(), doctree_temp_location_rel_to_sys_temp) docs_sources_path = os.path.join(root_folder, docs_src_path_rel_to_root) man_pages_destination_path = os.path.join(root_folder, docs_dest_path_rel_to_root) sphinx_main(argv=[docs_sources_path, "-b", "man", "-d", doctree_temp_location, man_pages_destination_path])
def cmd(src, dest, clean): click.echo("Initializing workspace...") src_ = Path.cwd() / src dest_ = Path.cwd() / dest click.echo(f"Srouce: {src_}") click.echo(f"Output: {dest_}") if dest_.exists() and clean: shutil.rmtree(dest_) dest_.mkdir(parents=True, exist_ok=True) args = ["-b", "revealjs"] args += [str(src_), str(dest_)] sphinx_main(args)
def _run_test(): rmtree("doc/", ignore_errors=True) rmtree("doc_build/", ignore_errors=True) # [OPTIONS] -o <OUTPUT_PATH> <MODULE_PATH> [EXCLUDE_PATTERN, ...] # apidoc_main(["-h"]) ret = apidoc_main( ["--module-first", "--force", "--full", "--output-dir", "doc/", "."]) if ret != 0: raise AssertionError("apidoc_main failed with err %d" % ret) # -b buildername # -a If given, always write all output files. The default is to only write output files for new and changed source files. (This may not apply to all builders.) # -E Don’t use a saved environment (the structure caching all cross-references), but rebuild it completely. The default is to only read and parse source files that are new or have changed since the last run. # -C Don’t look for a configuration file; only take options via the -D option. # [OPTIONS] SOURCEDIR OUTPUTDIR [FILENAMES...] # sphinx_main(["-h"]) ret = sphinx_main([ "-b", "html", "-E", "-c", cwd, "doc/", "doc_build/", ]) if ret != 0: raise AssertionError("sphinx_main failed with err %d" % ret)
def setup_class(cls): """Run Sphinx against the dir adjacent to the testcase.""" cls.docs_dir = join(cls.this_dir(), 'source', 'docs') # -v for better tracebacks: if sphinx_main([ cls.docs_dir, '-b', cls.builder, '-v', '-E', join(cls.docs_dir, '_build') ]): raise RuntimeError('Sphinx build exploded.')
def setup_class(cls): """ Run Sphinx against the dir adjacent to the testcase """ cls.docs_dir = os.path.join( os.path.dirname(sys.modules[cls.__module__].__file__), 'src') with cd(cls.docs_dir): if sphinx_main(['.', '-b', 'html', '-E', '_build']): raise RuntimeError('Sphinx build error')
def _run_sphinx_build(self): if os.path.exists('docs/_build'): logger.info('Removing docs/_build') rmtree('docs/_build') # "sphinx-build -W docs/source docs/_build -b dirhtml" argv = ['-W', 'docs/source', 'docs/_build', '-b', 'dirhtml'] logger.info('Running: sphinx-build %s' % ' '.join(argv)) rcode = sphinx_main(argv) if rcode != 0: raise RuntimeError('Sphinx exited %d' % rcode)
def on_any_event(self, event): load_dotenv(override=True) build_path = os.environ.get('BUILD_PATH', '_build') doc_version = os.environ.get('DOC_VERSION', '') if not build_path.endswith('/'): build_path = build_path + '/' build_path += doc_version if event is None: print('initial build') else: print(f'event type: {event.event_type} path : {event.src_path}') if event is not None and (datetime.datetime.now() - self.last_modified < datetime.timedelta(seconds=2)): return else: self.last_modified = datetime.datetime.now() argv = ['-b', 'html', '-d', '/tmp/sphinx_doctree', '.', build_path] ensure_dir(build_path) delete_dir_contents(build_path) # argv = ['-b', 'html', '-d', f'{build_path}/doctrees', '.', f'{build_path}/html'] sphinx_main(argv) print('waiting for file changes. Press Ctrl+c to cancel.')
def build( show: bool = typer.Option( False, help="Open the docs in a browser after they have been built."), sphinx_args: List[str] = typer.Argument(None), ): """ Build the documentation. \f :param show: Open the docs in a browser after they have been built, defaults to False. :param sphinx_args: Any remaining arguments will be passed to the underlying ``sphinx_main()`` function that actually builds the docs. .. important:: If these arguments contain ``-`` or ``--`` flags, you will need to preface this argument list with ``--``. **Examples:** .. code-block:: shell :caption: Simple build $ docs build .. code-block:: shell :caption: Open the docs afterwards $ docs build --show .. code-block:: shell :caption: Perform a full rebuild with debug logging $ docs --log-level DEBUG build -- a """ # Check that both the schema and the sample component.yaml file are correct _validate_component_schema() built_path = pathlib.Path("docs") / "built" logger.info("Generating docs at %s", built_path.as_posix()) result = sphinx_main(["-b", "html", "docs/source", "docs/built"]) if not result: logger.success("Docs generated at %s", built_path.as_posix()) else: logger.error("Docs not generated") raise typer.Abort("Failed to build docs") if show: logger.notice("Opening generated docs in a browser") typer.launch((built_path / "index.html").as_posix())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2009-2020 Joshua Bronson. All Rights Reserved. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # First run all tests that pytest discovers. """Run all tests.""" import sys from functools import reduce from operator import or_ from pytest import main as pytest_main from sphinx.cmd.build import main as sphinx_main TEST_FUNCS = [ pytest_main, # pytest's doctest support doesn't support Sphinx extensions # (see https://www.sphinx-doc.org/en/latest/usage/extensions/doctest.html) # so †est the code in the Sphinx docs using Sphinx's own doctest support. lambda: sphinx_main('-b doctest -d docs/_build/doctrees docs docs/_build/doctest'.split()), ] sys.exit(reduce(or_, (f() for f in TEST_FUNCS)))
import os import shutil import sphinx if not sphinx.version_info >= (1, 8): raise ImportError('Need sphinx version 1.8') from sphinx.cmd.build import main as sphinx_main import sys os.chdir('../../../docs_sphinx') if os.path.exists('../docs'): shutil.rmtree('../docs') # Some code (e.g. the definition of preferences) might need to know that Brian # is used to build the documentation. The READTHEDOCS variable is set # on the readthedocs.io server automatically, so we reuse it here to signal # a documentation build os.environ['READTHEDOCS'] = 'True' sys.exit(sphinx_main(['-b', 'html', '.', '../docs']))
def generate_docs(root_folder="", docs_src_path_rel_to_root="", docs_dest_path_rel_to_root="docs", apidoc_paths_rel_to_root=[], doctree_temp_location_rel_to_sys_temp="", ignored_modules=[], generate_api_docs=False, update_inventories=False, force_clean_build=False, build_coverage=True, logger=None): """Build this application documentation. Parameters ---------- root_folder : str, optional Path to the main folder that most paths should be relative to. docs_src_path_rel_to_root : str, optional Docs sources path relative to root_folder. docs_dest_path_rel_to_root : str, optional Built docs destination path relative to root_folder. apidoc_paths_rel_to_root : list, optional A list of tuples. Each tuple of length two contains the path to the Python modules folder at index zero from which to extract docstrings and the path to where to store the generated rst files at index one. doctree_temp_location_rel_to_sys_temp : str, optional Name of a temporary folder that will be used to create a path relative to the system temporary folder. ignored_modules : list, optional A list of paths to Python modules relative to the root_folder. These are ignored modules whose docstrings are a mess and/or are incomplete. Because such docstrings will produce hundred of annoying Sphinx warnings. generate_api_docs : bool If False, do not extract docstrings from Python modules. update_inventories : bool, optional Whether to force the update of the inventory files. Inventory files will be updated anyway f they don't exist. force_clean_build : bool, optional Remove destination and doctrees directories before building the documentation. build_coverage : bool, optional If True, build Sphinx coverage documents. logger : LogSystem The logger. """ doctree_temp_location = os.path.join(get_system_tempdir(), doctree_temp_location_rel_to_sys_temp) docs_sources_path = os.path.join(root_folder, docs_src_path_rel_to_root) docs_destination_path = os.path.join(root_folder, docs_dest_path_rel_to_root) check_inventories_existence(update_inventories, docs_sources_path, logger) if force_clean_build: rmtree(doctree_temp_location, ignore_errors=True) rmtree(docs_destination_path, ignore_errors=True) if generate_api_docs: logger.info(shell_utils.get_cli_separator("-"), date=False) logger.info("**Generating automodule directives...**") # NOTE: Countermeasure for retarded new Sphinx behavior. # https://github.com/sphinx-doc/sphinx/issues/8664 # In short, I have to force down os.environ's throat the SPHINX_APIDOC_OPTIONS environment # variable because the options it contains aren't exposed to be passed as arguments. # By default, SPHINX_APIDOC_OPTIONS will contain the undoc-members option, overriding its # value without the undoc-members option will prevent apidoc from belching a trillion # warnings unnecessarily. os.environ["SPHINX_APIDOC_OPTIONS"] = "members,show-inheritance" from sphinx.ext.apidoc import main as apidoc_main commmon_args = ["--module-first", "--separate", "--private", "--force", "--suffix", "rst", "--output-dir"] for rel_source_path, rel_destination_path in apidoc_paths_rel_to_root: apidoc_destination_path = os.path.join(root_folder, rel_destination_path) if force_clean_build: rmtree(apidoc_destination_path, ignore_errors=True) apidoc_main(argv=commmon_args + [ apidoc_destination_path, os.path.join(root_folder, rel_source_path) ] + ignored_modules) try: if build_coverage: logger.info(shell_utils.get_cli_separator("-"), date=False) logger.info("**Building coverage data...**") sphinx_main(argv=[docs_sources_path, "-b", "coverage", "-d", doctree_temp_location, docs_sources_path + "/coverage"]) finally: logger.info(shell_utils.get_cli_separator("-"), date=False) logger.info("**Generating HTML documentation...**") sphinx_main(argv=[docs_sources_path, "-b", "html", "-d", doctree_temp_location, docs_destination_path])
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2009-2018 Joshua Bronson. All Rights Reserved. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # First run all tests that pytest discovers. from pytest import main as pytest_main exit_code = pytest_main() # pytest's doctest support doesn't support Sphinx extensions # (see https://www.sphinx-doc.org/en/latest/usage/extensions/doctest.html) # so †est the code in the Sphinx docs using Sphinx's own doctest support. from sphinx.cmd.build import main as sphinx_main exit_code = sphinx_main('-b doctest -d docs/_build/doctrees docs docs/_build/doctest'.split()) or exit_code exit(exit_code)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2009-2019 Joshua Bronson. All Rights Reserved. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # First run all tests that pytest discovers. """Run all tests.""" from functools import reduce from operator import or_ from pytest import main as pytest_main from sphinx.cmd.build import main as sphinx_main TEST_FUNCS = [ pytest_main, # pytest's doctest support doesn't support Sphinx extensions # (see https://www.sphinx-doc.org/en/latest/usage/extensions/doctest.html) # so †est the code in the Sphinx docs using Sphinx's own doctest support. lambda: sphinx_main('-b doctest -d docs/_build/doctrees docs docs/_build/doctest'.split()), ] exit(reduce(or_, (f() for f in TEST_FUNCS)))
import os import sys import webbrowser import sphinx from pkg_resources import parse_version if not parse_version(sphinx.__version__) >= parse_version('1.7'): raise ImportError('Need Sphinx >= 1.7') doc_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'docs')) output_dir = os.path.join(doc_dir, '_build', 'html') from sphinx.cmd.build import main as sphinx_main ret_val = sphinx_main(['-q', doc_dir, output_dir]) if ret_val != 0: print('Building documentation failed.') sys.exit(ret_val) print('Documentation built successfully') webbrowser.open('file://{}/index.html'.format(output_dir))